From 808a8bb2ee2fdf5f2bb4dccc640175cb700c9e90 Mon Sep 17 00:00:00 2001 From: Christian Date: Mon, 5 Jan 2026 11:50:14 +0100 Subject: [PATCH] Fix: Ambiguous column reference i link_tmodule_customers_to_hub (NOT EXISTS i stedet for NOT IN) --- .../055_fix_tmodule_customer_linking.sql | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 migrations/055_fix_tmodule_customer_linking.sql diff --git a/migrations/055_fix_tmodule_customer_linking.sql b/migrations/055_fix_tmodule_customer_linking.sql new file mode 100644 index 0000000..e62458f --- /dev/null +++ b/migrations/055_fix_tmodule_customer_linking.sql @@ -0,0 +1,65 @@ +-- ============================================================================ +-- Migration 055: Fix ambiguous column reference i link_tmodule_customers_to_hub +-- ============================================================================ +-- Retter SQL fejl hvor tmodule_id var ambiguous i subquery +-- ============================================================================ + +DROP FUNCTION IF EXISTS link_tmodule_customers_to_hub(); + +CREATE OR REPLACE FUNCTION link_tmodule_customers_to_hub() +RETURNS TABLE ( + tmodule_id INTEGER, + tmodule_name TEXT, + hub_id INTEGER, + hub_name TEXT, + action TEXT +) AS $$ +BEGIN + RETURN QUERY + WITH economic_matches AS ( + -- Prioriter economic_customer_number match (mest præcis) + SELECT + tc.id as tmodule_id, + tc.name::TEXT as tmodule_name, + c.id as hub_id, + c.name::TEXT as hub_name, + 'economic_number_match'::TEXT as action + FROM tmodule_customers tc + JOIN customers c ON tc.economic_customer_number = c.economic_customer_number + WHERE tc.hub_customer_id IS NULL + AND tc.economic_customer_number IS NOT NULL + AND c.economic_customer_number IS NOT NULL + ), + name_matches AS ( + -- Fallback til navn match for kunder uden economic nummer + SELECT + tc.id as tmodule_id, + tc.name::TEXT as tmodule_name, + c.id as hub_id, + c.name::TEXT as hub_name, + 'name_match'::TEXT as action + FROM tmodule_customers tc + JOIN customers c ON LOWER(TRIM(tc.name)) = LOWER(TRIM(c.name)) + WHERE tc.hub_customer_id IS NULL + AND NOT EXISTS (SELECT 1 FROM economic_matches em WHERE em.tmodule_id = tc.id) + ), + all_matches AS ( + SELECT * FROM economic_matches + UNION ALL + SELECT * FROM name_matches + ), + updates AS ( + -- Opdater tmodule_customers med hub_customer_id + UPDATE tmodule_customers tc + SET hub_customer_id = m.hub_id, + updated_at = CURRENT_TIMESTAMP + FROM all_matches m + WHERE tc.id = m.tmodule_id + RETURNING tc.id, tc.name::TEXT, m.hub_id, m.hub_name, m.action + ) + SELECT * FROM updates; +END; +$$ LANGUAGE plpgsql; + +COMMENT ON FUNCTION link_tmodule_customers_to_hub() IS +'Linker tmodule_customers til Hub customers via economic_customer_number (prioritet) eller navn match (fallback). Fixed ambiguous column reference.';