Smooth analytics page reloads
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 34s

This commit is contained in:
Cauê Faleiros
2026-06-23 14:45:21 -03:00
parent 335d231903
commit 7d60073757
7 changed files with 233 additions and 126 deletions

View File

@@ -17,31 +17,28 @@ const PRODUCT_NAME_SQL = `
const NORMALIZED_CUSTOMER_NAME_SQL = "NULLIF(LOWER(TRIM(regexp_replace(COALESCE(cliente_nome, ''), '\\s+', ' ', 'g'))), '')";
// Phone-less historical rows must follow the later known phone for the same client name.
const CUSTOMER_IDENTITY_CTE = `
WITH order_identity AS (
WITH customer_phone_by_name AS (
SELECT
orders.*,
${NORMALIZED_CUSTOMER_NAME_SQL} as normalized_customer_name
FROM orders
),
customer_phone_by_name AS (
SELECT
normalized_customer_name,
${NORMALIZED_CUSTOMER_NAME_SQL} as normalized_customer_name,
(ARRAY_AGG(NULLIF(cliente_fone, '') ORDER BY data_pedido_date DESC NULLS LAST, id DESC)
FILTER (WHERE NULLIF(cliente_fone, '') IS NOT NULL))[1] as canonical_phone
FROM order_identity
WHERE normalized_customer_name IS NOT NULL
)[1] as canonical_phone
FROM orders
WHERE NULLIF(cliente_fone, '') IS NOT NULL
AND ${NORMALIZED_CUSTOMER_NAME_SQL} IS NOT NULL
GROUP BY normalized_customer_name
),
identity_orders AS (
SELECT
order_identity.*,
orders.*,
${NORMALIZED_CUSTOMER_NAME_SQL} as normalized_customer_name,
COALESCE(
NULLIF(order_identity.cliente_fone, ''),
NULLIF(orders.cliente_fone, ''),
customer_phone_by_name.canonical_phone,
'name:' || COALESCE(NULLIF(order_identity.cliente_nome, ''), 'Cliente Desconhecido')
'name:' || COALESCE(NULLIF(orders.cliente_nome, ''), 'Cliente Desconhecido')
) as customer_key
FROM order_identity
LEFT JOIN customer_phone_by_name USING (normalized_customer_name)
FROM orders
LEFT JOIN customer_phone_by_name
ON customer_phone_by_name.normalized_customer_name = ${NORMALIZED_CUSTOMER_NAME_SQL}
)
`;
const CUSTOMER_KEY_SQL = 'customer_key';