-- Автоматизация бухгалтерии (модуль quickbooks_bookkeeper, сервис accounting_automation): собственные таблицы, префикс acc_. -- Описание колонок: docs/proposed/data_objects/accounting_automation/. Зеркала QuickBooks - qbo_* (миграции 031-032). -- Ручной разбор: acc_manual_review (общая очередь) + acc_<вид>_review, к каждой acc_<вид>_review_original (как записал автомат) -- и acc_<вид>_review_history (после завершения разбора). Триггеры ведут очередь и копию original; перенос в history и в итоговые таблицы делает сервис. alter table person add column if not exists role_code text; -- owner, ceo, cfo, accountant, construction_manager, employee, it -- ----------------------------------------------------------------- справочники create table if not exists acc_bank_account_projects ( qbo_account_id text primary key, project_customer_id text not null, note text ); create table if not exists acc_card_holders ( card_or_account text primary key, person_id uuid not null references person (id), note text ); -- ----------------------------------------------------------------- итоговые и рабочие create table if not exists acc_contracts ( id uuid primary key default gen_random_uuid(), vendor_name text not null, vendor_qbo_id text, project_customer_id text not null, jt_job_id text, stage text, total_amount numeric(14,2) not null, paid_amount numeric(14,2) not null default 0, drive_file_id text ); create table if not exists acc_invoices ( id uuid primary key, source_message_id text not null, drive_file_id text not null, vendor_name text not null, vendor_qbo_id text, invoice_number text, invoice_date date not null, amount numeric(14,2) not null, lines jsonb, project_customer_id text not null, jt_job_id text, contract_id uuid references acc_contracts (id), stage text not null default 'checking' check (stage in ('checking', 'to_approve', 'approved', 'rejected', 'wait', 'paid')), conclusion jsonb, decided_by text, decided_at timestamptz, paid_on date, qbo_txn_id text, created_at timestamptz not null default now() ); create index if not exists acc_invoices_vendor_idx on acc_invoices (vendor_qbo_id, amount); create table if not exists acc_receipts ( id uuid primary key default gen_random_uuid(), slack_ref text, drive_file_id text not null, vendor_name text, receipt_date date, amount numeric(14,2), project_customer_id text, sender_person_id uuid references person (id), feed_txn_id text, received_at timestamptz not null default now() ); create index if not exists acc_receipts_amount_idx on acc_receipts (amount, receipt_date); create table if not exists acc_insurance_certificates ( id uuid primary key default gen_random_uuid(), vendor_name text not null, vendor_qbo_id text, insurer text, valid_until date not null, source_message_id text, drive_file_id text not null ); create table if not exists acc_discrepancies ( id uuid primary key default gen_random_uuid(), kind text not null check (kind in ('invoice_vs_qbo', 'statement_vs_qbo')), invoice_id uuid references acc_invoices (id), qbo_ref text, description text not null, amount_diff numeric(14,2), found_at timestamptz not null default now(), closed_at timestamptz, closed_by text, resolution text ); create table if not exists acc_chargeback ( id uuid primary key default gen_random_uuid(), feed_txn_id text not null, reason text not null, bank text, file_by date, status text not null default 'collecting' check (status in ('collecting', 'filed', 'refunded', 'rejected', 'closed')), bank_decision text, created_at timestamptz not null default now() ); -- ----------------------------------------------------------------- ручной разбор create table if not exists acc_manual_review ( id uuid primary key default gen_random_uuid(), kind text not null check (kind in ('invoice', 'categorization', 'certificate', 'discrepancy', 'receipt_search', 'chargeback', 'invoice_approval')), ref_table text not null, ref_id text not null, assignee_role text not null default 'accountant', problem_highlight text, snoozed_until timestamptz, created_at timestamptz not null default now(), unique (ref_table, ref_id) ); create index if not exists acc_manual_review_role_idx on acc_manual_review (assignee_role); create table if not exists acc_invoices_review ( id uuid primary key default gen_random_uuid(), source_message_id text not null, drive_file_id text not null, vendor_name text, vendor_qbo_id text, invoice_number text, invoice_date date, amount numeric(14,2), lines jsonb, project_customer_id text, jt_job_id text, contract_id uuid references acc_contracts (id), problem_highlight text, done boolean not null default false, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create table if not exists acc_categorization_review ( feed_txn_id text primary key, run_id text not null, run_started_at timestamptz not null, suggestion jsonb, confidence smallint check (confidence between 0 and 100), problem_highlight text, done boolean not null default false, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create table if not exists acc_certificates_review ( id uuid primary key default gen_random_uuid(), vendor_name text not null, vendor_qbo_id text, certificate_id uuid references acc_insurance_certificates (id), expires_on date, problem_highlight text, request_sent_at timestamptz, done boolean not null default false, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create table if not exists acc_receipt_search ( id uuid primary key default gen_random_uuid(), feed_txn_id text not null, -- операция ленты (строка acc_categorization_review может уйти в _history, поиск чека остаётся) responsible_person_id uuid not null references person (id), escalation_level smallint not null default 0, last_asked_at timestamptz, answer text check (answer in ('receipt', 'personal', 'unknown')), closed_at timestamptz, resolution text ); -- Копии: _original (без ограничений, тот же ключ в колонке id/feed_txn_id) и _history (+ кто, когда, что изменено). create table if not exists acc_invoices_review_original (like acc_invoices_review including defaults); create table if not exists acc_categorization_review_original (like acc_categorization_review including defaults); create table if not exists acc_certificates_review_original (like acc_certificates_review including defaults); create table if not exists acc_invoices_review_history (like acc_invoices_review including defaults, closed_by text, closed_at timestamptz not null default now(), changed_fields jsonb); create table if not exists acc_categorization_review_history (like acc_categorization_review including defaults, closed_by text, closed_at timestamptz not null default now(), changed_fields jsonb); create table if not exists acc_certificates_review_history (like acc_certificates_review including defaults, closed_by text, closed_at timestamptz not null default now(), changed_fields jsonb); -- history хранит одну строку на закрытие: допускаем повтор ключа (операция может вернуться в разбор) create index if not exists acc_invoices_review_history_id_idx on acc_invoices_review_history (id); create index if not exists acc_categorization_review_history_id_idx on acc_categorization_review_history (feed_txn_id); create index if not exists acc_certificates_review_history_id_idx on acc_certificates_review_history (id); -- ----------------------------------------------------------------- триггеры create or replace function acc_touch_updated_at() returns trigger language plpgsql as $$ begin new.updated_at := now(); return new; end $$; -- После вставки в review: копия в _original и задача в acc_manual_review (kind, ключ колонки - аргументы триггера). create or replace function acc_review_inserted() returns trigger language plpgsql as $$ declare v_kind text := tg_argv[0]; v_key text := tg_argv[1]; j jsonb := to_jsonb(new); begin execute format('insert into %I select ($1).*', tg_table_name || '_original') using new; insert into acc_manual_review (kind, ref_table, ref_id, assignee_role, problem_highlight) values (v_kind, tg_table_name, j ->> v_key, 'accountant', j ->> 'problem_highlight') on conflict (ref_table, ref_id) do nothing; return new; end $$; -- Задача из очереди исчезает вместе со строкой review. create or replace function acc_review_deleted() returns trigger language plpgsql as $$ declare v_key text := tg_argv[0]; begin delete from acc_manual_review where ref_table = tg_table_name and ref_id = to_jsonb(old) ->> v_key; return old; end $$; -- Проблема, изменённая в review, обновляется и в очереди. create or replace function acc_review_problem_synced() returns trigger language plpgsql as $$ declare v_key text := tg_argv[0]; begin if new.problem_highlight is distinct from old.problem_highlight then update acc_manual_review set problem_highlight = new.problem_highlight where ref_table = tg_table_name and ref_id = to_jsonb(new) ->> v_key; end if; return new; end $$; do $$ declare r record; begin for r in select * from (values ('acc_invoices_review', 'invoice', 'id'), ('acc_categorization_review', 'categorization', 'feed_txn_id'), ('acc_certificates_review', 'certificate', 'id')) as t(tbl, kind, key) loop execute format('drop trigger if exists %I on %I', r.tbl || '_touch', r.tbl); execute format('create trigger %I before update on %I for each row execute function acc_touch_updated_at()', r.tbl || '_touch', r.tbl); execute format('drop trigger if exists %I on %I', r.tbl || '_ins', r.tbl); execute format('create trigger %I after insert on %I for each row execute function acc_review_inserted(%L, %L)', r.tbl || '_ins', r.tbl, r.kind, r.key); execute format('drop trigger if exists %I on %I', r.tbl || '_del', r.tbl); execute format('create trigger %I after delete on %I for each row execute function acc_review_deleted(%L)', r.tbl || '_del', r.tbl, r.key); execute format('drop trigger if exists %I on %I', r.tbl || '_sync', r.tbl); execute format('create trigger %I after update on %I for each row execute function acc_review_problem_synced(%L)', r.tbl || '_sync', r.tbl, r.key); end loop; end $$; -- ----------------------------------------------------------------- RLS (доступ - ролями postgres/Mathesar/MCP) alter table acc_bank_account_projects enable row level security; alter table acc_card_holders enable row level security; alter table acc_contracts enable row level security; alter table acc_invoices enable row level security; alter table acc_receipts enable row level security; alter table acc_insurance_certificates enable row level security; alter table acc_discrepancies enable row level security; alter table acc_chargeback enable row level security; alter table acc_manual_review enable row level security; alter table acc_invoices_review enable row level security; alter table acc_categorization_review enable row level security; alter table acc_certificates_review enable row level security; alter table acc_receipt_search enable row level security; alter table acc_invoices_review_original enable row level security; alter table acc_categorization_review_original enable row level security; alter table acc_certificates_review_original enable row level security; alter table acc_invoices_review_history enable row level security; alter table acc_categorization_review_history enable row level security; alter table acc_certificates_review_history enable row level security;