diff --git a/src/embed/lead-embed.controller.ts b/src/embed/lead-embed.controller.ts index ca6ac6c..961ba93 100644 --- a/src/embed/lead-embed.controller.ts +++ b/src/embed/lead-embed.controller.ts @@ -32,6 +32,20 @@ export class LeadEmbedController { throw new HttpException('Either contact phone or email is required', 400); } + // Look up campaign by name and link via relation if not already set by ID + if (!leadData.campaignId) { + const campaignName = body.utm_campaign || body.utmCampaign || body.campaign; + if (campaignName) { + const campaignId = await this.lookupCampaignByName(campaignName, authHeader); + if (campaignId) { + leadData.campaignId = campaignId; + this.logger.log(`Matched campaign "${campaignName}" → ${campaignId}`); + } else { + this.logger.warn(`No campaign found matching name: "${campaignName}"`); + } + } + } + const result = await this.platform.queryWithAuth( `mutation($data: LeadCreateInput!) { createLead(data: $data) { id } }`, { data: leadData }, @@ -109,6 +123,24 @@ export class LeadEmbedController { leadData.campaignId = body.campaign_id || body.campaignId; } + // UTM tracking fields + const utmCampaign = body.utm_campaign || body.utmCampaign || body.campaign; + if (utmCampaign) { + leadData.utmCampaign = utmCampaign; + } + if (body.utm_source || body.utmSource) { + leadData.utmSource = body.utm_source || body.utmSource; + } + if (body.utm_medium || body.utmMedium) { + leadData.utmMedium = body.utm_medium || body.utmMedium; + } + if (body.utm_content || body.utmContent) { + leadData.utmContent = body.utm_content || body.utmContent; + } + if (body.utm_term || body.utmTerm) { + leadData.utmTerm = body.utm_term || body.utmTerm; + } + return leadData; } @@ -131,6 +163,24 @@ export class LeadEmbedController { return serviceMap[type.toLowerCase()] || type; } + private async lookupCampaignByName(name: string, authHeader: string): Promise { + try { + const data = await this.platform.queryWithAuth( + `{ campaigns(first: 50) { edges { node { id campaignName } } } }`, + undefined, + authHeader, + ); + const campaigns = data?.campaigns?.edges?.map((e: any) => e.node) ?? []; + const match = campaigns.find( + (c: any) => (c.campaignName ?? '').toLowerCase() === name.toLowerCase(), + ); + return match?.id ?? null; + } catch (err: any) { + this.logger.warn(`Campaign lookup failed: ${err.message}`); + return null; + } + } + private async createInitialActivity( leadId: string, body: Record,