alter table if exists invoice_applications
  add column if not exists invoice_type text not null default 'normal_e_invoice',
  add column if not exists applicant_user_id uuid references users(id) on delete set null,
  add column if not exists remark text not null default '',
  add column if not exists admin_note text not null default '',
  add column if not exists issued_by text not null default '',
  add column if not exists file_uploaded_at timestamptz;

update invoice_applications
set
  invoice_type = coalesce(nullif(invoice_type, ''), 'normal_e_invoice'),
  provider = coalesce(nullif(provider, ''), 'manual');

create index if not exists idx_invoice_applications_status_created
  on invoice_applications(status, created_at desc);

create index if not exists idx_invoice_applications_order_active
  on invoice_applications(order_id, status, created_at desc);

update staff_roles
set
  description = '负责订单、支付、平台收入、专家分账、提现、发票和对账导出。',
  permissions = array[
    'order:read',
    'payment:read',
    'settlement:read',
    'invoice:read',
    'invoice:write',
    'reconcile:export',
    'coupon:read'
  ]::text[],
  updated_at = now()
where code = 'finance_admin';
