create table if not exists accounting.sales_receipts (
  id uuid primary key default gen_random_uuid(),
  company_id uuid not null references accounting.companies(id) on delete cascade,
  number text not null,
  receipt_date date not null default current_date,
  customer_name text,
  customer_address text,
  income_account_id uuid references accounting.accounts(id),
  deposit_account_id uuid references accounting.accounts(id),
  quantity numeric not null default 1,
  rate numeric not null default 0,
  total numeric not null default 0,
  memo text,
  transaction_id uuid references accounting.transactions(id) on delete set null,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create index if not exists idx_sales_receipts_company on accounting.sales_receipts(company_id);
create index if not exists idx_sales_receipts_txn on accounting.sales_receipts(transaction_id);

alter table accounting.sales_receipts enable row level security;

create policy "Accounting staff full access" on accounting.sales_receipts
  for all using (accounting.is_accounting_staff()) with check (accounting.is_accounting_staff());
create policy "Members CRUD sales_receipts" on accounting.sales_receipts
  for all using (accounting.is_company_member(company_id, auth.uid()))
  with check (accounting.is_company_member(company_id, auth.uid()));
create policy "Board view sales_receipts" on accounting.sales_receipts
  for select using (accounting.is_company_board_member(company_id));

create trigger trg_sales_receipts_updated
  before update on accounting.sales_receipts
  for each row execute function public.update_updated_at_column();

grant select, insert, update, delete on accounting.sales_receipts to authenticated;
grant all on accounting.sales_receipts to service_role;
