Exclude leads sharing a WhatsApp number from the automatic campaign queue

candidateQuery now blocks a lead whose WhatsApp number is shared by 2+
leads, unless a shared-number override exists. The inner correlated
subquery compares the bare other.whatsapp column (not normalizedSql())
against the outer row's two computed number forms so SQLite can use
idx_leads_whatsapp instead of a full table scan, keeping the 1.3M-row
perf test within budget.

Also updates the pre-existing 'persiste erro temporario e nao repete
equivalente' test: its two leads use 8/9-digit equivalent numbers,
which the new filter now blocks by default, so an override is added
to keep exercising the intended equivalent-number dedup behavior.
This commit is contained in:
Gustavo
2026-07-31 11:18:41 -03:00
parent 3d2144eefc
commit d85fb12991
2 changed files with 58 additions and 0 deletions
+9
View File
@@ -63,6 +63,15 @@ function candidateQuery(confirmed) {
SELECT 1 FROM outreach_opt_outs opt_out
WHERE opt_out.numero IN (${leadNumber}, ${leadEquivalent})
)
AND (
(SELECT COUNT(DISTINCT other.id) FROM leads other
WHERE other.whatsapp IN (${leadNumber}, ${leadEquivalent})
) < 2
OR EXISTS (
SELECT 1 FROM outreach_shared_number_overrides ov
WHERE ov.numero IN (${leadNumber}, ${leadEquivalent})
)
)
AND NOT EXISTS (
SELECT 1 FROM outreach_inbound_replies replies
WHERE replies.lead_id = leads.id