BEGIN; -- The old integration message was exposed as "Tekst 1" in e-conomic. -- Keep user-entered notes intact and only remove the exact ALSO system text. UPDATE ordre_drafts SET notes = NULL, updated_at = CURRENT_TIMESTAMP WHERE invoice_aggregate_key LIKE 'also-cloud-%' AND notes = 'Genereret fra ALSO Cloud Billing approval'; -- Add the source service period to existing, still-pending ALSO order lines. WITH rebuilt AS ( SELECT d.id, jsonb_agg( CASE WHEN line.item->>'source_type' = 'also_cloud' AND COALESCE(line.item->>'description', '') NOT LIKE '% · Periode: %' AND source.charge_interval ~ '^\s*\d{2}[./-]\d{2}[./-]\d{4}\s*-\s*\d{2}[./-]\d{2}[./-]\d{4}\s*$' THEN jsonb_set( line.item, '{description}', to_jsonb( COALESCE(line.item->>'description', 'Cloud abonnement') || ' · Periode: ' || replace(source.charge_interval, '/', '.') ) ) ELSE line.item END ORDER BY line.ordinality ) AS lines_json FROM ordre_drafts d CROSS JOIN LATERAL jsonb_array_elements(d.lines_json) WITH ORDINALITY AS line(item, ordinality) LEFT JOIN also_import_lines source ON source.id = CASE WHEN line.item->>'source_id' ~ '^\d+$' THEN (line.item->>'source_id')::bigint ELSE NULL END WHERE d.sync_status = 'pending' AND d.invoice_aggregate_key LIKE 'also-cloud-%' GROUP BY d.id ) UPDATE ordre_drafts d SET lines_json = rebuilt.lines_json, updated_at = CURRENT_TIMESTAMP FROM rebuilt WHERE d.id = rebuilt.id AND d.lines_json IS DISTINCT FROM rebuilt.lines_json; COMMIT;