-- Этап 2: chargeback к контракту подрядчика и fraud по карте (процессы «Chargeback к контракту подрядчика», «Подозрительные операции по карте (fraud)»). -- Расширяет acc_chargeback (только добавления; ограничение статуса заменяется более широким). Описание: data_objects/accounting_automation/acc_chargeback.md, acc_contracts.md. alter table acc_chargeback add column if not exists kind text not null default 'card_fraud'; alter table acc_chargeback alter column feed_txn_id drop not null; alter table acc_chargeback alter column reason drop not null; alter table acc_chargeback add column if not exists contract_id uuid references acc_contracts (id); alter table acc_chargeback add column if not exists defect_daily_log_id text; alter table acc_chargeback add column if not exists defect_daily_log_url text; alter table acc_chargeback add column if not exists defect_description text; alter table acc_chargeback add column if not exists extra_daily_logs text[] not null default '{}'; alter table acc_chargeback add column if not exists reported_by uuid references person (id); alter table acc_chargeback add column if not exists decided_by uuid references person (id); alter table acc_chargeback add column if not exists decided_at timestamptz; alter table acc_chargeback add column if not exists fix_vendor_name text; alter table acc_chargeback add column if not exists fix_invoice_id uuid references acc_invoices (id); alter table acc_chargeback add column if not exists retained_amount numeric(14,2); alter table acc_chargeback add column if not exists close_reason text; alter table acc_chargeback add column if not exists confirmed_by uuid references person (id); alter table acc_chargeback add column if not exists confirmed_at timestamptz; -- fraud: комплект документов (операция, чек или отметка «чека нет») и кто завёл alter table acc_chargeback add column if not exists kit jsonb; alter table acc_chargeback add column if not exists created_by uuid references person (id); alter table acc_chargeback drop constraint if exists acc_chargeback_status_check; alter table acc_chargeback drop constraint if exists acc_chargeback_kind_status_check; alter table acc_chargeback add constraint acc_chargeback_kind_status_check check ( (kind = 'card_fraud' and status in ('collecting', 'filed', 'refunded', 'rejected', 'closed')) or (kind = 'contract' and status in ('claimed', 'approved', 'fix_invoiced', 'applied', 'rejected', 'closed'))); alter table acc_chargeback drop constraint if exists acc_chargeback_kind_fields_check; alter table acc_chargeback add constraint acc_chargeback_kind_fields_check check ( (kind = 'card_fraud' and feed_txn_id is not null) or (kind = 'contract' and contract_id is not null)); -- Один Daily Log - один дефект: повторный запрос ассистента менеджера не создаёт дубль. create unique index if not exists acc_chargeback_daily_log_uq on acc_chargeback (defect_daily_log_id) where defect_daily_log_id is not null; create index if not exists acc_chargeback_contract_idx on acc_chargeback (contract_id); create index if not exists acc_chargeback_fraud_txn_idx on acc_chargeback (feed_txn_id) where kind = 'card_fraud'; alter table acc_contracts add column if not exists retained_amount numeric(14,2) not null default 0; -- Пересчёт удержаний контракта: сумма retained_amount строк contract в статусе applied; строка, закрытая после подтверждения суммы -- (confirmed_at заполнено), продолжает учитываться, иначе закрытие в шаге 12 вернуло бы остаток. create or replace function acc_contract_retained_recalc(p_contract uuid) returns void language plpgsql as $$ declare v numeric(14,2); begin if p_contract is null then return; end if; select coalesce(sum(retained_amount), 0) into v from acc_chargeback where contract_id = p_contract and kind = 'contract' and (status = 'applied' or (status = 'closed' and confirmed_at is not null)); update acc_contracts set retained_amount = v where id = p_contract and retained_amount is distinct from v; end $$; create or replace function acc_chargeback_after_change() returns trigger language plpgsql as $$ begin if tg_op <> 'DELETE' then perform acc_contract_retained_recalc(new.contract_id); if new.status = 'closed' then delete from acc_manual_review where ref_table = 'acc_chargeback' and ref_id = new.id::text; end if; end if; if tg_op = 'DELETE' or (tg_op = 'UPDATE' and old.contract_id is distinct from new.contract_id) then perform acc_contract_retained_recalc(old.contract_id); end if; return null; end $$; drop trigger if exists acc_chargeback_change on acc_chargeback; create trigger acc_chargeback_change after insert or update or delete on acc_chargeback for each row execute function acc_chargeback_after_change(); -- Шаг 12: остаток к оплате (total - retained - paid) исчерпан - строки applied закрываются. create or replace function acc_contract_settle() returns trigger language plpgsql as $$ begin if new.total_amount - new.retained_amount - new.paid_amount <= 0 then update acc_chargeback set status = 'closed', close_reason = coalesce(close_reason, 'остаток по контракту оплачен') where contract_id = new.id and kind = 'contract' and status = 'applied'; end if; return null; end $$; drop trigger if exists acc_contract_settle_trg on acc_contracts; create trigger acc_contract_settle_trg after update of total_amount, paid_amount, retained_amount on acc_contracts for each row execute function acc_contract_settle();