-- Orders are written before calling WeChat. Keep them when a user or -- organization is deleted so paid money cannot lose its audit trail. create table if not exists public.payment_orders ( id text primary key check (length(id) between 1 and 32 and id ~ '^[A-Za-z0-9_-]+$'), organization_id text not null references public.platform_organizations(id) on delete restrict, account_id text not null references public.platform_users(id) on delete restrict, request_key text not null check (length(request_key) between 1 and 64 and request_key ~ '^[A-Za-z0-9_-]+$'), mch_id text not null check (length(mch_id) between 1 and 64), app_id text not null check (length(app_id) between 1 and 64), amount_fen bigint not null check (amount_fen between 1 and 1000000), currency text not null check (currency = 'CNY'), status text not null default 'pending' check (status in ('pending', 'paid', 'closed')), code_url text, transaction_id text, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), expires_at timestamptz not null, paid_at timestamptz, constraint payment_orders_paid_fields_check check ( (status = 'paid' and transaction_id is not null and length(transaction_id) > 0 and paid_at is not null) or (status <> 'paid' and transaction_id is null and paid_at is null) ), constraint payment_orders_expiry_check check (expires_at > created_at), constraint payment_orders_org_request_unique unique (organization_id, request_key) ); create unique index if not exists payment_orders_provider_transaction_unique on public.payment_orders(mch_id, transaction_id) where transaction_id is not null; create index if not exists payment_orders_org_created_idx on public.payment_orders(organization_id, created_at desc); create index if not exists payment_orders_pending_check_idx on public.payment_orders(updated_at, created_at) where status = 'pending';