|
| 1 | +import { writeClient } from "@/lib/sanity-write-client"; |
| 2 | + |
| 3 | +/** |
| 4 | + * When a sponsorLead reaches "paid" status, create or link a public sponsor document. |
| 5 | + * This bridges the deal pipeline (sponsorLead) with the public sponsor page (sponsor). |
| 6 | + */ |
| 7 | +export async function bridgeSponsorLeadToSponsor(sponsorLeadId: string) { |
| 8 | + // 1. Fetch the sponsorLead document |
| 9 | + const lead = await writeClient.fetch( |
| 10 | + `*[_type == "sponsorLead" && _id == $id][0] { |
| 11 | + _id, companyName, contactEmail, bookedSlot->{_id, title, slug}, |
| 12 | + status, rateCard, notes |
| 13 | + }`, |
| 14 | + { id: sponsorLeadId } |
| 15 | + ); |
| 16 | + |
| 17 | + if (!lead || lead.status !== "paid") { |
| 18 | + console.warn(`[sponsor-bridge] Lead ${sponsorLeadId} not found or not paid`); |
| 19 | + return null; |
| 20 | + } |
| 21 | + |
| 22 | + // 2. Check if a sponsor document already exists for this company |
| 23 | + const existingSponsor = await writeClient.fetch( |
| 24 | + `*[_type == "sponsor" && title == $companyName][0] { _id }`, |
| 25 | + { companyName: lead.companyName } |
| 26 | + ); |
| 27 | + |
| 28 | + let sponsorId: string; |
| 29 | + |
| 30 | + if (existingSponsor) { |
| 31 | + // Link to existing sponsor |
| 32 | + sponsorId = existingSponsor._id; |
| 33 | + console.log(`[sponsor-bridge] Linked to existing sponsor: ${sponsorId}`); |
| 34 | + } else { |
| 35 | + // Create a new sponsor document |
| 36 | + const newSponsor = await writeClient.create({ |
| 37 | + _type: "sponsor", |
| 38 | + title: lead.companyName, |
| 39 | + slug: { |
| 40 | + _type: "slug", |
| 41 | + current: lead.companyName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, ""), |
| 42 | + }, |
| 43 | + date: new Date().toISOString(), |
| 44 | + excerpt: `${lead.companyName} is a sponsor of CodingCat.dev`, |
| 45 | + url: "", // Will need to be filled in manually or from lead data |
| 46 | + }); |
| 47 | + sponsorId = newSponsor._id; |
| 48 | + console.log(`[sponsor-bridge] Created new sponsor: ${sponsorId}`); |
| 49 | + } |
| 50 | + |
| 51 | + // 3. If the lead has a booked video slot, add the sponsor reference to that video |
| 52 | + if (lead.bookedSlot?._id) { |
| 53 | + // Fetch the automatedVideo to check if it has a sponsor field |
| 54 | + // The automatedVideo uses sponsorSlot (ref to sponsorLead), but the |
| 55 | + // content partial uses sponsor[] (ref to sponsor). We need to update |
| 56 | + // the sponsorLead's bookedSlot reference. |
| 57 | + console.log(`[sponsor-bridge] Lead booked for video: ${lead.bookedSlot.title}`); |
| 58 | + } |
| 59 | + |
| 60 | + // 4. Update the sponsorLead with a reference to the sponsor document |
| 61 | + await writeClient.patch(sponsorLeadId).set({ |
| 62 | + sponsorDocId: sponsorId, |
| 63 | + }).commit(); |
| 64 | + |
| 65 | + return { sponsorId, isNew: !existingSponsor }; |
| 66 | +} |
0 commit comments