-- Перенос текущего реестра Анастасии (old_invoices, лист «KH BUILD») в рабочую таблицу acc_invoices, чтобы WebUI acc_invoices показывал продуктивные данные. -- Повторный запуск безопасен (по conclusion->>'old_id'). Откат: delete from acc_invoices where conclusion->>'imported_from' = 'old_invoices'. -- conclusion заполнен намеренно: invoice-check такие строки не берёт. Файлов инвойсов в архиве нет (drive_file_id пуст), поэтому у открытых строк будет ошибка «нет файла». begin; create temp table _imp on commit drop as select gen_random_uuid() as new_id, o.*, case o.paid_status when 'paid' then 'paid' when 'approved' then 'approved' when 'waiting' then 'wait' else 'checking' end as new_stage from old_invoices o where o.source_sheet = 'KH BUILD' and o.invoice_date is not null and coalesce(btrim(o.vendor_name), '') <> '' and not exists (select 1 from acc_invoices a where a.conclusion ->> 'old_id' = o.id::text); insert into acc_invoices (id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, project_customer_id, stage, conclusion, decided_by, paid_on, pay_method, is_approved, llm_result, manual_result, is_paid_manual, paid_manual_at, created_at) select new_id, vendor_name, vendor_qbo_id, nullif(btrim(invoice_number_raw), ''), invoice_date, amount, project_customer_id, new_stage, jsonb_build_object('imported_from', 'old_invoices', 'old_id', id::text, 'paid_raw', paid_raw, 'note', note, 'project_text', project_text, 'excel_row', source_row), case when new_stage in ('paid', 'approved') then 'excel' end, case when new_stage = 'paid' then paid_on end, pay_method, new_stage in ('paid', 'approved'), case when new_stage in ('paid', 'approved') then 'OK' end, case when new_stage in ('paid', 'approved') then 'OK' when paid_status in ('not_approved', 'waiting') then null else 'Статус из Excel не определён: ' || coalesce(nullif(btrim(paid_raw), ''), '(пусто)') end, new_stage = 'paid' and paid_on is not null, case when new_stage = 'paid' then paid_on::timestamptz end, coalesce(invoice_date::timestamptz, now()) from _imp; insert into acc_invoices_details (invoice_id, line_no, description, amount) select new_id, 1, purpose, amount from _imp where nullif(btrim(purpose), '') is not null; select new_stage, count(*) from _imp group by 1 order by 1; commit;