92 lines
6.1 KiB
SQL
92 lines
6.1 KiB
SQL
-- Сервис acc_invoices (WebUI и бэкенд платёжного процесса): расширение acc_invoices, строки инвойса и контрактов, согласования, роли.
|
||
-- Описание: docs/proposed/input_specs/payment_and_invoices.md, docs/proposed/modules/acc_invoices.md. Только добавления и ослабление NOT NULL (задания accounting_automation работают как раньше).
|
||
|
||
alter table person add column if not exists is_agent boolean not null default false; -- агент, разбирающий почту (author инвойсов из письма)
|
||
|
||
-- роли сотрудников платёжного процесса (у человека может быть несколько); если записей нет, берётся person.role_code
|
||
create table if not exists user_roles (
|
||
person_id uuid not null references person (id) on delete cascade,
|
||
role text not null check (role in ('accountant', 'cfo')),
|
||
primary key (person_id, role)
|
||
);
|
||
alter table user_roles enable row level security;
|
||
|
||
-- инвойс может быть создан в WebUI (черновик) без письма и файла
|
||
alter table acc_invoices alter column source_message_id drop not null;
|
||
alter table acc_invoices alter column drive_file_id drop not null;
|
||
alter table acc_invoices alter column project_customer_id drop not null;
|
||
|
||
alter table acc_invoices add column if not exists author uuid references person (id);
|
||
alter table acc_invoices add column if not exists target_employee uuid references person (id);
|
||
alter table acc_invoices add column if not exists is_draft boolean not null default false;
|
||
alter table acc_invoices add column if not exists sent_to_bank timestamptz;
|
||
alter table acc_invoices add column if not exists review_date date;
|
||
alter table acc_invoices add column if not exists cancelled boolean not null default false;
|
||
alter table acc_invoices add column if not exists llm_result text;
|
||
alter table acc_invoices add column if not exists manual_result text;
|
||
alter table acc_invoices add column if not exists is_approved boolean not null default false;
|
||
alter table acc_invoices add column if not exists invoice_url text;
|
||
alter table acc_invoices add column if not exists payment_url text;
|
||
alter table acc_invoices add column if not exists need_employee_refund boolean not null default false;
|
||
alter table acc_invoices add column if not exists is_employee_refunded boolean not null default false;
|
||
-- «оплачен» по отметке сотрудника (второй флаг фильтра «Оплачены»; первый - paid_on из QuickBooks, ТЗ называет его payed_date_qb)
|
||
alter table acc_invoices add column if not exists is_paid_manual boolean not null default false;
|
||
alter table acc_invoices add column if not exists paid_manual_at timestamptz; -- когда поставлена отметка «оплачен»: через сутки без QuickBooks - ошибка
|
||
alter table acc_invoices add column if not exists updated_at timestamptz not null default now();
|
||
|
||
-- прежние записи: перенос смысла в новые поля (повторный запуск безопасен)
|
||
update acc_invoices set invoice_url = 'https://drive.google.com/file/d/' || drive_file_id || '/view'
|
||
where invoice_url is null and drive_file_id is not null;
|
||
update acc_invoices set is_approved = true where stage in ('approved', 'paid') and not is_approved;
|
||
update acc_invoices set is_paid_manual = true, paid_manual_at = paid_on::timestamptz where paid_on is not null and not is_paid_manual;
|
||
update acc_invoices
|
||
set llm_result = case when jsonb_array_length(coalesce(conclusion -> 'problems', '[]'::jsonb)) = 0 then 'OK'
|
||
else (select string_agg(p, '; ') from jsonb_array_elements_text(conclusion -> 'problems') p) end
|
||
where conclusion is not null and llm_result is null;
|
||
update acc_invoices set cancelled = true where stage = 'rejected' and not cancelled;
|
||
|
||
create index if not exists acc_invoices_flags_idx on acc_invoices (is_draft, cancelled, is_approved);
|
||
|
||
create table if not exists acc_invoices_details (
|
||
id uuid primary key default gen_random_uuid(),
|
||
invoice_id uuid not null references acc_invoices (id) on delete cascade,
|
||
line_no int not null,
|
||
description text,
|
||
quantity numeric(14,4),
|
||
unit_price numeric(14,4),
|
||
amount numeric(14,2) not null,
|
||
category_qbo_id text, -- счёт/категория QuickBooks (qbo_account.id)
|
||
category_name text,
|
||
contract_detail_id uuid, -- строка контракта (FK ниже, после создания acc_contract_details)
|
||
unique (invoice_id, line_no)
|
||
);
|
||
|
||
create table if not exists acc_contract_details (
|
||
id uuid primary key default gen_random_uuid(),
|
||
contract_id uuid not null references acc_contracts (id) on delete cascade,
|
||
line_no int not null,
|
||
description text,
|
||
amount numeric(14,2) not null,
|
||
unique (contract_id, line_no)
|
||
);
|
||
do $$ begin
|
||
alter table acc_invoices_details add constraint acc_invoices_details_contract_detail_fk foreign key (contract_detail_id) references acc_contract_details (id) on delete set null;
|
||
exception when duplicate_object then null; end $$;
|
||
|
||
create table if not exists acc_invoices_approves (
|
||
id uuid primary key default gen_random_uuid(),
|
||
invoice_id uuid not null references acc_invoices (id) on delete cascade,
|
||
approver_person_id uuid not null references person (id),
|
||
decision text not null default 'pending' check (decision in ('pending', 'approved', 'rejected')),
|
||
comment text,
|
||
requested_by uuid references person (id),
|
||
requested_at timestamptz not null default now(),
|
||
decided_at timestamptz,
|
||
unique (invoice_id, approver_person_id)
|
||
);
|
||
create index if not exists acc_invoices_approves_inv_idx on acc_invoices_approves (invoice_id);
|
||
|
||
alter table acc_invoices_details enable row level security;
|
||
alter table acc_contract_details enable row level security;
|
||
alter table acc_invoices_approves enable row level security;
|