@aglyn/plugins-marketing 1.0.0-beta.199 → 1.0.0-beta.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +15 -15
  2. package/src/lib/components/campaign-detail-card.js +106 -36
  3. package/src/lib/components/campaign-detail-card.js.map +1 -1
  4. package/src/lib/components/campaign-queries.d.ts +11 -0
  5. package/src/lib/components/campaign-queries.js +13 -0
  6. package/src/lib/components/campaign-queries.js.map +1 -1
  7. package/src/lib/components/campaigns-card.d.ts +8 -6
  8. package/src/lib/components/campaigns-card.js +283 -125
  9. package/src/lib/components/campaigns-card.js.map +1 -1
  10. package/src/lib/components/emails-list-card.d.ts +11 -15
  11. package/src/lib/components/emails-list-card.js +139 -142
  12. package/src/lib/components/emails-list-card.js.map +1 -1
  13. package/src/lib/components/host-experiments-card.component.js +107 -78
  14. package/src/lib/components/host-experiments-card.component.js.map +1 -1
  15. package/src/lib/components/org-experiments-card.js +7 -3
  16. package/src/lib/components/org-experiments-card.js.map +1 -1
  17. package/src/lib/model/campaign-list-query.d.ts +99 -0
  18. package/src/lib/model/campaign-list-query.js +373 -0
  19. package/src/lib/model/campaign-list-query.js.map +1 -0
  20. package/src/lib/model/experiment-list-query.d.ts +22 -0
  21. package/src/lib/model/experiment-list-query.js +85 -0
  22. package/src/lib/model/experiment-list-query.js.map +1 -0
  23. package/src/lib/server/campaign-manage.d.ts +1 -1
  24. package/src/lib/server/campaign-manage.js +30 -18
  25. package/src/lib/server/campaign-manage.js.map +1 -1
  26. package/src/lib/server/campaign-send.d.ts +7 -0
  27. package/src/lib/server/campaign-send.js +17 -5
  28. package/src/lib/server/campaign-send.js.map +1 -1
  29. package/src/lib/server/email-events.js +3 -1
  30. package/src/lib/server/email-events.js.map +1 -1
  31. package/src/lib/components/email-send-filter.d.ts +0 -32
  32. package/src/lib/components/email-send-filter.js +0 -55
  33. package/src/lib/components/email-send-filter.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-manage.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * TAKING SOMETHING AWAY: a campaign container, and an abandoned draft.\n *\n * Both are removals, and neither may take a delivered message with it. That\n * is the whole reason this file is small and the comments are long.\n *\n * ## Why these two are not client writes\n *\n * The console creates and edits a campaign CONTAINER with the client SDK —\n * `orgs/{orgId}/emailCampaigns` is client-writable, because a container holds\n * no counter, no consent record and no entitlement input. It is not\n * client-DELETABLE: removing one has to detach everything that names it\n * first, across every site in the organization, which no rule can express.\n *\n * The SEND collection is the opposite: `orgs/{orgId}/campaigns` is excluded\n * from client create, update AND delete, because each document is the record\n * of what a merchant mailed and to whom they were allowed to mail it. Both\n * operations here have to touch it — one to detach sends from the container\n * being removed, the other to remove a draft outright — so both run on the\n * Admin SDK behind a role check.\n *\n * ## Two doors: a site, and the organization\n *\n * A campaign belongs to the organization and may be placed on several of its\n * sites. A request from a SITE hub names the site (`hostId`) and is\n * authorized by the caller's role there, as the send route is — and it acts\n * only on what that site holds: a send sent as another site, or a campaign\n * not placed on this one, answers as if it did not exist. A request from the\n * ORGANIZATION hub names the org (`orgId`) and no site, and is authorized by\n * the caller's org-wide membership; for an email it acts in the name of the\n * site the email is sent as.\n *\n * ## What deleting a campaign MEANS\n *\n * The container goes; every email inside it stays, and reads afterwards as a\n * single send.\n *\n * It cannot mean anything else. A send id is cited by mail already delivered\n * — every unsubscribe footer carries `cid={sendId}` inside its own HMAC, and\n * `/marketing/campaigns/{sendId}` is a URL merchants paste into their own\n * messages — so deleting a container that destroyed its sends would break\n * opt-out links that must go on resolving forever, which is a compliance\n * failure rather than a broken page.\n *\n * Nor may the sends simply be left pointing at a container that is gone.\n * `campaignListRows` groups sends by the container they name and draws one\n * row per container; a send naming a container that no longer exists is in\n * neither half of that — not a container row, and not an orphan the list\n * adopts — so it would vanish from the campaigns table while remaining\n * perfectly deliverable. Detaching is what puts it back in the list, as the\n * \"Single send\" the product already models and the table already draws.\n *\n * Deleting a campaign is therefore NOT a way to stop its mail. A scheduled\n * email inside it keeps its send time and still goes out, because a\n * container is a grouping and cancelling somebody's mail is `cancel`'s job.\n * The console says so before it asks.\n *\n * ## The same rule for everything else the campaign held\n *\n * A campaign also groups forms, screens and contacts, each of which names it\n * from its OWN document. They are detached on exactly the argument the sends\n * are: a form left naming a container nobody can read has not been freed, it\n * has been made unreadable — its page draws a dead id where a campaign name\n * belongs, and the campaigns table can no longer find it. The record itself\n * is never touched. Deleting a campaign deletes a campaign.\n */\n\n/*\n * The MODULE, not the barrel. `@aglyn/tenant-data-admin`'s index reaches\n * `render-cache`, which imports `next/cache` and therefore the whole Next\n * server pipeline — everything this file needs from the admin SDK is one\n * default export, and taking it from the leaf keeps that pipeline out of the\n * graph.\n */\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { logResourceDuplicated } from '@aglyn/tenant-data-admin/server/duplicate-activity'\nimport {\n DUPLICATE_BUSY_MESSAGE,\n duplicateDisplayName,\n uniqueDuplicateName,\n} from '@aglyn/aglyn/app-utils/duplicate-resource'\nimport { claimAttempt, createResourceUid } from '@aglyn/aglyn/server'\n/*\n * The MODULES again, for the same reason: the org and membership reads here\n * are what the contact pass and the organization door need, and taking them\n * from `@aglyn/tenant-data-admin`'s index would pull the whole Next server\n * pipeline back into this file's graph.\n */\nimport {\n consentGroupForSite,\n getOrgDoc,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport {\n CAMPAIGN_MEMBER_HOST_COLLECTIONS,\n CAMPAIGN_MEMBERSHIP_FIELD,\n contactCampaignFieldPath,\n isOrgWideMember,\n type AglynOrgMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n} from '@aglyn/aglyn/server'\nimport {\n CAMPAIGN_SEND_CONTAINER_FIELD,\n CAMPAIGN_SEND_HOST_FIELD,\n campaignPlacedOnHost,\n campaignSiteIds,\n campaignVisibleTo,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport {\n campaignSendSiteStamp,\n orgCampaignSends,\n orgEmailCampaigns,\n sendHostId,\n sendIsOnHost,\n} from './campaign-org-refs'\nimport { SCREEN_KIND_EMAIL } from '@aglyn/aglyn/app-utils/screen-route'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { runPluginMembershipDetachers } from '@aglyn/aglyn/plugin-manager/plugin-membership-detach'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\n\n/**\n * Sends detached in one write.\n *\n * Under Firestore's 500-operation batch limit with room to spare rather than\n * at it: a batch that is refused for being one over has done nothing, and the\n * margin costs one extra round trip on a campaign of exactly this size.\n */\nconst DETACH_BATCH = 400\n\n/**\n * How many batches one request will run.\n *\n * A ceiling on the REQUEST, not on the campaign. The loop below terminates on\n * its own — each pass clears the very field it queries on, so a detached send\n * is not returned again — but a request that runs unbounded is a request that\n * eventually exceeds the platform's own timeout with no idea how far it got.\n *\n * Stopping early is safe and is why this is a ceiling rather than a refusal\n * up front: detaching is idempotent and partial progress is a consistent\n * state — the sends already detached read as single sends, the rest still\n * read under the campaign — so the answer to hitting it is to ask again.\n */\nconst DETACH_PASSES = 25\n\n/**\n * The most sites one deletion walks for members.\n *\n * A campaign is the organization's, so its forms, screens and consent-group\n * facets may be on any of its sites. An organization past this has more\n * sites than one request should sweep, and the deletion refuses rather than\n * removing a container some sites' records would still name.\n */\nconst ORG_SITES_MAX = 200\n\n/** What one `campaigns/manage` call answered with. */\ninterface ManageResult {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Clears {@link CAMPAIGN_SEND_CONTAINER_FIELD} from every send in a campaign.\n *\n * Equality on one field with a `limit` — no `orderBy` — which Firestore's\n * automatic single-field index serves. Ordering would need a composite index\n * for a walk whose order does not matter: every match is being written, so\n * which order they come back in cannot change the outcome.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachSends(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await orgCampaignSends(firestore, orgId)\n .where(CAMPAIGN_SEND_CONTAINER_FIELD, '==', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const send of page.docs) {\n /*\n * The FIELD is removed, not set to an empty string. `campaignListRows`\n * adopts a send whose container id is falsy, so an empty string would\n * work by accident today — but the field is also what the campaign\n * detail page's `where` clause matches, and an equality query on `''`\n * is a different query from the absence the pre-container sends have.\n * One shape for \"belongs to no campaign\" is what keeps those two\n * readers agreeing.\n */\n batch.update(send.ref, {\n [CAMPAIGN_SEND_CONTAINER_FIELD]:\n firebaseAdmin.firestore.FieldValue.delete(),\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Clears one campaign id out of a membership array, wherever it is held.\n *\n * The same walk {@link detachSends} makes, over an ARRAY field rather than a\n * scalar one: `array-contains` matches on Firestore's automatic single-field\n * index, and `arrayRemove` takes out the one id without touching the other\n * campaigns a form or a screen is in. That is the whole reason the membership\n * is an array here and a `FieldValue.delete()` on a send — a send is in one\n * campaign and a landing page is in several, so removing one must not be\n * removing all of them.\n *\n * `query` rather than a collection ref, because the contact pass hands in a\n * path this file cannot build for itself.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachMembership(\n firestore: FirebaseFirestore.Firestore,\n collectionRef: FirebaseFirestore.CollectionReference,\n fieldPath: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await collectionRef\n .where(fieldPath, 'array-contains', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const member of page.docs) {\n batch.update(member.ref, {\n [fieldPath]: firebaseAdmin.firestore.FieldValue.arrayRemove(campaignId),\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Every site of the organization, by id — the sites a campaign's members may\n * be on. One equality on the `hostIndex` mirror, the same document\n * `resolveOrgIdForHost` reads to put a site in an org.\n *\n * @returns the ids, and whether the org has more than {@link ORG_SITES_MAX}.\n */\nasync function orgSiteIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<{ hostIds: string[]; truncated: boolean }> {\n const page = await firestore\n .collection('hostIndex')\n .where('orgId', '==', orgId)\n .limit(ORG_SITES_MAX + 1)\n .get()\n const hostIds = page.docs.map((doc) => String(doc.id))\n return {\n hostIds: hostIds.slice(0, ORG_SITES_MAX),\n truncated: hostIds.length > ORG_SITES_MAX,\n }\n}\n\n/**\n * Clears the campaign off every form, screen, lead and contact holding it,\n * on every site of the organization, and then off every record a plugin\n * keeps about it (AGL-3254).\n *\n * ## Why the campaign is not simply deleted over the top of them\n *\n * A campaign that went away leaving members naming it is the same failure the\n * send detach exists to prevent, one collection over: the campaign's own page\n * finds its forms and screens with `array-contains`, and a form still naming\n * a container nobody can read is in neither half of that — not a member of\n * any campaign the console can draw, and not free of one either. Its own page\n * would render the dead id as a chip with no name.\n *\n * ## Every site, not the one that asked\n *\n * The campaign is the organization's, and a site it has since been taken off\n * may still hold forms and screens filed under it. So the walk covers every\n * site in the org regardless of which door the deletion came through.\n *\n * ## Leads and contacts are reached on the organization\n *\n * A lead lives at `orgs/{orgId}/leads` and carries the field at the top of\n * its document, like a form. The site `leads` collection is walked as well,\n * as part of each site's own collections: records captured before leads\n * moved to the org are still read there.\n *\n * A contact lives at `orgs/{orgId}/contacts` and is shared by every site, so\n * the membership sits inside a consent group's facet rather than at the top\n * of the document. The field PATH is therefore the scope, and the walk runs\n * once per distinct group of the org's sites — two sites declared as one\n * sender share a facet, and clearing it twice would find nothing the second\n * time. The unscoped collection ref is what the walk runs on precisely\n * because the path already carries the boundary — a `visibleTo` filter would\n * spend the query's one array-contains slot and leave none for the\n * membership.\n *\n * ## A plugin's members are the plugin's to clear\n *\n * A sequence and its enrollments name the campaign from documents under the\n * org, in collections this plugin does not know (AGL-3254). Every plugin\n * with a membership detacher registered on the core's seam is asked, once\n * per site, with the campaign's id and the field it is held in, and a\n * detacher that reports records remaining — or threw, which is reported as\n * `null` — holds the container exactly as this pass's own `remaining` does.\n * A plugin that failed is a plugin whose records may still name the\n * campaign, and the deletion has no way to tell that apart from one that has\n * more than a request clears.\n */\nasync function detachMembers(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n let remaining = false\n const take = (pass: { detached: number; remaining: boolean }) => {\n detached += pass.detached\n remaining = remaining || pass.remaining\n }\n const { hostIds, truncated } = await orgSiteIds(firestore, orgId)\n if (truncated) remaining = true\n for (const hostId of hostIds) {\n const hostRef = firestore.collection('hosts').doc(hostId)\n for (const collectionName of CAMPAIGN_MEMBER_HOST_COLLECTIONS) {\n take(\n await detachMembership(\n firestore,\n hostRef.collection(collectionName),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n ),\n )\n }\n }\n const orgRef = firestore.collection('orgs').doc(orgId)\n take(\n await detachMembership(\n firestore,\n orgRef.collection('leads'),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n ),\n )\n /*\n * An org with no sites still has plugins that may hold the campaign, so\n * the seam is asked once with no site rather than not at all.\n */\n for (const hostId of hostIds.length ? hostIds : ['']) {\n const plugins = await runPluginMembershipDetachers({\n hostId,\n orgId,\n field: CAMPAIGN_MEMBERSHIP_FIELD,\n id: campaignId,\n })\n for (const report of Object.values(plugins)) {\n detached += report?.detached ?? 0\n remaining = remaining || report === null || report.remaining\n }\n }\n /*\n * One read of the org document serves every site's group: with it in\n * hand, `consentGroupForSite` resolves from the declaration without a\n * lookup per site. A missing document answers every site as a group of\n * one, which is `consentGroupForSite`'s documented failure direction and\n * the safe one here — each site's own facet is cleared, and no other.\n */\n const org = ((await getOrgDoc(orgId)) ?? {}) as Record<string, unknown>\n const groupIds = new Set<string>()\n for (const hostId of hostIds) {\n groupIds.add((await consentGroupForSite(hostId, org)).groupId)\n }\n const contacts = orgRef.collection('contacts')\n for (const groupId of groupIds) {\n take(\n await detachMembership(\n firestore,\n contacts,\n contactCampaignFieldPath(groupId),\n campaignId,\n ),\n )\n }\n return { detached, remaining }\n}\n\n/** Who is deleting, and through which door. */\ninterface DeleteAccess {\n /** The site hub the request came from, or `''` from the organization hub. */\n hostId: string\n /** The caller, for the site door's reach check. */\n uid: string\n}\n\n/**\n * Removes a campaign container, leaving its emails standing.\n *\n * Detach first, delete second, and the order is the point: stopping between\n * them leaves a container whose emails are already single sends, which the\n * list draws correctly and a second run finishes. Deleting first would leave\n * sends naming a container nobody can read, which is the state that loses\n * them from the table.\n *\n * ## What a site hub may delete\n *\n * A campaign placed on this site and on no other — the one a site hub\n * creates. A campaign that is not placed here is not this site's to see, so\n * it answers 404 as a missing one would. A campaign also placed on other\n * sites is refused unless the caller is an org-wide member: deleting it\n * takes it off those sites too, which is the same reach change the rules\n * reserve for org-wide members when a campaign is edited.\n */\nasync function deleteCampaign(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n access: DeleteAccess,\n): Promise<ManageResult> {\n const ref = orgEmailCampaigns(firestore, orgId).doc(campaignId)\n const snapshot = await ref.get()\n /*\n * A 404 rather than a silent success. The id in a campaign URL may name a\n * container OR a single send — that ambiguity is what keeps every link\n * minted before containers existed resolving — so \"no container here\" is\n * very often \"this is a send\", and answering it as a completed deletion\n * would tell the console it had removed something it never touched.\n */\n const placement = {\n visibleTo: snapshot.exists\n ? (snapshot.get('visibleTo') as string[] | undefined)\n : undefined,\n }\n if (\n !snapshot.exists ||\n (access.hostId && !campaignPlacedOnHost(placement, access.hostId))\n ) {\n return { status: 404, body: { error: 'Unknown campaign' } }\n }\n if (access.hostId) {\n const sites = campaignSiteIds(placement)\n const onlyHere = sites !== null && sites.every((id) => id === access.hostId)\n if (!onlyHere) {\n const membership = await resolveOrgMembership(access.uid, orgId)\n if (!isOrgWideMember(membership?.member)) {\n return {\n status: 403,\n body: {\n error:\n 'This campaign is on other sites too, so deleting it would take ' +\n 'it off them as well. An organization admin can delete it from ' +\n 'the organization’s campaigns.',\n },\n }\n }\n }\n }\n const { detached, remaining } = await detachSends(firestore, orgId, campaignId)\n if (remaining) {\n return {\n status: 409,\n body: {\n detached,\n error:\n `This campaign holds more emails than one request can detach. ` +\n `${detached.toLocaleString()} of them now read as single sends and ` +\n 'the campaign is still here — run the delete again to finish it.',\n },\n }\n }\n /*\n * The MEMBERS come off before the container does, for the reason the sends\n * do: a partial run leaves records that are already out of the campaign,\n * which every surface draws correctly, while deleting first would leave\n * forms, screens and contacts naming an id nothing can resolve.\n *\n * Their own 409 rather than a shared one. \"More emails than one request can\n * detach\" is a sentence about the campaign's mail, and a merchant reading\n * it about a campaign of two emails and four thousand contacts would go\n * looking for emails that are not the problem.\n */\n const members = await detachMembers(firestore, orgId, campaignId)\n if (members.remaining) {\n return {\n status: 409,\n body: {\n detached,\n detachedMembers: members.detached,\n error:\n 'This campaign is on more records than one request can clear. ' +\n `${members.detached.toLocaleString()} of them are already out of ` +\n 'it and the campaign is still here — run the delete again to ' +\n 'finish it.',\n },\n }\n }\n await ref.delete()\n return {\n status: 200,\n body: {\n campaignId,\n detached,\n detachedMembers: members.detached,\n deleted: true,\n },\n }\n}\n\n/**\n * Discards a DRAFT email, and refuses anything else.\n *\n * The state check is inside the transaction as well as being the reason for\n * it. `sendNow` claims a draft by moving it to `sending` in a transaction of\n * its own, so a check made against an earlier read could delete a record\n * while the send path was mailing from it — the merchant would receive a\n * report for an email that no longer exists, and its `cid` would stop\n * resolving with the message already in inboxes.\n *\n * Only `draft`. A scheduled email is withdrawn with `cancel`, which leaves\n * the record and its report standing; a sent one has reached people, and\n * nothing on this surface may remove the evidence of that.\n *\n * `hostId` is the site hub the request came from, and a draft sent as a\n * different site is refused as unknown; from the organization hub it is\n * `''` and any site's draft may be discarded.\n */\nasync function discardDraft(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n emailId: string,\n hostId: string,\n): Promise<ManageResult> {\n const ref = orgCampaignSends(firestore, orgId).doc(emailId)\n const refusal = (state: string): string => {\n if (state === 'sent') {\n return 'This email has already been sent, so it cannot be discarded. ' +\n 'Its report and its unsubscribe links have to go on resolving.'\n }\n if (state === 'scheduled') {\n return 'This email is scheduled. Cancel the send first — cancelling ' +\n 'keeps the email and takes it off the clock.'\n }\n if (state === 'sending') {\n return 'This email is being sent right now.'\n }\n return 'Only a draft can be discarded.'\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult> => {\n const fresh = await transaction.get(ref)\n if (!fresh.exists || (hostId && !sendIsOnHost(fresh, hostId))) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const state = String(fresh.get('status') ?? '')\n if (state !== 'draft') {\n return { status: 409, body: { error: refusal(state) } }\n }\n /*\n * A plain delete, with nothing recursive under it. The one\n * subcollection a message grows is `reports/links`, written by the\n * delivery webhook — an email that has never been sent has no\n * deliveries, so there is nothing beneath a draft to leave behind.\n */\n transaction.delete(ref)\n return { status: 200, body: { emailId, discarded: true } }\n },\n )\n return outcome\n}\n\n/**\n * The fields a copy of a message carries (AGL-2936): what was written and\n * how it is sent — never who it goes to or when. The audience, list,\n * segment, addresses, schedule and experiment are the decisions a person\n * makes about THIS send, and a copy that inherited them would be one click\n * from mailing the same people twice.\n */\nconst DUPLICATED_MESSAGE_FIELDS = [\n 'subject',\n 'body',\n 'fromName',\n 'replyTo',\n 'senderId',\n 'templateScreenId',\n 'plainText',\n 'plainTextVersionId',\n 'topicId',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n] as const\n\n/**\n * Copies a message as a new draft (AGL-2936). Any status can be copied —\n * a sent email is the usual source — and the copy is always `draft`, with\n * the name the person gave it made unique among its site's messages.\n *\n * The copy is sent as the same site as its source: the sender, the design\n * and the consent it would mail under are all that site's. From a site hub\n * that is the requesting site, and a source sent as another site is refused\n * as unknown; from the organization hub (`hostId` `''`) it is whichever site\n * the source records, and a source that records none cannot be copied,\n * because the copy would be an email that can never be sent.\n */\nasync function duplicateMessage(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n hostId: string,\n emailId: string,\n requestedName: string,\n actor: { uid: string; email: string | null },\n): Promise<ManageResult> {\n const messages = orgCampaignSends(firestore, orgId)\n const id = createResourceUid()\n /*\n * The source is read once outside the transaction to learn its site, which\n * decides which siblings the name must be unique among; the transaction\n * reads it again, so a source changed in between is copied as it stands.\n */\n const peek = await messages.doc(emailId).get()\n if (!peek.exists || (hostId && !sendIsOnHost(peek, hostId))) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const siteId = hostId || sendHostId(peek)\n if (!siteId) {\n return {\n status: 409,\n body: {\n error:\n 'This email does not record which site it is sent from, so it ' +\n 'cannot be copied from here. Open it from its site instead.',\n },\n }\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult & { name?: string; sourceName?: string }> => {\n const [source, siblings] = await Promise.all([\n transaction.get(messages.doc(emailId)),\n transaction.get(\n messages\n .select('displayName', 'subject')\n .where(CAMPAIGN_SEND_HOST_FIELD, '==', siteId),\n ),\n ])\n if (!source.exists) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const data = (source.data() ?? {}) as Record<string, unknown>\n const sourceName = String(data['displayName'] ?? data['subject'] ?? '').trim()\n const name = uniqueDuplicateName(\n requestedName.trim() || duplicateDisplayName(sourceName),\n siblings.docs.map((row) => String(row.get('displayName') ?? row.get('subject') ?? '')),\n )\n const copy: Record<string, unknown> = {}\n for (const field of DUPLICATED_MESSAGE_FIELDS) {\n if (data[field] !== undefined && data[field] !== null) copy[field] = data[field]\n }\n const nowMs = Date.now()\n transaction.create(messages.doc(id), {\n ...copy,\n ...campaignSendSiteStamp(siteId),\n displayName: name,\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: new Date(nowMs),\n draftedBy: actor.uid,\n })\n return { status: 200, body: { emailId: id, name }, name, sourceName }\n },\n )\n if (outcome.status === 200) {\n await logResourceDuplicated(\n 'campaign',\n { uid: actor.uid, email: actor.email },\n {\n orgId,\n hostId: siteId,\n source: { id: emailId, name: outcome.sourceName ?? '' },\n target: { id, name: outcome.name ?? '' },\n },\n )\n }\n return { status: outcome.status, body: outcome.body }\n}\n\n/*==========================================\n * A CAMPAIGN THAT EXISTS BEFORE ANYBODY CHOSE WHO GETS IT (AGL-2912).\n *\n * The draft writer this plugin registers for the `campaign` resource on the\n * core's resource-drafts seam. Another plugin that produces a campaign — a\n * generator working from a brief, an importer bringing campaigns over from\n * another tool — asks for it by name, and gets exactly two documents:\n *\n * - the CONTAINER at `orgs/{orgId}/emailCampaigns/{id}`, written as a site\n * hub's create drawer writes one: aimed at no list, placed on the site\n * the draft was asked for;\n * - ONE EMAIL inside it at `orgs/{orgId}/campaigns/{id}-email`,\n * `status: 'draft'`, sent as that site, naming the email design it sends\n * and holding its subject, preheader and the alternatives to them.\n *\n * ## What a drafted email never holds\n *\n * An audience, a list, a segment, addresses, a topic, a sender, a send time or\n * an experiment. Those are the decisions a person makes about a send — the\n * duplicate above strips the same ones for the same reason — and a draft that\n * arrived holding any of them would be one click from mailing people nobody\n * chose. So the writer has no field for them to arrive in.\n *\n * ## Why a draft cannot escape\n *\n * Nothing here reserves an allowance, claims a budget or calls the send path,\n * and the scheduled processor queries `status == 'scheduled'`, which a draft\n * never is. `performCampaignSend` is the only thing that mails a draft, behind\n * the send route's own authorization, when a member asks.\n *\n * The id of the email is derived from the campaign's rather than minted, so a\n * write asked again finds the email it made — and differs from it, because a\n * campaign URL names a container OR a send, and one id naming both would read\n * as either.\n *=========================================*/\n\n/** The resource name the campaign draft writer is registered under. */\nexport const CAMPAIGN_DRAFT_RESOURCE = 'campaign'\n\n/** The id `plugins.config.json` registers this plugin under. */\nconst MARKETING_PLUGIN_ID = 'marketing'\n\n/** A drafted campaign's name when the caller asks for none. */\nexport const CAMPAIGN_DRAFT_DEFAULT_NAME = 'Untitled campaign'\n\n/** The longest subject or preheader a drafted email stores: the send route's header cap. */\nexport const CAMPAIGN_DRAFT_HEADER_MAX_CHARS = 200\n\n/** The most alternative subject lines or preheaders a drafted email keeps. */\nexport const CAMPAIGN_DRAFT_MAX_VARIANTS = 10\n\n/** The site roles that may compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLES = ['admin', 'editor'] as const\n/** The send route's refusal for a member who may not compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLE_REFUSAL = 'Not a site admin or editor'\n\n/** The id of the one email inside a drafted campaign. */\nexport function campaignDraftEmailId(campaignId: string): string {\n return `${campaignId}-email`\n}\n\n/** Every field a drafted email is written with, and so every field it can hold. */\nexport const CAMPAIGN_DRAFT_EMAIL_FIELDS = [\n 'subject',\n 'preheader',\n 'templateScreenId',\n 'subjectVariants',\n 'preheaderVariants',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n CAMPAIGN_SEND_HOST_FIELD,\n 'visibleTo',\n 'status',\n 'createdAtMs',\n 'draftedAt',\n 'draftedBy',\n] as const\n\n/** What a caller sends as `content`. */\nexport interface CampaignDraftContent {\n /** The email design the email sends: a `kind: 'email'` screen on the site. */\n templateScreenId: string\n subject: string\n preheader: string\n subjectVariants: string[]\n preheaderVariants: string[]\n}\n\n/** A header value on one line: controls and runs of space folded to one space. */\nfunction draftHeaderLine(value: unknown): string {\n return String(value ?? '').replace(/[\\p{Cc}\\s]+/gu, ' ').trim()\n}\n\nfunction draftVariants(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const seen = new Set<string>()\n const lines: string[] = []\n for (const raw of value) {\n const line = draftHeaderLine(raw)\n if (!line || seen.has(line.toLowerCase())) continue\n seen.add(line.toLowerCase())\n lines.push(line)\n }\n return lines.slice(0, CAMPAIGN_DRAFT_MAX_VARIANTS)\n}\n\nexport function readCampaignDraftContent(\n content: Readonly<Record<string, unknown>>,\n): { ok: true; value: CampaignDraftContent } | { ok: false; problems: string[] } {\n const value: CampaignDraftContent = {\n templateScreenId: String(content['templateScreenId'] ?? ''),\n subject: draftHeaderLine(content['subject']),\n preheader: draftHeaderLine(content['preheader']),\n subjectVariants: draftVariants(content['subjectVariants']),\n preheaderVariants: draftVariants(content['preheaderVariants']),\n }\n const problems: string[] = []\n if (!isDocumentId(value.templateScreenId)) {\n problems.push('A drafted campaign needs the email design it sends')\n }\n if (!value.subject) problems.push('A drafted campaign needs a subject line')\n const long = (lines: string[]) =>\n lines.some((line) => line.length > CAMPAIGN_DRAFT_HEADER_MAX_CHARS)\n if (long([value.subject, ...value.subjectVariants])) {\n problems.push(`A subject line is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n if (long([value.preheader, ...value.preheaderVariants])) {\n problems.push(`A preheader is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n return problems.length ? { ok: false, problems } : { ok: true, value }\n}\n\nfunction campaignDraftRoleRefusal(\n host: FirebaseFirestore.DocumentSnapshot,\n uid: string,\n): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return CAMPAIGN_DRAFT_ROLES.includes(role)\n ? null\n : { status: 403, error: CAMPAIGN_DRAFT_ROLE_REFUSAL }\n}\n\nfunction campaignDraftRecord(campaign: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n return {\n id: campaign.id,\n name: String(campaign.get('name') ?? ''),\n versionId: null,\n facts: { emailId: campaignDraftEmailId(campaign.id) },\n }\n}\n\nexport interface CampaignDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => FirebaseFirestore.Firestore\n /** The site's organization, or null; specs hand in a double. */\n resolveOrgId?: (hostId: string) => Promise<string | null>\n}\n\nexport function createCampaignDraftWriter(\n deps: CampaignDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore =\n deps.firestore ??\n (() => firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore)\n /*\n * The org is resolved from the SITE rather than taken from the request's\n * context: the site is what the role check reads, so the campaign lands in\n * the organization that site belongs to and no other.\n */\n const resolveOrgId = deps.resolveOrgId ?? resolveOrgIdForHost\n return {\n refusal: async ({ hostId, uid }) => {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n return campaignDraftRoleRefusal(host, uid)\n },\n\n check: (content) => {\n const read = readCampaignDraftContent(content)\n return read.ok === false\n ? read\n : { ok: true, facts: { fields: [...CAMPAIGN_DRAFT_EMAIL_FIELDS] } }\n },\n\n read: async ({ hostId, id }) => {\n if (!isDocumentId(id)) return null\n const orgId = await resolveOrgId(hostId)\n if (!orgId) return null\n const campaign = await orgEmailCampaigns(firestore(), orgId).doc(id).get()\n return campaign.exists &&\n campaignPlacedOnHost(\n { visibleTo: campaign.get('visibleTo') as string[] | undefined },\n hostId,\n )\n ? campaignDraftRecord(campaign)\n : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCampaignDraftContent(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n if (!isDocumentId(request.id)) return { ok: false, status: 400, error: 'Invalid campaignId' }\n const db = firestore()\n const orgId = await resolveOrgId(request.hostId)\n if (!orgId) {\n return { ok: false, status: 409, error: 'This site is not part of an organization' }\n }\n const hostRef = db.collection('hosts').doc(request.hostId)\n const campaignRef = orgEmailCampaigns(db, orgId).doc(request.id)\n const emailId = campaignDraftEmailId(request.id)\n const emailRef = orgCampaignSends(db, orgId).doc(emailId)\n const designRef = hostRef.collection('screens').doc(read.value.templateScreenId)\n return db.runTransaction(async (transaction): Promise<PluginDraftWrite> => {\n const [host, campaign, email, design] = await Promise.all([\n transaction.get(hostRef),\n transaction.get(campaignRef),\n transaction.get(emailRef),\n transaction.get(designRef),\n ])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (campaign.exists) {\n /*\n * A replay answers only for a campaign this site can see: the id\n * space is the organization's, and one placed on a sibling site is\n * not this request's to report or to write over.\n */\n if (\n !campaignPlacedOnHost(\n { visibleTo: campaign.get('visibleTo') as string[] | undefined },\n request.hostId,\n )\n ) {\n return { ok: false, status: 409, error: 'That campaign already exists' }\n }\n return { ok: true, replayed: true, ...campaignDraftRecord(campaign) }\n }\n const refusal = campaignDraftRoleRefusal(host, request.uid)\n if (refusal) return { ok: false, ...refusal }\n if (\n !design.exists ||\n design.get('deletedAt') != null ||\n design.get('kind') !== SCREEN_KIND_EMAIL\n ) {\n return { ok: false, status: 400, error: 'Unknown email design' }\n }\n if (email.exists) return { ok: false, status: 409, error: 'That email already exists' }\n const name = draftHeaderLine(request.name) || CAMPAIGN_DRAFT_DEFAULT_NAME\n const nowMs = request.now.getTime()\n // A site hub's create drawer's own document: a name, no dates, no\n // lists, placed on the site it was drafted for.\n transaction.create(campaignRef, {\n name,\n listIds: [],\n visibleTo: campaignVisibleTo([request.hostId]),\n createdAtMs: nowMs,\n createdBy: request.uid,\n })\n const { value } = read\n transaction.create(emailRef, {\n subject: value.subject,\n ...(value.preheader ? { preheader: value.preheader } : {}),\n templateScreenId: value.templateScreenId,\n ...(value.subjectVariants.length ? { subjectVariants: value.subjectVariants } : {}),\n ...(value.preheaderVariants.length ? { preheaderVariants: value.preheaderVariants } : {}),\n [CAMPAIGN_SEND_CONTAINER_FIELD]: request.id,\n ...campaignSendSiteStamp(request.hostId),\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: request.now,\n draftedBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: { emailId },\n }\n })\n },\n }\n}\n\nexport const campaignDraftWriter = createCampaignDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerCampaignDraftWriter(): void {\n registerPluginResourceDraftWriter(CAMPAIGN_DRAFT_RESOURCE, campaignDraftWriter, {\n pluginId: MARKETING_PLUGIN_ID,\n })\n}\n\n/** The org roles that may manage campaigns from the organization hub. */\nconst ORG_MANAGE_ROLES = ['owner', 'admin', 'editor'] as const\n\n/**\n * The organization a `campaigns/manage` request from the organization hub is\n * for, read off its JSON body, so the dispatcher's release gate asks about the\n * right organization. Only consulted for a request that names no site.\n * Unverified, exactly as a `hostId` is: the handler refuses anyone who is not\n * an org-wide member of it.\n */\nexport async function campaignManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as { orgId?: unknown } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/**\n * Campaign management API: removing a campaign, discarding a draft, and\n * copying an email.\n *\n * Separate from `campaigns/send` because nothing here sends, reserves\n * allowance or moves a meter, and because the removals are about a record\n * ceasing to exist — which is the one class of change that has to be read\n * against what a merchant has already mailed.\n *\n * Reached through two doors — see the header. A site request carries\n * `hostId` and is authorized by the caller's admin or editor role on that\n * site; an organization request carries `orgId` and no `hostId`, and is\n * authorized by an org-wide membership as owner, admin or editor.\n *\n * Editing a campaign is deliberately NOT here. The container is client-\n * writable, its create already runs on the client SDK, and a second door to\n * the same document would be a second place for the two to disagree about\n * what a campaign may hold.\n */\nexport const campaignManageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const requestedOrgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '')\n const targetId = String(req.body?.campaignId ?? '')\n if (!hostId && !requestedOrgId) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n if (hostId && !isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (requestedOrgId && !isDocumentId(requestedOrgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!isDocumentId(targetId)) {\n return res.status(400).json({ error: 'Invalid campaignId' })\n }\n if (\n action !== 'deleteCampaign' &&\n action !== 'discardEmail' &&\n action !== 'duplicate'\n ) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n let orgId: string\n if (hostId) {\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n orgId = (await resolveOrgIdForHost(hostId)) ?? ''\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it holds no campaigns.',\n })\n }\n /*\n * A request naming both is answered for the site, and only when the\n * two agree: an org id the site does not belong to is a confused\n * caller, and acting on the site's own org instead would be a guess.\n */\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n } else {\n const membership = await resolveOrgMembership(decoded.uid, requestedOrgId)\n const member = membership?.member as Partial<AglynOrgMember> | undefined\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(ORG_MANAGE_ROLES as readonly string[]).includes(String(member.role ?? ''))\n ) {\n return res\n .status(403)\n .json({ error: 'Not an organization owner, admin or editor' })\n }\n /*\n * The site door is refused by the dispatcher when Marketing is off for\n * the site; a request naming no site reaches here past only the release\n * gate, so the organization's own switch is asked here.\n */\n if (!isPluginEnabled(await getOrgDoc(requestedOrgId), MARKETING_PLUGIN_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n orgId = requestedOrgId\n }\n\n if (action === 'duplicate') {\n // One attempt key, one copy (AGL-2936): a double click on Duplicate\n // replays the first answer rather than drafting the message twice.\n const attemptKey = String(req.body?.attemptKey ?? '').trim().slice(0, 200)\n const claimed = attemptKey\n ? await claimAttempt(firestore as never, {\n kind: 'duplicate-campaign',\n scopeId: `${hostId || `org:${orgId}`}:${targetId}`,\n orgId,\n key: attemptKey,\n busyMessage: DUPLICATE_BUSY_MESSAGE,\n })\n : null\n if (claimed && 'replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n const claim = claimed && 'claim' in claimed ? claimed.claim : null\n const copied = await duplicateMessage(\n firestore,\n orgId,\n hostId,\n targetId,\n String(req.body?.name ?? ''),\n { uid: decoded.uid, email: decoded.email ?? null },\n )\n if (copied.status === 200) await claim?.record(copied.status, copied.body)\n else await claim?.release()\n return res.status(copied.status).json(copied.body)\n }\n const result =\n action === 'deleteCampaign'\n ? await deleteCampaign(firestore, orgId, targetId, {\n hostId,\n uid: decoded.uid,\n })\n : await discardDraft(firestore, orgId, targetId, hostId)\n return res.status(result.status).json(result.body)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'The request could not be completed' })\n }\n}\n"],"names":["firebaseAdmin","isDocumentId","logResourceDuplicated","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","claimAttempt","createResourceUid","consentGroupForSite","getOrgDoc","resolveOrgIdForHost","resolveOrgMembership","CAMPAIGN_MEMBER_HOST_COLLECTIONS","CAMPAIGN_MEMBERSHIP_FIELD","contactCampaignFieldPath","isOrgWideMember","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_SEND_HOST_FIELD","campaignPlacedOnHost","campaignSiteIds","campaignVisibleTo","campaignSendSiteStamp","orgCampaignSends","orgEmailCampaigns","sendHostId","sendIsOnHost","SCREEN_KIND_EMAIL","registerPluginResourceDraftWriter","runPluginMembershipDetachers","isPluginEnabled","DETACH_BATCH","DETACH_PASSES","ORG_SITES_MAX","detachSends","firestore","orgId","campaignId","detached","pass","page","where","limit","get","empty","remaining","batch","send","docs","update","ref","FieldValue","delete","commit","size","detachMembership","collectionRef","fieldPath","member","arrayRemove","orgSiteIds","collection","hostIds","map","doc","String","id","slice","truncated","length","detachMembers","take","hostId","hostRef","collectionName","orgRef","plugins","field","report","Object","values","org","groupIds","Set","add","groupId","contacts","deleteCampaign","access","snapshot","placement","visibleTo","exists","undefined","status","body","error","sites","onlyHere","every","membership","uid","toLocaleString","members","detachedMembers","deleted","discardDraft","emailId","refusal","state","outcome","runTransaction","transaction","fresh","discarded","DUPLICATED_MESSAGE_FIELDS","duplicateMessage","requestedName","actor","messages","peek","siteId","source","data","siblings","Promise","all","select","sourceName","trim","name","row","copy","nowMs","Date","now","create","displayName","createdAtMs","draftedAt","draftedBy","email","target","CAMPAIGN_DRAFT_RESOURCE","MARKETING_PLUGIN_ID","CAMPAIGN_DRAFT_DEFAULT_NAME","CAMPAIGN_DRAFT_HEADER_MAX_CHARS","CAMPAIGN_DRAFT_MAX_VARIANTS","CAMPAIGN_DRAFT_ROLES","CAMPAIGN_DRAFT_ROLE_REFUSAL","campaignDraftEmailId","CAMPAIGN_DRAFT_EMAIL_FIELDS","draftHeaderLine","value","replace","draftVariants","Array","isArray","seen","lines","raw","line","has","toLowerCase","push","readCampaignDraftContent","content","templateScreenId","subject","preheader","subjectVariants","preheaderVariants","problems","long","some","ok","campaignDraftRoleRefusal","host","role","includes","campaignDraftRecord","campaign","versionId","facts","createCampaignDraftWriter","deps","app","resolveOrgId","check","read","fields","write","request","db","campaignRef","emailRef","designRef","design","replayed","getTime","listIds","createdBy","campaignDraftWriter","registerCampaignDraftWriter","pluginId","ORG_MANAGE_ROLES","campaignManageSubject","method","json","catch","campaignManageHandler","req","res","requestedOrgId","action","targetId","authorization","headers","idToken","startsWith","decoded","auth","verifyIdToken","hostSnapshot","memberRole","attemptKey","claimed","kind","scopeId","key","busyMessage","replay","claim","copied","record","release","result","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED;;;;;;CAMC,GACD,OAAOA,mBAAmB,iDAAgD;AAC1E,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,sBAAqB;AACrE;;;;;CAKC,GACD,SACEC,mBAAmB,EACnBC,SAAS,EACTC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SACEC,gCAAgC,EAChCC,yBAAyB,EACzBC,wBAAwB,EACxBC,eAAe,QAIV,sBAAqB;AAC5B,SACEC,6BAA6B,EAC7BC,wBAAwB,EACxBC,oBAAoB,EACpBC,eAAe,EACfC,iBAAiB,QACZ,yCAAwC;AAC/C,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,QACP,yBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,iCAAiC,QAK5B,qDAAoD;AAC3D,SAASC,4BAA4B,QAA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,MAAM6I,SACJtB,WAAW,mBACP,MAAM/H,eAAepD,WAAWC,OAAOmL,UAAU;YAC/C/I;YACA6B,KAAKuH,QAAQvH,GAAG;QAClB,KACA,MAAMK,aAAavE,WAAWC,OAAOmL,UAAU/I;QACrD,OAAO4I,IAAItH,MAAM,CAAC8I,OAAO9I,MAAM,EAAEkH,IAAI,CAAC4B,OAAO7I,IAAI;IACnD,EAAE,OAAOC,OAAO;QACd6I,QAAQ7I,KAAK,CAACA;QACd,OAAOoH,IAAItH,MAAM,CAAC,KAAKkH,IAAI,CAAC;YAAEhH,OAAO;QAAqC;IAC5E;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-manage.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * TAKING SOMETHING AWAY: a campaign container, and an abandoned draft.\n *\n * Both are removals, and neither may take a delivered message with it. That\n * is the whole reason this file is small and the comments are long.\n *\n * ## Why these two are not client writes\n *\n * The console creates and edits a campaign CONTAINER with the client SDK —\n * `orgs/{orgId}/emailCampaigns` is client-writable, because a container holds\n * no counter, no consent record and no entitlement input. It is not\n * client-DELETABLE: removing one has to detach everything that names it\n * first, across every site in the organization, which no rule can express.\n *\n * The SEND collection is the opposite: `orgs/{orgId}/campaigns` is excluded\n * from client create, update AND delete, because each document is the record\n * of what a merchant mailed and to whom they were allowed to mail it. Both\n * operations here have to touch it — one to detach sends from the container\n * being removed, the other to remove a draft outright — so both run on the\n * Admin SDK behind a role check.\n *\n * ## Two doors: a site, and the organization\n *\n * A campaign belongs to the organization and may be placed on several of its\n * sites. A request from a SITE hub names the site (`hostId`) and is\n * authorized by the caller's role there, as the send route is — and it acts\n * only on what that site holds: a send sent as another site, or a campaign\n * not placed on this one, answers as if it did not exist. A request from the\n * ORGANIZATION hub names the org (`orgId`) and no site, and is authorized by\n * the caller's org-wide membership; for an email it acts in the name of the\n * site the email is sent as.\n *\n * ## What deleting a campaign MEANS\n *\n * The container goes; every email inside it stays, and reads afterwards as a\n * single send.\n *\n * It cannot mean anything else. A send id is cited by mail already delivered\n * — every unsubscribe footer carries `cid={sendId}` inside its own HMAC, and\n * `/marketing/campaigns/{sendId}` is a URL merchants paste into their own\n * messages — so deleting a container that destroyed its sends would break\n * opt-out links that must go on resolving forever, which is a compliance\n * failure rather than a broken page.\n *\n * Nor may the sends simply be left pointing at a container that is gone.\n * `campaignListRows` groups sends by the container they name and draws one\n * row per container; a send naming a container that no longer exists is in\n * neither half of that — not a container row, and not an orphan the list\n * adopts — so it would vanish from the campaigns table while remaining\n * perfectly deliverable. Detaching is what puts it back in the list, as the\n * \"Single send\" the product already models and the table already draws.\n *\n * Deleting a campaign is therefore NOT a way to stop its mail. A scheduled\n * email inside it keeps its send time and still goes out, because a\n * container is a grouping and cancelling somebody's mail is `cancel`'s job.\n * The console says so before it asks.\n *\n * ## The same rule for everything else the campaign held\n *\n * A campaign also groups forms, screens and contacts, each of which names it\n * from its OWN document. They are detached on exactly the argument the sends\n * are: a form left naming a container nobody can read has not been freed, it\n * has been made unreadable — its page draws a dead id where a campaign name\n * belongs, and the campaigns table can no longer find it. The record itself\n * is never touched. Deleting a campaign deletes a campaign.\n */\n\n/*\n * The MODULE, not the barrel. `@aglyn/tenant-data-admin`'s index reaches\n * `render-cache`, which imports `next/cache` and therefore the whole Next\n * server pipeline — everything this file needs from the admin SDK is one\n * default export, and taking it from the leaf keeps that pipeline out of the\n * graph.\n */\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { logResourceDuplicated } from '@aglyn/tenant-data-admin/server/duplicate-activity'\nimport { restampCrmListFieldsOf } from '@aglyn/tenant-data-admin/server/crm-records'\nimport {\n DUPLICATE_BUSY_MESSAGE,\n duplicateDisplayName,\n uniqueDuplicateName,\n} from '@aglyn/aglyn/app-utils/duplicate-resource'\nimport { claimAttempt, createResourceUid } from '@aglyn/aglyn/server'\n/*\n * The MODULES again, for the same reason: the org and membership reads here\n * are what the contact pass and the organization door need, and taking them\n * from `@aglyn/tenant-data-admin`'s index would pull the whole Next server\n * pipeline back into this file's graph.\n */\nimport {\n consentGroupForSite,\n getOrgDoc,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport {\n CAMPAIGN_MEMBER_HOST_COLLECTIONS,\n CAMPAIGN_MEMBERSHIP_FIELD,\n contactCampaignFieldPath,\n isOrgWideMember,\n type AglynOrgMember,\n type PluginApiHandler,\n type PluginApiRequestSubject,\n} from '@aglyn/aglyn/server'\nimport {\n CAMPAIGN_SEND_CONTAINER_FIELD,\n CAMPAIGN_SEND_HOST_FIELD,\n campaignPlacedOnHost,\n campaignSiteIds,\n campaignVisibleTo,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport {\n campaignSendSiteStamp,\n orgCampaignSends,\n orgEmailCampaigns,\n sendHostId,\n sendIsOnHost,\n} from './campaign-org-refs'\nimport { SCREEN_KIND_EMAIL } from '@aglyn/aglyn/app-utils/screen-route'\nimport {\n campaignContainerSearchFields,\n campaignSendSearchFields,\n} from '../model/campaign-list-query'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { runPluginMembershipDetachers } from '@aglyn/aglyn/plugin-manager/plugin-membership-detach'\nimport { isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\n\n/**\n * Sends detached in one write.\n *\n * Under Firestore's 500-operation batch limit with room to spare rather than\n * at it: a batch that is refused for being one over has done nothing, and the\n * margin costs one extra round trip on a campaign of exactly this size.\n */\nconst DETACH_BATCH = 400\n\n/**\n * How many batches one request will run.\n *\n * A ceiling on the REQUEST, not on the campaign. The loop below terminates on\n * its own — each pass clears the very field it queries on, so a detached send\n * is not returned again — but a request that runs unbounded is a request that\n * eventually exceeds the platform's own timeout with no idea how far it got.\n *\n * Stopping early is safe and is why this is a ceiling rather than a refusal\n * up front: detaching is idempotent and partial progress is a consistent\n * state — the sends already detached read as single sends, the rest still\n * read under the campaign — so the answer to hitting it is to ask again.\n */\nconst DETACH_PASSES = 25\n\n/**\n * The most sites one deletion walks for members.\n *\n * A campaign is the organization's, so its forms, screens and consent-group\n * facets may be on any of its sites. An organization past this has more\n * sites than one request should sweep, and the deletion refuses rather than\n * removing a container some sites' records would still name.\n */\nconst ORG_SITES_MAX = 200\n\n/** What one `campaigns/manage` call answered with. */\ninterface ManageResult {\n status: number\n body: Record<string, unknown>\n}\n\n/**\n * Files every send in a campaign under NO campaign: {@link\n * CAMPAIGN_SEND_CONTAINER_FIELD} set to `null`.\n *\n * Equality on one field with a `limit` — no `orderBy` — which Firestore's\n * automatic single-field index serves. Ordering would need a composite index\n * for a walk whose order does not matter: every match is being written, so\n * which order they come back in cannot change the outcome.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachSends(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await orgCampaignSends(firestore, orgId)\n .where(CAMPAIGN_SEND_CONTAINER_FIELD, '==', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const send of page.docs) {\n /*\n * `null`, not an empty string and not a removed field. \"Belongs to no\n * campaign\" has ONE stored shape, because it is a query: the lists ask\n * `emailCampaignId == null` for single sends (AGL-3321), which an\n * empty string would not answer and a missing field cannot — a query\n * never finds a field that is not there. `campaignListRows` adopts any\n * falsy container id, so every reader agrees.\n */\n batch.update(send.ref, {\n [CAMPAIGN_SEND_CONTAINER_FIELD]: null,\n })\n }\n await batch.commit()\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Clears one campaign id out of a membership array, wherever it is held.\n *\n * The same walk {@link detachSends} makes, over an ARRAY field rather than a\n * scalar one: `array-contains` matches on Firestore's automatic single-field\n * index, and `arrayRemove` takes out the one id without touching the other\n * campaigns a form or a screen is in. That is the whole reason the membership\n * is an array here and a `FieldValue.delete()` on a send — a send is in one\n * campaign and a landing page is in several, so removing one must not be\n * removing all of them.\n *\n * `query` rather than a collection ref, because the contact pass hands in a\n * path this file cannot build for itself.\n *\n * @returns how many were detached, and whether any were left.\n */\nasync function detachMembership(\n firestore: FirebaseFirestore.Firestore,\n collectionRef: FirebaseFirestore.CollectionReference,\n fieldPath: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n for (let pass = 0; pass < DETACH_PASSES; pass += 1) {\n const page = await collectionRef\n .where(fieldPath, 'array-contains', campaignId)\n .limit(DETACH_BATCH)\n .get()\n if (page.empty) return { detached, remaining: false }\n const batch = firestore.batch()\n for (const member of page.docs) {\n batch.update(member.ref, {\n [fieldPath]: firebaseAdmin.firestore.FieldValue.arrayRemove(campaignId),\n })\n }\n await batch.commit()\n // A lead's campaigns are what the Leads list's Campaign filter reads\n // under a site (AGL-3321): restamped from each lead as it now stands.\n if (collectionRef.id === 'leads') {\n await restampCrmListFieldsOf(page.docs.map((member) => member.ref), 'leads')\n }\n detached += page.size\n if (page.size < DETACH_BATCH) return { detached, remaining: false }\n }\n return { detached, remaining: true }\n}\n\n/**\n * Every site of the organization, by id — the sites a campaign's members may\n * be on. One equality on the `hostIndex` mirror, the same document\n * `resolveOrgIdForHost` reads to put a site in an org.\n *\n * @returns the ids, and whether the org has more than {@link ORG_SITES_MAX}.\n */\nasync function orgSiteIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<{ hostIds: string[]; truncated: boolean }> {\n const page = await firestore\n .collection('hostIndex')\n .where('orgId', '==', orgId)\n .limit(ORG_SITES_MAX + 1)\n .get()\n const hostIds = page.docs.map((doc) => String(doc.id))\n return {\n hostIds: hostIds.slice(0, ORG_SITES_MAX),\n truncated: hostIds.length > ORG_SITES_MAX,\n }\n}\n\n/**\n * Clears the campaign off every form, screen, lead and contact holding it,\n * on every site of the organization, and then off every record a plugin\n * keeps about it (AGL-3254).\n *\n * ## Why the campaign is not simply deleted over the top of them\n *\n * A campaign that went away leaving members naming it is the same failure the\n * send detach exists to prevent, one collection over: the campaign's own page\n * finds its forms and screens with `array-contains`, and a form still naming\n * a container nobody can read is in neither half of that — not a member of\n * any campaign the console can draw, and not free of one either. Its own page\n * would render the dead id as a chip with no name.\n *\n * ## Every site, not the one that asked\n *\n * The campaign is the organization's, and a site it has since been taken off\n * may still hold forms and screens filed under it. So the walk covers every\n * site in the org regardless of which door the deletion came through.\n *\n * ## Leads and contacts are reached on the organization\n *\n * A lead lives at `orgs/{orgId}/leads` and carries the field at the top of\n * its document, like a form. The site `leads` collection is walked as well,\n * as part of each site's own collections: records captured before leads\n * moved to the org are still read there.\n *\n * A contact lives at `orgs/{orgId}/contacts` and is shared by every site, so\n * the membership sits inside a consent group's facet rather than at the top\n * of the document. The field PATH is therefore the scope, and the walk runs\n * once per distinct group of the org's sites — two sites declared as one\n * sender share a facet, and clearing it twice would find nothing the second\n * time. The unscoped collection ref is what the walk runs on precisely\n * because the path already carries the boundary — a `visibleTo` filter would\n * spend the query's one array-contains slot and leave none for the\n * membership.\n *\n * ## A plugin's members are the plugin's to clear\n *\n * A sequence and its enrollments name the campaign from documents under the\n * org, in collections this plugin does not know (AGL-3254). Every plugin\n * with a membership detacher registered on the core's seam is asked, once\n * per site, with the campaign's id and the field it is held in, and a\n * detacher that reports records remaining — or threw, which is reported as\n * `null` — holds the container exactly as this pass's own `remaining` does.\n * A plugin that failed is a plugin whose records may still name the\n * campaign, and the deletion has no way to tell that apart from one that has\n * more than a request clears.\n */\nasync function detachMembers(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n): Promise<{ detached: number; remaining: boolean }> {\n let detached = 0\n let remaining = false\n const take = (pass: { detached: number; remaining: boolean }) => {\n detached += pass.detached\n remaining = remaining || pass.remaining\n }\n const { hostIds, truncated } = await orgSiteIds(firestore, orgId)\n if (truncated) remaining = true\n for (const hostId of hostIds) {\n const hostRef = firestore.collection('hosts').doc(hostId)\n for (const collectionName of CAMPAIGN_MEMBER_HOST_COLLECTIONS) {\n take(\n await detachMembership(\n firestore,\n hostRef.collection(collectionName),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n ),\n )\n }\n }\n const orgRef = firestore.collection('orgs').doc(orgId)\n take(\n await detachMembership(\n firestore,\n orgRef.collection('leads'),\n CAMPAIGN_MEMBERSHIP_FIELD,\n campaignId,\n ),\n )\n /*\n * An org with no sites still has plugins that may hold the campaign, so\n * the seam is asked once with no site rather than not at all.\n */\n for (const hostId of hostIds.length ? hostIds : ['']) {\n const plugins = await runPluginMembershipDetachers({\n hostId,\n orgId,\n field: CAMPAIGN_MEMBERSHIP_FIELD,\n id: campaignId,\n })\n for (const report of Object.values(plugins)) {\n detached += report?.detached ?? 0\n remaining = remaining || report === null || report.remaining\n }\n }\n /*\n * One read of the org document serves every site's group: with it in\n * hand, `consentGroupForSite` resolves from the declaration without a\n * lookup per site. A missing document answers every site as a group of\n * one, which is `consentGroupForSite`'s documented failure direction and\n * the safe one here — each site's own facet is cleared, and no other.\n */\n const org = ((await getOrgDoc(orgId)) ?? {}) as Record<string, unknown>\n const groupIds = new Set<string>()\n for (const hostId of hostIds) {\n groupIds.add((await consentGroupForSite(hostId, org)).groupId)\n }\n const contacts = orgRef.collection('contacts')\n for (const groupId of groupIds) {\n take(\n await detachMembership(\n firestore,\n contacts,\n contactCampaignFieldPath(groupId),\n campaignId,\n ),\n )\n }\n return { detached, remaining }\n}\n\n/** Who is deleting, and through which door. */\ninterface DeleteAccess {\n /** The site hub the request came from, or `''` from the organization hub. */\n hostId: string\n /** The caller, for the site door's reach check. */\n uid: string\n}\n\n/**\n * Removes a campaign container, leaving its emails standing.\n *\n * Detach first, delete second, and the order is the point: stopping between\n * them leaves a container whose emails are already single sends, which the\n * list draws correctly and a second run finishes. Deleting first would leave\n * sends naming a container nobody can read, which is the state that loses\n * them from the table.\n *\n * ## What a site hub may delete\n *\n * A campaign placed on this site and on no other — the one a site hub\n * creates. A campaign that is not placed here is not this site's to see, so\n * it answers 404 as a missing one would. A campaign also placed on other\n * sites is refused unless the caller is an org-wide member: deleting it\n * takes it off those sites too, which is the same reach change the rules\n * reserve for org-wide members when a campaign is edited.\n */\nasync function deleteCampaign(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n campaignId: string,\n access: DeleteAccess,\n): Promise<ManageResult> {\n const ref = orgEmailCampaigns(firestore, orgId).doc(campaignId)\n const snapshot = await ref.get()\n /*\n * A 404 rather than a silent success. The id in a campaign URL may name a\n * container OR a single send — that ambiguity is what keeps every link\n * minted before containers existed resolving — so \"no container here\" is\n * very often \"this is a send\", and answering it as a completed deletion\n * would tell the console it had removed something it never touched.\n */\n const placement = {\n visibleTo: snapshot.exists\n ? (snapshot.get('visibleTo') as string[] | undefined)\n : undefined,\n }\n if (\n !snapshot.exists ||\n (access.hostId && !campaignPlacedOnHost(placement, access.hostId))\n ) {\n return { status: 404, body: { error: 'Unknown campaign' } }\n }\n if (access.hostId) {\n const sites = campaignSiteIds(placement)\n const onlyHere = sites !== null && sites.every((id) => id === access.hostId)\n if (!onlyHere) {\n const membership = await resolveOrgMembership(access.uid, orgId)\n if (!isOrgWideMember(membership?.member)) {\n return {\n status: 403,\n body: {\n error:\n 'This campaign is on other sites too, so deleting it would take ' +\n 'it off them as well. An organization admin can delete it from ' +\n 'the organization’s campaigns.',\n },\n }\n }\n }\n }\n const { detached, remaining } = await detachSends(firestore, orgId, campaignId)\n if (remaining) {\n return {\n status: 409,\n body: {\n detached,\n error:\n `This campaign holds more emails than one request can detach. ` +\n `${detached.toLocaleString()} of them now read as single sends and ` +\n 'the campaign is still here — run the delete again to finish it.',\n },\n }\n }\n /*\n * The MEMBERS come off before the container does, for the reason the sends\n * do: a partial run leaves records that are already out of the campaign,\n * which every surface draws correctly, while deleting first would leave\n * forms, screens and contacts naming an id nothing can resolve.\n *\n * Their own 409 rather than a shared one. \"More emails than one request can\n * detach\" is a sentence about the campaign's mail, and a merchant reading\n * it about a campaign of two emails and four thousand contacts would go\n * looking for emails that are not the problem.\n */\n const members = await detachMembers(firestore, orgId, campaignId)\n if (members.remaining) {\n return {\n status: 409,\n body: {\n detached,\n detachedMembers: members.detached,\n error:\n 'This campaign is on more records than one request can clear. ' +\n `${members.detached.toLocaleString()} of them are already out of ` +\n 'it and the campaign is still here — run the delete again to ' +\n 'finish it.',\n },\n }\n }\n await ref.delete()\n return {\n status: 200,\n body: {\n campaignId,\n detached,\n detachedMembers: members.detached,\n deleted: true,\n },\n }\n}\n\n/**\n * Discards a DRAFT email, and refuses anything else.\n *\n * The state check is inside the transaction as well as being the reason for\n * it. `sendNow` claims a draft by moving it to `sending` in a transaction of\n * its own, so a check made against an earlier read could delete a record\n * while the send path was mailing from it — the merchant would receive a\n * report for an email that no longer exists, and its `cid` would stop\n * resolving with the message already in inboxes.\n *\n * Only `draft`. A scheduled email is withdrawn with `cancel`, which leaves\n * the record and its report standing; a sent one has reached people, and\n * nothing on this surface may remove the evidence of that.\n *\n * `hostId` is the site hub the request came from, and a draft sent as a\n * different site is refused as unknown; from the organization hub it is\n * `''` and any site's draft may be discarded.\n */\nasync function discardDraft(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n emailId: string,\n hostId: string,\n): Promise<ManageResult> {\n const ref = orgCampaignSends(firestore, orgId).doc(emailId)\n const refusal = (state: string): string => {\n if (state === 'sent') {\n return 'This email has already been sent, so it cannot be discarded. ' +\n 'Its report and its unsubscribe links have to go on resolving.'\n }\n if (state === 'scheduled') {\n return 'This email is scheduled. Cancel the send first — cancelling ' +\n 'keeps the email and takes it off the clock.'\n }\n if (state === 'sending') {\n return 'This email is being sent right now.'\n }\n return 'Only a draft can be discarded.'\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult> => {\n const fresh = await transaction.get(ref)\n if (!fresh.exists || (hostId && !sendIsOnHost(fresh, hostId))) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const state = String(fresh.get('status') ?? '')\n if (state !== 'draft') {\n return { status: 409, body: { error: refusal(state) } }\n }\n /*\n * A plain delete, with nothing recursive under it. The one\n * subcollection a message grows is `reports/links`, written by the\n * delivery webhook — an email that has never been sent has no\n * deliveries, so there is nothing beneath a draft to leave behind.\n */\n transaction.delete(ref)\n return { status: 200, body: { emailId, discarded: true } }\n },\n )\n return outcome\n}\n\n/**\n * The fields a copy of a message carries (AGL-2936): what was written and\n * how it is sent — never who it goes to or when. The audience, list,\n * segment, addresses, schedule and experiment are the decisions a person\n * makes about THIS send, and a copy that inherited them would be one click\n * from mailing the same people twice.\n */\nconst DUPLICATED_MESSAGE_FIELDS = [\n 'subject',\n 'body',\n 'fromName',\n 'replyTo',\n 'senderId',\n 'templateScreenId',\n 'plainText',\n 'plainTextVersionId',\n 'topicId',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n] as const\n\n/**\n * Copies a message as a new draft (AGL-2936). Any status can be copied —\n * a sent email is the usual source — and the copy is always `draft`, with\n * the name the person gave it made unique among its site's messages.\n *\n * The copy is sent as the same site as its source: the sender, the design\n * and the consent it would mail under are all that site's. From a site hub\n * that is the requesting site, and a source sent as another site is refused\n * as unknown; from the organization hub (`hostId` `''`) it is whichever site\n * the source records, and a source that records none cannot be copied,\n * because the copy would be an email that can never be sent.\n */\nasync function duplicateMessage(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n hostId: string,\n emailId: string,\n requestedName: string,\n actor: { uid: string; email: string | null },\n): Promise<ManageResult> {\n const messages = orgCampaignSends(firestore, orgId)\n const id = createResourceUid()\n /*\n * The source is read once outside the transaction to learn its site, which\n * decides which siblings the name must be unique among; the transaction\n * reads it again, so a source changed in between is copied as it stands.\n */\n const peek = await messages.doc(emailId).get()\n if (!peek.exists || (hostId && !sendIsOnHost(peek, hostId))) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const siteId = hostId || sendHostId(peek)\n if (!siteId) {\n return {\n status: 409,\n body: {\n error:\n 'This email does not record which site it is sent from, so it ' +\n 'cannot be copied from here. Open it from its site instead.',\n },\n }\n }\n const outcome = await firestore.runTransaction(\n async (transaction): Promise<ManageResult & { name?: string; sourceName?: string }> => {\n const [source, siblings] = await Promise.all([\n transaction.get(messages.doc(emailId)),\n transaction.get(\n messages\n .select('displayName', 'subject')\n .where(CAMPAIGN_SEND_HOST_FIELD, '==', siteId),\n ),\n ])\n if (!source.exists) {\n return { status: 404, body: { error: 'Unknown email' } }\n }\n const data = (source.data() ?? {}) as Record<string, unknown>\n const sourceName = String(data['displayName'] ?? data['subject'] ?? '').trim()\n const name = uniqueDuplicateName(\n requestedName.trim() || duplicateDisplayName(sourceName),\n siblings.docs.map((row) => String(row.get('displayName') ?? row.get('subject') ?? '')),\n )\n const copy: Record<string, unknown> = {}\n for (const field of DUPLICATED_MESSAGE_FIELDS) {\n if (data[field] !== undefined && data[field] !== null) copy[field] = data[field]\n }\n const nowMs = Date.now()\n transaction.create(messages.doc(id), {\n ...copy,\n // The list fields a new record carries (AGL-3321): its subject's\n // search tokens, and `null` for a source filed under no campaign.\n ...campaignSendSearchFields(copy['subject']),\n [CAMPAIGN_SEND_CONTAINER_FIELD]: copy[CAMPAIGN_SEND_CONTAINER_FIELD] ?? null,\n ...campaignSendSiteStamp(siteId),\n displayName: name,\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: new Date(nowMs),\n draftedBy: actor.uid,\n })\n return { status: 200, body: { emailId: id, name }, name, sourceName }\n },\n )\n if (outcome.status === 200) {\n await logResourceDuplicated(\n 'campaign',\n { uid: actor.uid, email: actor.email },\n {\n orgId,\n hostId: siteId,\n source: { id: emailId, name: outcome.sourceName ?? '' },\n target: { id, name: outcome.name ?? '' },\n },\n )\n }\n return { status: outcome.status, body: outcome.body }\n}\n\n/*==========================================\n * A CAMPAIGN THAT EXISTS BEFORE ANYBODY CHOSE WHO GETS IT (AGL-2912).\n *\n * The draft writer this plugin registers for the `campaign` resource on the\n * core's resource-drafts seam. Another plugin that produces a campaign — a\n * generator working from a brief, an importer bringing campaigns over from\n * another tool — asks for it by name, and gets exactly two documents:\n *\n * - the CONTAINER at `orgs/{orgId}/emailCampaigns/{id}`, written as a site\n * hub's create drawer writes one: aimed at no list, placed on the site\n * the draft was asked for;\n * - ONE EMAIL inside it at `orgs/{orgId}/campaigns/{id}-email`,\n * `status: 'draft'`, sent as that site, naming the email design it sends\n * and holding its subject, preheader and the alternatives to them.\n *\n * ## What a drafted email never holds\n *\n * An audience, a list, a segment, addresses, a topic, a sender, a send time or\n * an experiment. Those are the decisions a person makes about a send — the\n * duplicate above strips the same ones for the same reason — and a draft that\n * arrived holding any of them would be one click from mailing people nobody\n * chose. So the writer has no field for them to arrive in.\n *\n * ## Why a draft cannot escape\n *\n * Nothing here reserves an allowance, claims a budget or calls the send path,\n * and the scheduled processor queries `status == 'scheduled'`, which a draft\n * never is. `performCampaignSend` is the only thing that mails a draft, behind\n * the send route's own authorization, when a member asks.\n *\n * The id of the email is derived from the campaign's rather than minted, so a\n * write asked again finds the email it made — and differs from it, because a\n * campaign URL names a container OR a send, and one id naming both would read\n * as either.\n *=========================================*/\n\n/** The resource name the campaign draft writer is registered under. */\nexport const CAMPAIGN_DRAFT_RESOURCE = 'campaign'\n\n/** The id `plugins.config.json` registers this plugin under. */\nconst MARKETING_PLUGIN_ID = 'marketing'\n\n/** A drafted campaign's name when the caller asks for none. */\nexport const CAMPAIGN_DRAFT_DEFAULT_NAME = 'Untitled campaign'\n\n/** The longest subject or preheader a drafted email stores: the send route's header cap. */\nexport const CAMPAIGN_DRAFT_HEADER_MAX_CHARS = 200\n\n/** The most alternative subject lines or preheaders a drafted email keeps. */\nexport const CAMPAIGN_DRAFT_MAX_VARIANTS = 10\n\n/** The site roles that may compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLES = ['admin', 'editor'] as const\n/** The send route's refusal for a member who may not compose this site's mail. */\nexport const CAMPAIGN_DRAFT_ROLE_REFUSAL = 'Not a site admin or editor'\n\n/** The id of the one email inside a drafted campaign. */\nexport function campaignDraftEmailId(campaignId: string): string {\n return `${campaignId}-email`\n}\n\n/** Every field a drafted email is written with, and so every field it can hold. */\nexport const CAMPAIGN_DRAFT_EMAIL_FIELDS = [\n 'subject',\n 'subjectTokens',\n 'preheader',\n 'templateScreenId',\n 'subjectVariants',\n 'preheaderVariants',\n CAMPAIGN_SEND_CONTAINER_FIELD,\n CAMPAIGN_SEND_HOST_FIELD,\n 'visibleTo',\n 'status',\n 'createdAtMs',\n 'draftedAt',\n 'draftedBy',\n] as const\n\n/** What a caller sends as `content`. */\nexport interface CampaignDraftContent {\n /** The email design the email sends: a `kind: 'email'` screen on the site. */\n templateScreenId: string\n subject: string\n preheader: string\n subjectVariants: string[]\n preheaderVariants: string[]\n}\n\n/** A header value on one line: controls and runs of space folded to one space. */\nfunction draftHeaderLine(value: unknown): string {\n return String(value ?? '').replace(/[\\p{Cc}\\s]+/gu, ' ').trim()\n}\n\nfunction draftVariants(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const seen = new Set<string>()\n const lines: string[] = []\n for (const raw of value) {\n const line = draftHeaderLine(raw)\n if (!line || seen.has(line.toLowerCase())) continue\n seen.add(line.toLowerCase())\n lines.push(line)\n }\n return lines.slice(0, CAMPAIGN_DRAFT_MAX_VARIANTS)\n}\n\nexport function readCampaignDraftContent(\n content: Readonly<Record<string, unknown>>,\n): { ok: true; value: CampaignDraftContent } | { ok: false; problems: string[] } {\n const value: CampaignDraftContent = {\n templateScreenId: String(content['templateScreenId'] ?? ''),\n subject: draftHeaderLine(content['subject']),\n preheader: draftHeaderLine(content['preheader']),\n subjectVariants: draftVariants(content['subjectVariants']),\n preheaderVariants: draftVariants(content['preheaderVariants']),\n }\n const problems: string[] = []\n if (!isDocumentId(value.templateScreenId)) {\n problems.push('A drafted campaign needs the email design it sends')\n }\n if (!value.subject) problems.push('A drafted campaign needs a subject line')\n const long = (lines: string[]) =>\n lines.some((line) => line.length > CAMPAIGN_DRAFT_HEADER_MAX_CHARS)\n if (long([value.subject, ...value.subjectVariants])) {\n problems.push(`A subject line is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n if (long([value.preheader, ...value.preheaderVariants])) {\n problems.push(`A preheader is longer than ${CAMPAIGN_DRAFT_HEADER_MAX_CHARS} characters`)\n }\n return problems.length ? { ok: false, problems } : { ok: true, value }\n}\n\nfunction campaignDraftRoleRefusal(\n host: FirebaseFirestore.DocumentSnapshot,\n uid: string,\n): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return CAMPAIGN_DRAFT_ROLES.includes(role)\n ? null\n : { status: 403, error: CAMPAIGN_DRAFT_ROLE_REFUSAL }\n}\n\nfunction campaignDraftRecord(campaign: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n return {\n id: campaign.id,\n name: String(campaign.get('name') ?? ''),\n versionId: null,\n facts: { emailId: campaignDraftEmailId(campaign.id) },\n }\n}\n\nexport interface CampaignDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => FirebaseFirestore.Firestore\n /** The site's organization, or null; specs hand in a double. */\n resolveOrgId?: (hostId: string) => Promise<string | null>\n}\n\nexport function createCampaignDraftWriter(\n deps: CampaignDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore =\n deps.firestore ??\n (() => firebaseAdmin.app().firestore() as unknown as FirebaseFirestore.Firestore)\n /*\n * The org is resolved from the SITE rather than taken from the request's\n * context: the site is what the role check reads, so the campaign lands in\n * the organization that site belongs to and no other.\n */\n const resolveOrgId = deps.resolveOrgId ?? resolveOrgIdForHost\n return {\n refusal: async ({ hostId, uid }) => {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n return campaignDraftRoleRefusal(host, uid)\n },\n\n check: (content) => {\n const read = readCampaignDraftContent(content)\n return read.ok === false\n ? read\n : { ok: true, facts: { fields: [...CAMPAIGN_DRAFT_EMAIL_FIELDS] } }\n },\n\n read: async ({ hostId, id }) => {\n if (!isDocumentId(id)) return null\n const orgId = await resolveOrgId(hostId)\n if (!orgId) return null\n const campaign = await orgEmailCampaigns(firestore(), orgId).doc(id).get()\n return campaign.exists &&\n campaignPlacedOnHost(\n { visibleTo: campaign.get('visibleTo') as string[] | undefined },\n hostId,\n )\n ? campaignDraftRecord(campaign)\n : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readCampaignDraftContent(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n if (!isDocumentId(request.id)) return { ok: false, status: 400, error: 'Invalid campaignId' }\n const db = firestore()\n const orgId = await resolveOrgId(request.hostId)\n if (!orgId) {\n return { ok: false, status: 409, error: 'This site is not part of an organization' }\n }\n const hostRef = db.collection('hosts').doc(request.hostId)\n const campaignRef = orgEmailCampaigns(db, orgId).doc(request.id)\n const emailId = campaignDraftEmailId(request.id)\n const emailRef = orgCampaignSends(db, orgId).doc(emailId)\n const designRef = hostRef.collection('screens').doc(read.value.templateScreenId)\n return db.runTransaction(async (transaction): Promise<PluginDraftWrite> => {\n const [host, campaign, email, design] = await Promise.all([\n transaction.get(hostRef),\n transaction.get(campaignRef),\n transaction.get(emailRef),\n transaction.get(designRef),\n ])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (campaign.exists) {\n /*\n * A replay answers only for a campaign this site can see: the id\n * space is the organization's, and one placed on a sibling site is\n * not this request's to report or to write over.\n */\n if (\n !campaignPlacedOnHost(\n { visibleTo: campaign.get('visibleTo') as string[] | undefined },\n request.hostId,\n )\n ) {\n return { ok: false, status: 409, error: 'That campaign already exists' }\n }\n return { ok: true, replayed: true, ...campaignDraftRecord(campaign) }\n }\n const refusal = campaignDraftRoleRefusal(host, request.uid)\n if (refusal) return { ok: false, ...refusal }\n if (\n !design.exists ||\n design.get('deletedAt') != null ||\n design.get('kind') !== SCREEN_KIND_EMAIL\n ) {\n return { ok: false, status: 400, error: 'Unknown email design' }\n }\n if (email.exists) return { ok: false, status: 409, error: 'That email already exists' }\n const name = draftHeaderLine(request.name) || CAMPAIGN_DRAFT_DEFAULT_NAME\n const nowMs = request.now.getTime()\n // A site hub's create drawer's own document: a name, no dates, no\n // lists, placed on the site it was drafted for.\n const visibleTo = campaignVisibleTo([request.hostId])\n transaction.create(campaignRef, {\n name,\n ...campaignContainerSearchFields(name),\n listIds: [],\n visibleTo,\n createdAtMs: nowMs,\n createdBy: request.uid,\n })\n const { value } = read\n transaction.create(emailRef, {\n subject: value.subject,\n ...campaignSendSearchFields(value.subject),\n ...(value.preheader ? { preheader: value.preheader } : {}),\n templateScreenId: value.templateScreenId,\n ...(value.subjectVariants.length ? { subjectVariants: value.subjectVariants } : {}),\n ...(value.preheaderVariants.length ? { preheaderVariants: value.preheaderVariants } : {}),\n [CAMPAIGN_SEND_CONTAINER_FIELD]: request.id,\n ...campaignSendSiteStamp(request.hostId),\n status: 'draft',\n createdAtMs: nowMs,\n draftedAt: request.now,\n draftedBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name,\n versionId: null,\n facts: { emailId },\n }\n })\n },\n }\n}\n\nexport const campaignDraftWriter = createCampaignDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerCampaignDraftWriter(): void {\n registerPluginResourceDraftWriter(CAMPAIGN_DRAFT_RESOURCE, campaignDraftWriter, {\n pluginId: MARKETING_PLUGIN_ID,\n })\n}\n\n/** The org roles that may manage campaigns from the organization hub. */\nconst ORG_MANAGE_ROLES = ['owner', 'admin', 'editor'] as const\n\n/**\n * The organization a `campaigns/manage` request from the organization hub is\n * for, read off its JSON body, so the dispatcher's release gate asks about the\n * right organization. Only consulted for a request that names no site.\n * Unverified, exactly as a `hostId` is: the handler refuses anyone who is not\n * an org-wide member of it.\n */\nexport async function campaignManageSubject(\n request: Request,\n): Promise<PluginApiRequestSubject | null> {\n if (request.method !== 'POST') return null\n const body = (await request.json().catch(() => null)) as { orgId?: unknown } | null\n const orgId = typeof body?.orgId === 'string' ? body.orgId : ''\n return isDocumentId(orgId) ? { orgId } : null\n}\n\n/**\n * Campaign management API: removing a campaign, discarding a draft, and\n * copying an email.\n *\n * Separate from `campaigns/send` because nothing here sends, reserves\n * allowance or moves a meter, and because the removals are about a record\n * ceasing to exist — which is the one class of change that has to be read\n * against what a merchant has already mailed.\n *\n * Reached through two doors — see the header. A site request carries\n * `hostId` and is authorized by the caller's admin or editor role on that\n * site; an organization request carries `orgId` and no `hostId`, and is\n * authorized by an org-wide membership as owner, admin or editor.\n *\n * Editing a campaign is deliberately NOT here. The container is client-\n * writable, its create already runs on the client SDK, and a second door to\n * the same document would be a second place for the two to disagree about\n * what a campaign may hold.\n */\nexport const campaignManageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const requestedOrgId = String(req.body?.orgId ?? '')\n const action = String(req.body?.action ?? '')\n const targetId = String(req.body?.campaignId ?? '')\n if (!hostId && !requestedOrgId) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n if (hostId && !isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Invalid hostId' })\n }\n if (requestedOrgId && !isDocumentId(requestedOrgId)) {\n return res.status(400).json({ error: 'Invalid orgId' })\n }\n if (!isDocumentId(targetId)) {\n return res.status(400).json({ error: 'Invalid campaignId' })\n }\n if (\n action !== 'deleteCampaign' &&\n action !== 'discardEmail' &&\n action !== 'duplicate'\n ) {\n return res.status(400).json({ error: 'Unknown action' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n let orgId: string\n if (hostId) {\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n orgId = (await resolveOrgIdForHost(hostId)) ?? ''\n if (!orgId) {\n return res.status(409).json({\n error: 'This site is not part of an organization, so it holds no campaigns.',\n })\n }\n /*\n * A request naming both is answered for the site, and only when the\n * two agree: an org id the site does not belong to is a confused\n * caller, and acting on the site's own org instead would be a guess.\n */\n if (requestedOrgId && requestedOrgId !== orgId) {\n return res.status(400).json({ error: 'That site is not in this organization' })\n }\n } else {\n const membership = await resolveOrgMembership(decoded.uid, requestedOrgId)\n const member = membership?.member as Partial<AglynOrgMember> | undefined\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(ORG_MANAGE_ROLES as readonly string[]).includes(String(member.role ?? ''))\n ) {\n return res\n .status(403)\n .json({ error: 'Not an organization owner, admin or editor' })\n }\n /*\n * The site door is refused by the dispatcher when Marketing is off for\n * the site; a request naming no site reaches here past only the release\n * gate, so the organization's own switch is asked here.\n */\n if (!isPluginEnabled(await getOrgDoc(requestedOrgId), MARKETING_PLUGIN_ID)) {\n return res.status(404).json({ error: 'Not found' })\n }\n orgId = requestedOrgId\n }\n\n if (action === 'duplicate') {\n // One attempt key, one copy (AGL-2936): a double click on Duplicate\n // replays the first answer rather than drafting the message twice.\n const attemptKey = String(req.body?.attemptKey ?? '').trim().slice(0, 200)\n const claimed = attemptKey\n ? await claimAttempt(firestore as never, {\n kind: 'duplicate-campaign',\n scopeId: `${hostId || `org:${orgId}`}:${targetId}`,\n orgId,\n key: attemptKey,\n busyMessage: DUPLICATE_BUSY_MESSAGE,\n })\n : null\n if (claimed && 'replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n const claim = claimed && 'claim' in claimed ? claimed.claim : null\n const copied = await duplicateMessage(\n firestore,\n orgId,\n hostId,\n targetId,\n String(req.body?.name ?? ''),\n { uid: decoded.uid, email: decoded.email ?? null },\n )\n if (copied.status === 200) await claim?.record(copied.status, copied.body)\n else await claim?.release()\n return res.status(copied.status).json(copied.body)\n }\n const result =\n action === 'deleteCampaign'\n ? await deleteCampaign(firestore, orgId, targetId, {\n hostId,\n uid: decoded.uid,\n })\n : await discardDraft(firestore, orgId, targetId, hostId)\n return res.status(result.status).json(result.body)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'The request could not be completed' })\n }\n}\n"],"names":["firebaseAdmin","isDocumentId","logResourceDuplicated","restampCrmListFieldsOf","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","claimAttempt","createResourceUid","consentGroupForSite","getOrgDoc","resolveOrgIdForHost","resolveOrgMembership","CAMPAIGN_MEMBER_HOST_COLLECTIONS","CAMPAIGN_MEMBERSHIP_FIELD","contactCampaignFieldPath","isOrgWideMember","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_SEND_HOST_FIELD","campaignPlacedOnHost","campaignSiteIds","campaignVisibleTo","campaignSendSiteStamp","orgCampaignSends","orgEmailCampaigns","sendHostId","sendIsOnHost","SCREEN_KIND_EMAIL","campaignContainerSearchFields","campaignSendSearchFields","registerPluginResourceDraftWriter","runPluginMembershipDetachers","isPluginEnabled","DETACH_BATCH","DETACH_PASSES","ORG_SITES_MAX","detachSends","firestore","orgId","campaignId","detached","pass","page","where","limit","get","empty","remaining","batch","send","docs","update","ref","commit","size","detachMembership","collectionRef","fieldPath","member","FieldValue","arrayRemove","id","map","orgSiteIds","collection","hostIds","doc","String","slice","truncated","length","detachMembers","take","hostId","hostRef","collectionName","orgRef","plugins","field","report","Object","values","org","groupIds","Set","add","groupId","contacts","deleteCampaign","access","snapshot","placement","visibleTo","exists","undefined","status","body","error","sites","onlyHere","every","membership","uid","toLocaleString","members","detachedMembers","delete","deleted","discardDraft","emailId","refusal","state","outcome","runTransaction","transaction","fresh","discarded","DUPLICATED_MESSAGE_FIELDS","duplicateMessage","requestedName","actor","messages","peek","siteId","source","data","copy","siblings","Promise","all","select","sourceName","trim","name","row","nowMs","Date","now","create","displayName","createdAtMs","draftedAt","draftedBy","email","target","CAMPAIGN_DRAFT_RESOURCE","MARKETING_PLUGIN_ID","CAMPAIGN_DRAFT_DEFAULT_NAME","CAMPAIGN_DRAFT_HEADER_MAX_CHARS","CAMPAIGN_DRAFT_MAX_VARIANTS","CAMPAIGN_DRAFT_ROLES","CAMPAIGN_DRAFT_ROLE_REFUSAL","campaignDraftEmailId","CAMPAIGN_DRAFT_EMAIL_FIELDS","draftHeaderLine","value","replace","draftVariants","Array","isArray","seen","lines","raw","line","has","toLowerCase","push","readCampaignDraftContent","content","templateScreenId","subject","preheader","subjectVariants","preheaderVariants","problems","long","some","ok","campaignDraftRoleRefusal","host","role","includes","campaignDraftRecord","campaign","versionId","facts","createCampaignDraftWriter","deps","app","resolveOrgId","check","read","fields","write","request","db","campaignRef","emailRef","designRef","design","replayed","getTime","listIds","createdBy","campaignDraftWriter","registerCampaignDraftWriter","pluginId","ORG_MANAGE_ROLES","campaignManageSubject","method","json","catch","campaignManageHandler","req","res","requestedOrgId","action","targetId","authorization","headers","idToken","startsWith","decoded","auth","verifyIdToken","hostSnapshot","memberRole","attemptKey","claimed","kind","scopeId","key","busyMessage","replay","claim","copied","record","release","result","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED;;;;;;CAMC,GACD,OAAOA,mBAAmB,iDAAgD;AAC1E,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SAASC,sBAAsB,QAAQ,8CAA6C;AACpF,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,sBAAqB;AACrE;;;;;CAKC,GACD,SACEC,mBAAmB,EACnBC,SAAS,EACTC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SACEC,gCAAgC,EAChCC,yBAAyB,EACzBC,wBAAwB,EACxBC,eAAe,QAIV,sBAAqB;AAC5B,SACEC,6BAA6B,EAC7BC,wBAAwB,EACxBC,oBAAoB,EACpBC,eAAe,EACfC,iBAAiB,QACZ,yCAAwC;AAC/C,SACEC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,UAAU,EACVC,YAAY,QACP,yBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SACEC,6BAA6B,EAC7BC,wBAAwB,QACnB,kCAA8B;AACrC,SACEC,iCAAiC,QAK5B,qDAAoD;AAC3D,SAASC,4BAA4B,QAAQ,uDAAsD;AACnG,SAASC,eAAe,QAAQ,8CAA6C;AAE7E;;;;;;CAMC,GACD,MAAMC,eAAe;AAErB;;;;;;;;;;;;CAYC,GACD,MAAMC,gBAAgB;AAEtB;;;;;;;CAOC,GACD,MAAMC,gBAAgB;AAQtB;;;;;;;;;;CAUC,GACD,eAAeC,YACbC,SAAsC,EACtCC,KAAa,EACbC,UAAkB;IAElB,IAAIC,WAAW;IAC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AC4I,OAAO5I,MAAM,EAAEmH,IAAI,CAACyB,OAAO3I,IAAI;QACnD;QACA,MAAM8I,SACJtB,WAAW,mBACP,MAAMhI,eAAenD,WAAWC,OAAOmL,UAAU;YAC/ChJ;YACA6B,KAAKwH,QAAQxH,GAAG;QAClB,KACA,MAAMM,aAAavE,WAAWC,OAAOmL,UAAUhJ;QACrD,OAAO6I,IAAIvH,MAAM,CAAC+I,OAAO/I,MAAM,EAAEmH,IAAI,CAAC4B,OAAO9I,IAAI;IACnD,EAAE,OAAOC,OAAO;QACd8I,QAAQ9I,KAAK,CAACA;QACd,OAAOqH,IAAIvH,MAAM,CAAC,KAAKmH,IAAI,CAAC;YAAEjH,OAAO;QAAqC;IAC5E;AACF,EAAC"}
@@ -169,6 +169,13 @@ export interface CampaignSendOptions {
169
169
  displayName?: string;
170
170
  /** Test sends (AGL-349) skip the campaign record and stats. */
171
171
  recordCampaign?: boolean;
172
+ /**
173
+ * The `campaignId` names a record that does not exist yet, so this send
174
+ * MINTS it and stamps what a new record carries — its creation date, and
175
+ * `emailCampaignId: null` when it is filed under no campaign. Without it a
176
+ * caller naming an id is taken to address an existing record.
177
+ */
178
+ mintsRecord?: boolean;
172
179
  /**
173
180
  * SEND THIS EMAIL AGAIN, TO PEOPLE IT HAS NOT REACHED.
174
181
  *
@@ -51,6 +51,7 @@ import { filterCadenceSendable, recordMarketingSends } from "@aglyn/tenant-data-
51
51
  * from the real module.
52
52
  */ import { CAMPAIGN_REACH_CEILING, campaignReachCovers, campaignSettledSize, partitionByCampaignReach, readCampaignReach, readCampaignSettled, recordCampaignReach, recordCampaignSkipped } from "./email-campaign-reach.js";
53
53
  import { campaignSendSiteStamp, orgCampaignSends, orgEmailCampaigns, sendIsOnHost } from "./campaign-org-refs.js";
54
+ import { campaignSendSearchFields } from "../model/campaign-list-query.js";
54
55
  /*
55
56
  * The LEAF module for the reputation controls too, and for the same reason
56
57
  * as the three above it: every spec that reaches this file mocks the
@@ -1298,7 +1299,7 @@ export async function performCampaignSend(options) {
1298
1299
  * that record already carries its own creation stamp. Re-stamping it would
1299
1300
  * move an email's creation date forward every time it was sent again, and
1300
1301
  * the emails list orders drafts on exactly that field.
1301
- */ const mintsRecord = !options.campaignId;
1302
+ */ const mintsRecord = !options.campaignId || options.mintsRecord === true;
1302
1303
  // Designed email template (AGL-349): loaded once; rendered per
1303
1304
  // recipient with their merge values.
1304
1305
  const template = options.templateScreenId ? await loadEmailTemplate(hostId, options.templateScreenId) : null;
@@ -1956,7 +1957,8 @@ export async function performCampaignSend(options) {
1956
1957
  * below are stored under: they are true of the send that happened.
1957
1958
  */ const measuresTheAudience = !options.continuation;
1958
1959
  await sends.doc(campaignId).set(_extends({}, campaignSendSiteStamp(hostId), {
1959
- subject,
1960
+ subject
1961
+ }, campaignSendSearchFields(subject), {
1960
1962
  body,
1961
1963
  audience
1962
1964
  }, mintsRecord ? {
@@ -1993,6 +1995,8 @@ export async function performCampaignSend(options) {
1993
1995
  displayName: options.displayName
1994
1996
  } : {}, options.emailCampaignId ? {
1995
1997
  emailCampaignId: options.emailCampaignId
1998
+ } : mintsRecord ? {
1999
+ emailCampaignId: null
1996
2000
  } : {}, {
1997
2001
  /*
1998
2002
  * WHAT THIS EMAIL DID WITH THE UNSUBSCRIBE HEADER, and why (AGL-3307).
@@ -3064,7 +3068,8 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
3064
3068
  });
3065
3069
  }
3066
3070
  await targetRef.set(_extends({}, campaignSendSiteStamp(hostId), {
3067
- subject,
3071
+ subject
3072
+ }, campaignSendSearchFields(subject), {
3068
3073
  body,
3069
3074
  audience
3070
3075
  }, targetSnapshot.exists ? {} : {
@@ -3113,7 +3118,9 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
3113
3118
  displayName
3114
3119
  } : {}, emailCampaignId ? {
3115
3120
  emailCampaignId
3116
- } : {}, scheduling ? {
3121
+ } : targetSnapshot.exists ? {} : {
3122
+ emailCampaignId: null
3123
+ }, scheduling ? {
3117
3124
  status: 'scheduled',
3118
3125
  sendAtMs,
3119
3126
  scheduledAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),
@@ -3305,6 +3312,7 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
3305
3312
  * which takes no copy from the request at all and subtracts everyone the
3306
3313
  * earlier sends recorded.
3307
3314
  *=========================================*/ const sendId = String((_ref12 = (_req_body15 = req.body) == null ? void 0 : _req_body15.campaignId) != null ? _ref12 : '');
3315
+ /** The id names no record yet, so this send mints it (AGL-3321). */ let mintsNamedRecord = false;
3308
3316
  if (sendId) {
3309
3317
  var _existing_get;
3310
3318
  if (!isDocumentId(sendId)) {
@@ -3313,6 +3321,7 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
3313
3321
  });
3314
3322
  }
3315
3323
  const existing = await orgSends.doc(sendId).get();
3324
+ mintsNamedRecord = !existing.exists;
3316
3325
  if (existing.exists && !sendIsOnHost(existing, hostId)) {
3317
3326
  return res.status(404).json({
3318
3327
  error: 'Unknown email'
@@ -3334,7 +3343,10 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
3334
3343
  listId: String((_ref14 = (_req_body17 = req.body) == null ? void 0 : _req_body17.listId) != null ? _ref14 : ''),
3335
3344
  topicId: topicId || undefined,
3336
3345
  emails: Array.isArray((_req_body18 = req.body) == null ? void 0 : _req_body18.emails) ? req.body.emails : undefined,
3337
- campaignId: sendId,
3346
+ campaignId: sendId
3347
+ }, mintsNamedRecord ? {
3348
+ mintsRecord: true
3349
+ } : {}, {
3338
3350
  experimentId: String((_ref15 = (_req_body19 = req.body) == null ? void 0 : _req_body19.experimentId) != null ? _ref15 : ''),
3339
3351
  templateScreenId: templateScreenId || undefined
3340
3352
  }, plainText ? {