@aglyn/plugins-marketing 1.0.0-beta.287 → 1.0.0-beta.288
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.
- package/package.json +16 -16
- package/src/lib/declarations.d.ts +25 -0
- package/src/lib/declarations.js +36 -0
- package/src/lib/declarations.js.map +1 -0
- package/src/lib/model/marketing-permissions.d.ts +26 -0
- package/src/lib/model/marketing-permissions.js +42 -0
- package/src/lib/model/marketing-permissions.js.map +1 -0
- package/src/lib/server/campaign-manage.d.ts +2 -4
- package/src/lib/server/campaign-manage.js +16 -21
- package/src/lib/server/campaign-manage.js.map +1 -1
- package/src/lib/server/campaign-recipients.js +7 -5
- package/src/lib/server/campaign-recipients.js.map +1 -1
- package/src/lib/server/campaign-send.js +7 -4
- package/src/lib/server/campaign-send.js.map +1 -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 { restampFormsInCampaign } from './campaign-form-flags'\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 getOrgDoc,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport {\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 '../model/campaign-container'\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 CAMPAIGN_MEMBER_HOST_COLLECTIONS,\n CAMPAIGN_MEMBERSHIP_FIELD,\n} from '../model/campaign-kind'\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 * @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 const isForms = collectionRef.id === 'forms'\n for (const member of page.docs) {\n batch.update(member.ref, {\n [fieldPath]: firebaseAdmin.firestore.FieldValue.arrayRemove(campaignId),\n // Leaving a campaign is an edit to the form, and Updated says when\n // the form was last edited (AGL-3330).\n ...(isForms ? { updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() } : {}),\n })\n }\n await batch.commit()\n // A form's `inCampaign` is what the Forms list's \"In a campaign\" filter\n // asks (AGL-3330), and `arrayRemove` cannot say whether it emptied the\n // array: restamped from each form as it now stands.\n if (isForms) {\n await restampFormsInCampaign(firestore, page.docs.map((member) => member.ref))\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 and screen holding it, on every site of\n * the organization, and then off every record a plugin keeps filed under it\n * (AGL-3254, AGL-3080).\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 * ## A plugin's members are the plugin's to clear\n *\n * A lead, a contact, a sequence and its enrollments name the campaign from\n * documents another plugin keeps, in collections this plugin does not know:\n * the CRM's leads carry the field at the top of their documents and its\n * contacts inside each consent group's facet, and Outreach's sequences under\n * the org. Every plugin with a membership detacher registered on the core's\n * seam is asked, once per site, with the campaign's id and the field it is\n * held in, and a detacher that reports records remaining — or threw, which is\n * reported as `null` — holds the container exactly as this pass's own\n * `remaining` does. A plugin that failed is a plugin whose records may still\n * name the campaign, and the deletion has no way to tell that apart from one\n * that has 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 /*\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 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 'subjectLower',\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","restampFormsInCampaign","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","claimAttempt","createResourceUid","getOrgDoc","resolveOrgIdForHost","resolveOrgMembership","isOrgWideMember","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_SEND_HOST_FIELD","campaignPlacedOnHost","campaignSiteIds","campaignVisibleTo","campaignSendSiteStamp","orgCampaignSends","orgEmailCampaigns","sendHostId","sendIsOnHost","SCREEN_KIND_EMAIL","CAMPAIGN_MEMBER_HOST_COLLECTIONS","CAMPAIGN_MEMBERSHIP_FIELD","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","isForms","id","member","FieldValue","arrayRemove","updatedAt","serverTimestamp","map","orgSiteIds","collection","hostIds","doc","String","slice","truncated","length","detachMembers","take","hostId","hostRef","collectionName","plugins","field","report","Object","values","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","Set","lines","raw","line","has","toLowerCase","add","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,2BAAuB;AAC9D,SACEC,sBAAsB,EACtBC,oBAAoB,EACpBC,mBAAmB,QACd,4CAA2C;AAClD,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,sBAAqB;AACrE;;;;;CAKC,GACD,SACEC,SAAS,EACTC,mBAAmB,EACnBC,oBAAoB,QACf,gDAA+C;AACtD,SACEC,eAAe,QAIV,sBAAqB;AAC5B,SACEC,6BAA6B,EAC7BC,wBAAwB,EACxB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B;YAAK;YAEnD,IAAIa,OAAO9I,MAAM,KAAK,KAAK,OAAM6I,yBAAAA,MAAOE,MAAM,CAACD,OAAO9I,MAAM,EAAE8I,OAAO7I,IAAI;iBACpE,OAAM4I,yBAAAA,MAAOG,OAAO;YACzB,OAAOvB,IAAIzH,MAAM,CAAC8I,OAAO9I,MAAM,EAAEqH,IAAI,CAACyB,OAAO7I,IAAI;QACnD;QACA,MAAMgJ,SACJtB,WAAW,mBACP,MAAMlI,eAAe/C,WAAWC,OAAOiL,UAAU;YAC/C3I;YACAsB,KAAK0H,QAAQ1H,GAAG;QAClB,KACA,MAAMM,aAAanE,WAAWC,OAAOiL,UAAU3I;QACrD,OAAOwI,IAAIzH,MAAM,CAACiJ,OAAOjJ,MAAM,EAAEqH,IAAI,CAAC4B,OAAOhJ,IAAI;IACnD,EAAE,OAAOC,OAAO;QACdgJ,QAAQhJ,KAAK,CAACA;QACd,OAAOuH,IAAIzH,MAAM,CAAC,KAAKqH,IAAI,CAAC;YAAEnH,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 { restampFormsInCampaign } from './campaign-form-flags'\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 getOrgDoc,\n memberHasOrgPermission,\n resolveOrgIdForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin/server/organizations'\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETING_CAMPAIGNS_REFUSAL, MARKETING_CAMPAIGNS_SITE_ROLE_PRESET } from '../model/marketing-permissions'\nimport {\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 '../model/campaign-container'\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 CAMPAIGN_MEMBER_HOST_COLLECTIONS,\n CAMPAIGN_MEMBERSHIP_FIELD,\n} from '../model/campaign-kind'\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 * @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 const isForms = collectionRef.id === 'forms'\n for (const member of page.docs) {\n batch.update(member.ref, {\n [fieldPath]: firebaseAdmin.firestore.FieldValue.arrayRemove(campaignId),\n // Leaving a campaign is an edit to the form, and Updated says when\n // the form was last edited (AGL-3330).\n ...(isForms ? { updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() } : {}),\n })\n }\n await batch.commit()\n // A form's `inCampaign` is what the Forms list's \"In a campaign\" filter\n // asks (AGL-3330), and `arrayRemove` cannot say whether it emptied the\n // array: restamped from each form as it now stands.\n if (isForms) {\n await restampFormsInCampaign(firestore, page.docs.map((member) => member.ref))\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 and screen holding it, on every site of\n * the organization, and then off every record a plugin keeps filed under it\n * (AGL-3254, AGL-3080).\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 * ## A plugin's members are the plugin's to clear\n *\n * A lead, a contact, a sequence and its enrollments name the campaign from\n * documents another plugin keeps, in collections this plugin does not know:\n * the CRM's leads carry the field at the top of their documents and its\n * contacts inside each consent group's facet, and Outreach's sequences under\n * the org. Every plugin with a membership detacher registered on the core's\n * seam is asked, once per site, with the campaign's id and the field it is\n * held in, and a detacher that reports records remaining — or threw, which is\n * reported as `null` — holds the container exactly as this pass's own\n * `remaining` does. A plugin that failed is a plugin whose records may still\n * name the campaign, and the deletion has no way to tell that apart from one\n * that has 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 /*\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 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 refusal for a member without \"Run email campaigns\" here (AGL-4047): names the permission. */\nexport const CAMPAIGN_DRAFT_ROLE_REFUSAL = MARKETING_CAMPAIGNS_REFUSAL\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 'subjectLower',\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 // \"Run email campaigns\" (AGL-4047): the site's stamp, else the preset of\n // the member's site role, the Admin and Editor this asked for before.\n return holdsStampedSiteKey(host, uid, 'marketing.campaigns', MARKETING_CAMPAIGNS_SITE_ROLE_PRESET)\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/**\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 if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketing.campaigns', MARKETING_CAMPAIGNS_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: MARKETING_CAMPAIGNS_REFUSAL })\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 // A member of the whole workspace holding \"Run email campaigns\" with\n // no site named (AGL-4047): its default is the owner, admins and\n // editors this asked for before, then their custom role and their own\n // permissions.\n if (\n !member ||\n !isOrgWideMember(member) ||\n !(await memberHasOrgPermission(requestedOrgId, member, 'marketing.campaigns' as never))\n ) {\n return res.status(403).json({ error: MARKETING_CAMPAIGNS_REFUSAL })\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","restampFormsInCampaign","DUPLICATE_BUSY_MESSAGE","duplicateDisplayName","uniqueDuplicateName","claimAttempt","createResourceUid","getOrgDoc","memberHasOrgPermission","resolveOrgIdForHost","resolveOrgMembership","holdsStampedSiteKey","MARKETING_CAMPAIGNS_REFUSAL","MARKETING_CAMPAIGNS_SITE_ROLE_PRESET","isOrgWideMember","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_SEND_HOST_FIELD","campaignPlacedOnHost","campaignSiteIds","campaignVisibleTo","campaignSendSiteStamp","orgCampaignSends","orgEmailCampaigns","sendHostId","sendIsOnHost","SCREEN_KIND_EMAIL","CAMPAIGN_MEMBER_HOST_COLLECTIONS","CAMPAIGN_MEMBERSHIP_FIELD","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","isForms","id","member","FieldValue","arrayRemove","updatedAt","serverTimestamp","map","orgSiteIds","collection","hostIds","doc","String","slice","truncated","length","detachMembers","take","hostId","hostRef","collectionName","plugins","field","report","Object","values","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_ROLE_REFUSAL","campaignDraftEmailId","CAMPAIGN_DRAFT_EMAIL_FIELDS","draftHeaderLine","value","replace","draftVariants","Array","isArray","seen","Set","lines","raw","line","has","toLowerCase","add","push","readCampaignDraftContent","content","templateScreenId","subject","preheader","subjectVariants","preheaderVariants","problems","long","some","ok","campaignDraftRoleRefusal","host","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","campaignManageSubject","method","json","catch","campaignManageHandler","req","res","requestedOrgId","action","targetId","authorization","headers","idToken","startsWith","decoded","auth","verifyIdToken","hostSnapshot","attemptKey","claimed","kind","scopeId","key","busyMessage","replay","claim","copied","record","release","result","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED;;;;;;CAMC,GACD,OAAOA,mBAAmB,iDAAgD;A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ACAC,OACAsC,QACAuI,UACA7I,iBAAOyI,aAAAA,IAAInH,IAAI,qBAARmH,WAAU9E,IAAI,oBAAI,KACzB;gBAAE/B,KAAKsH,QAAQtH,GAAG;gBAAEyC,KAAK,GAAE6E,iBAAAA,QAAQ7E,KAAK,YAAb6E,iBAAiB;YAAK;YAEnD,IAAIY,OAAOzI,MAAM,KAAK,KAAK,OAAMwI,yBAAAA,MAAOE,MAAM,CAACD,OAAOzI,MAAM,EAAEyI,OAAOxI,IAAI;iBACpE,OAAMuI,yBAAAA,MAAOG,OAAO;YACzB,OAAOtB,IAAIrH,MAAM,CAACyI,OAAOzI,MAAM,EAAEiH,IAAI,CAACwB,OAAOxI,IAAI;QACnD;QACA,MAAM2I,SACJrB,WAAW,mBACP,MAAM9H,eAAe/C,WAAWC,OAAO6K,UAAU;YAC/CvI;YACAsB,KAAKsH,QAAQtH,GAAG;QAClB,KACA,MAAMM,aAAanE,WAAWC,OAAO6K,UAAUvI;QACrD,OAAOoI,IAAIrH,MAAM,CAAC4I,OAAO5I,MAAM,EAAEiH,IAAI,CAAC2B,OAAO3I,IAAI;IACnD,EAAE,OAAOC,OAAO;QACd2I,QAAQ3I,KAAK,CAACA;QACd,OAAOmH,IAAIrH,MAAM,CAAC,KAAKiH,IAAI,CAAC;YAAE/G,OAAO;QAAqC;IAC5E;AACF,EAAC"}
|
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/ import {
|
|
16
|
+
*/ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
17
|
+
import { MARKETING_CAMPAIGNS_REFUSAL, MARKETING_CAMPAIGNS_SITE_ROLE_PRESET } from "../model/marketing-permissions.js";
|
|
18
|
+
import { firebaseAdmin, resolveOrgIdForHost } from "@aglyn/tenant-data-admin";
|
|
17
19
|
// Leaf imports, for the reason `email-events.ts` records: a spec that mocks
|
|
18
20
|
// the `@aglyn/tenant-data-admin` barrel would otherwise replace the real
|
|
19
21
|
// delivery-log reader with whatever the factory listed, and this handler's
|
|
@@ -122,7 +124,6 @@ import { orgCampaignSends, sendIsOnHost } from "./campaign-org-refs.js";
|
|
|
122
124
|
error: 'Unauthenticated'
|
|
123
125
|
});
|
|
124
126
|
try {
|
|
125
|
-
var _hostSnapshot_get;
|
|
126
127
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
127
128
|
const firestore = firebaseAdmin.app().firestore();
|
|
128
129
|
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
@@ -132,10 +133,11 @@ import { orgCampaignSends, sendIsOnHost } from "./campaign-org-refs.js";
|
|
|
132
133
|
error: 'Unknown site'
|
|
133
134
|
});
|
|
134
135
|
}
|
|
135
|
-
|
|
136
|
-
|
|
136
|
+
// "Run email campaigns" (AGL-4047): the site's stamp, else the preset of
|
|
137
|
+
// the member's site role, the Admin and Editor this asked for before.
|
|
138
|
+
if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketing.campaigns', MARKETING_CAMPAIGNS_SITE_ROLE_PRESET)) {
|
|
137
139
|
return res.status(403).json({
|
|
138
|
-
error:
|
|
140
|
+
error: MARKETING_CAMPAIGNS_REFUSAL
|
|
139
141
|
});
|
|
140
142
|
}
|
|
141
143
|
/*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-recipients.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\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, resolveOrgIdForHost } from '@aglyn/tenant-data-admin'\n// Leaf imports, for the reason `email-events.ts` records: a spec that mocks\n// the `@aglyn/tenant-data-admin` barrel would otherwise replace the real\n// delivery-log reader with whatever the factory listed, and this handler's\n// whole behaviour is what that reader returns.\nimport {\n readSendEngagement,\n EMAIL_SEND_ENGAGEMENT_MAX_SENDS,\n type EmailEngagementFilter,\n} from '@aglyn/tenant-data-admin/server/email-delivery-log'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { FieldPath } from 'firebase-admin/firestore'\nimport { CAMPAIGN_SEND_HOST_FIELD } from '../model/campaign-container'\nimport { orgCampaignSends, sendIsOnHost } from './campaign-org-refs'\n\n/**\n * When a message went out, or is due to.\n *\n * There is no one date field: the send path writes `sentAt` from one branch\n * and `sendAtMs` from the other, and nothing stamps a `createdAt`. Both are\n * read so a scheduled message sorts beside a sent one instead of falling to\n * the bottom of every list that touches it.\n */\nfunction messageTimeMs(snapshot: any): number {\n const sentAt = snapshot.get('sentAt')\n if (typeof sentAt?.toMillis === 'function') return sentAt.toMillis()\n const scheduled = Number(snapshot.get('sendAtMs') ?? 0)\n return Number.isFinite(scheduled) ? scheduled : 0\n}\n\n/**\n * WHO OPENED THIS, ONE PAGE AT A TIME.\n *\n * ## Why a server route rather than a client listen\n *\n * The per-recipient delivery log lives at `emailDeliveries/{sha256(address)}`\n * — a platform-level collection keyed by a hash of an address, holding the\n * mail of every site on the install and every transactional message besides.\n * No security rule can express \"this site's editors may read the rows tagged\n * with this site\" over a collection-group query, because the predicate that\n * narrows it is the query's own `where`, and a rule cannot require one. So\n * the narrowing happens here, behind a role check, on a server that holds the\n * admin credential.\n *\n * ## What the role check is\n *\n * Admin or editor on the site — deliberately the SAME role the send path\n * requires, and checked the same way. Whoever may address these people may\n * see which of them opened; a page that were readable by anyone the campaign\n * report is readable by would hand the address list to a role that cannot\n * mail it.\n *\n * ## What comes back, and what does not\n *\n * The rows carry the recipient address, because that is the question. They do\n * not carry the sha256 key, the suppression state, or anything about mail\n * this site did not send: the query is filtered on `hostId` as well as on the\n * message ids, so a row belonging to another site cannot be returned even if\n * a message id were wrong.\n *\n * ## Two scopes, one route\n *\n * `emailId` reads one message; `screenId` reads every message built from one\n * template. They are one route because they are one question asked at two\n * altitudes, and splitting them would mean two role checks, two cursors and\n * two chances for one of them to drift out of agreement with the other.\n */\nexport const campaignRecipientsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const hostId = String(req.body?.hostId ?? '')\n const screenId = String(req.body?.screenId ?? '')\n const emailId = String(req.body?.emailId ?? '')\n const rawFilter = String(req.body?.filter ?? 'all')\n const cursor = String(req.body?.cursor ?? '')\n if (!isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n /*\n * ONE scope, named, and validated as a document id.\n *\n * Both are path components on the reads below, so \"non-empty\" was never the\n * whole question: a value carrying a slash names the nesting as well as the\n * document. Refusing both-or-neither rather than preferring one keeps the\n * answer a function of what was asked, so a caller who sends both because a\n * component forgot to clear a prop is told rather than silently served the\n * wrong scope.\n */\n if (Boolean(screenId) === Boolean(emailId)) {\n return res.status(400).json({ error: 'Name one of screenId or emailId' })\n }\n if (screenId && !isDocumentId(screenId)) {\n return res.status(400).json({ error: 'Invalid screenId' })\n }\n if (emailId && !isDocumentId(emailId)) {\n return res.status(400).json({ error: 'Invalid emailId' })\n }\n const filter: EmailEngagementFilter =\n rawFilter === 'opened' || rawFilter === 'clicked' ? rawFilter : 'all'\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 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 /*\n * The messages are the organization's, one collection for every site, so\n * each read below is narrowed to the ones sent as THIS site — by equality\n * on the template query, and by the stored site on a single message.\n */\n const orgId = await resolveOrgIdForHost(hostId)\n if (!orgId) {\n return res.status(404).json({ error: emailId ? 'Unknown email' : 'Unknown design' })\n }\n const sends = orgCampaignSends(firestore, orgId)\n\n /*\n * The messages this read covers.\n *\n * A single message is its own id and costs no query. A TEMPLATE resolves\n * to its messages here rather than taking a list of ids from the request:\n * a caller who could name message ids could name another site's, and\n * while the `hostId` filter below would still refuse them, the narrower\n * input is the one that cannot be got wrong later.\n *\n * ORDERED BY DOCUMENT ID, not by date, and that is forced rather than\n * chosen. A sent message carries `sentAt` and a scheduled one carries\n * `sendAtMs`; `orderBy` DROPS every document missing the ordered field,\n * so ordering on either would silently hide half the template's messages.\n * The document id is the one ordering every message satisfies, it needs\n * no composite index beside the two equality filters — Firestore merges\n * their single-field indexes in document-id order — and the messages are\n * then sorted by send time here — over a window already read, so the\n * \"most recent\" the caller is told about really is the most recent.\n *\n * One MORE than the reader can span, so the overflow is a fact rather\n * than the surface silently describing thirty messages as if they were\n * all of them.\n */\n const ceiling = EMAIL_SEND_ENGAGEMENT_MAX_SENDS + 1\n const messageDocs = emailId\n ? [await sends.doc(emailId).get()].filter(\n (snapshot: any) => snapshot.exists && sendIsOnHost(snapshot, hostId),\n )\n : (\n await sends\n .where(CAMPAIGN_SEND_HOST_FIELD, '==', hostId)\n .where('templateScreenId', '==', screenId)\n .orderBy(FieldPath.documentId())\n .limit(ceiling)\n .get()\n ).docs\n if (emailId && !messageDocs.length) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n const ordered = [...messageDocs].sort(\n (a: any, b: any) => messageTimeMs(b) - messageTimeMs(a),\n )\n const campaignIds = ordered.map((doc: any) => doc.id)\n const subjects: Record<string, string> = {}\n for (const doc of ordered) {\n subjects[doc.id] = String(doc.get('subject') ?? '')\n }\n\n const page = await readSendEngagement({\n hostId,\n sendIds: campaignIds,\n filter,\n cursor: cursor || null,\n firestore,\n })\n\n return res.status(200).json({\n /*\n * The rows, reduced to what the table renders. Not the stored document:\n * `provider`, `bounceType` and `detail` are operational fields a\n * merchant has no reading for, and shipping every field of an internal\n * record to a browser is how one becomes an accidental contract.\n */\n rows: page.rows.map((row) => ({\n messageId: row.messageId,\n to: row.to,\n subject: row.subject ?? subjects[row.campaignId ?? ''] ?? null,\n campaignId: row.campaignId,\n status: row.status,\n openCount: row.openCount,\n clickCount: row.clickCount,\n clickedLinks: row.clickedLinks,\n firstSeenAtMs: row.firstSeenAtMs,\n lastEventAtMs:\n row.timestamps.clicked ??\n row.timestamps.opened ??\n row.timestamps.delivered ??\n row.firstSeenAtMs,\n })),\n cursor: page.cursor,\n lookupFailed: page.lookupFailed,\n campaignsRead: campaignIds.length - page.sendsOmitted,\n campaignsOmitted: page.sendsOmitted,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Could not read recipients' })\n }\n}\n"],"names":["firebaseAdmin","resolveOrgIdForHost","readSendEngagement","EMAIL_SEND_ENGAGEMENT_MAX_SENDS","isDocumentId","FieldPath","CAMPAIGN_SEND_HOST_FIELD","orgCampaignSends","sendIsOnHost","messageTimeMs","snapshot","sentAt","get","toMillis","scheduled","Number","isFinite","campaignRecipientsHandler","req","res","method","status","json","error","hostId","String","body","screenId","emailId","rawFilter","filter","cursor","Boolean","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","exists","memberRole","uid","orgId","sends","ceiling","messageDocs","where","orderBy","documentId","limit","docs","ordered","sort","a","b","campaignIds","map","id","subjects","page","sendIds","rows","row","messageId","to","subject","campaignId","openCount","clickCount","clickedLinks","firstSeenAtMs","lastEventAtMs","timestamps","clicked","opened","delivered","lookupFailed","campaignsRead","sendsOmitted","campaignsOmitted","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AAC7E,4EAA4E;AAC5E,yEAAyE;AACzE,2EAA2E;AAC3E,+CAA+C;AAC/C,SACEC,kBAAkB,EAClBC,+BAA+B,QAE1B,qDAAoD;AAC3D,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,wBAAwB,QAAQ,iCAA6B;AACtE,SAASC,gBAAgB,EAAEC,YAAY,QAAQ,yBAAqB;AAEpE;;;;;;;CAOC,GACD,SAASC,cAAcC,QAAa;QAGTA;IAFzB,MAAMC,SAASD,SAASE,GAAG,CAAC;IAC5B,IAAI,QAAOD,0BAAAA,OAAQE,QAAQ,MAAK,YAAY,OAAOF,OAAOE,QAAQ;IAClE,MAAMC,YAAYC,QAAOL,gBAAAA,SAASE,GAAG,CAAC,uBAAbF,gBAA4B;IACrD,OAAOK,OAAOC,QAAQ,CAACF,aAAaA,YAAY;AAClD;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCC,GACD,OAAO,MAAMG,4BAA8C,OAAOC,KAAKC;0CAmCxCD;QA9BPA,WACEA,YACDA,YACEA,YACHA;IARtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IAEA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,WAAWF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,QAAQ,oBAAI;IAC9C,MAAMC,UAAUH,i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B,YAAY;QACrC;IACF,EAAE,OAAOjE,OAAO;QACdmE,QAAQnE,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA4B;IACnE;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-recipients.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\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { MARKETING_CAMPAIGNS_REFUSAL, MARKETING_CAMPAIGNS_SITE_ROLE_PRESET } from '../model/marketing-permissions'\nimport { firebaseAdmin, resolveOrgIdForHost } from '@aglyn/tenant-data-admin'\n// Leaf imports, for the reason `email-events.ts` records: a spec that mocks\n// the `@aglyn/tenant-data-admin` barrel would otherwise replace the real\n// delivery-log reader with whatever the factory listed, and this handler's\n// whole behaviour is what that reader returns.\nimport {\n readSendEngagement,\n EMAIL_SEND_ENGAGEMENT_MAX_SENDS,\n type EmailEngagementFilter,\n} from '@aglyn/tenant-data-admin/server/email-delivery-log'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { FieldPath } from 'firebase-admin/firestore'\nimport { CAMPAIGN_SEND_HOST_FIELD } from '../model/campaign-container'\nimport { orgCampaignSends, sendIsOnHost } from './campaign-org-refs'\n\n/**\n * When a message went out, or is due to.\n *\n * There is no one date field: the send path writes `sentAt` from one branch\n * and `sendAtMs` from the other, and nothing stamps a `createdAt`. Both are\n * read so a scheduled message sorts beside a sent one instead of falling to\n * the bottom of every list that touches it.\n */\nfunction messageTimeMs(snapshot: any): number {\n const sentAt = snapshot.get('sentAt')\n if (typeof sentAt?.toMillis === 'function') return sentAt.toMillis()\n const scheduled = Number(snapshot.get('sendAtMs') ?? 0)\n return Number.isFinite(scheduled) ? scheduled : 0\n}\n\n/**\n * WHO OPENED THIS, ONE PAGE AT A TIME.\n *\n * ## Why a server route rather than a client listen\n *\n * The per-recipient delivery log lives at `emailDeliveries/{sha256(address)}`\n * — a platform-level collection keyed by a hash of an address, holding the\n * mail of every site on the install and every transactional message besides.\n * No security rule can express \"this site's editors may read the rows tagged\n * with this site\" over a collection-group query, because the predicate that\n * narrows it is the query's own `where`, and a rule cannot require one. So\n * the narrowing happens here, behind a role check, on a server that holds the\n * admin credential.\n *\n * ## What the role check is\n *\n * Admin or editor on the site — deliberately the SAME role the send path\n * requires, and checked the same way. Whoever may address these people may\n * see which of them opened; a page that were readable by anyone the campaign\n * report is readable by would hand the address list to a role that cannot\n * mail it.\n *\n * ## What comes back, and what does not\n *\n * The rows carry the recipient address, because that is the question. They do\n * not carry the sha256 key, the suppression state, or anything about mail\n * this site did not send: the query is filtered on `hostId` as well as on the\n * message ids, so a row belonging to another site cannot be returned even if\n * a message id were wrong.\n *\n * ## Two scopes, one route\n *\n * `emailId` reads one message; `screenId` reads every message built from one\n * template. They are one route because they are one question asked at two\n * altitudes, and splitting them would mean two role checks, two cursors and\n * two chances for one of them to drift out of agreement with the other.\n */\nexport const campaignRecipientsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n\n const hostId = String(req.body?.hostId ?? '')\n const screenId = String(req.body?.screenId ?? '')\n const emailId = String(req.body?.emailId ?? '')\n const rawFilter = String(req.body?.filter ?? 'all')\n const cursor = String(req.body?.cursor ?? '')\n if (!isDocumentId(hostId)) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n /*\n * ONE scope, named, and validated as a document id.\n *\n * Both are path components on the reads below, so \"non-empty\" was never the\n * whole question: a value carrying a slash names the nesting as well as the\n * document. Refusing both-or-neither rather than preferring one keeps the\n * answer a function of what was asked, so a caller who sends both because a\n * component forgot to clear a prop is told rather than silently served the\n * wrong scope.\n */\n if (Boolean(screenId) === Boolean(emailId)) {\n return res.status(400).json({ error: 'Name one of screenId or emailId' })\n }\n if (screenId && !isDocumentId(screenId)) {\n return res.status(400).json({ error: 'Invalid screenId' })\n }\n if (emailId && !isDocumentId(emailId)) {\n return res.status(400).json({ error: 'Invalid emailId' })\n }\n const filter: EmailEngagementFilter =\n rawFilter === 'opened' || rawFilter === 'clicked' ? rawFilter : 'all'\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 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 // \"Run email campaigns\" (AGL-4047): the site's stamp, else the preset of\n // the member's site role, the Admin and Editor this asked for before.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketing.campaigns', MARKETING_CAMPAIGNS_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: MARKETING_CAMPAIGNS_REFUSAL })\n }\n /*\n * The messages are the organization's, one collection for every site, so\n * each read below is narrowed to the ones sent as THIS site — by equality\n * on the template query, and by the stored site on a single message.\n */\n const orgId = await resolveOrgIdForHost(hostId)\n if (!orgId) {\n return res.status(404).json({ error: emailId ? 'Unknown email' : 'Unknown design' })\n }\n const sends = orgCampaignSends(firestore, orgId)\n\n /*\n * The messages this read covers.\n *\n * A single message is its own id and costs no query. A TEMPLATE resolves\n * to its messages here rather than taking a list of ids from the request:\n * a caller who could name message ids could name another site's, and\n * while the `hostId` filter below would still refuse them, the narrower\n * input is the one that cannot be got wrong later.\n *\n * ORDERED BY DOCUMENT ID, not by date, and that is forced rather than\n * chosen. A sent message carries `sentAt` and a scheduled one carries\n * `sendAtMs`; `orderBy` DROPS every document missing the ordered field,\n * so ordering on either would silently hide half the template's messages.\n * The document id is the one ordering every message satisfies, it needs\n * no composite index beside the two equality filters — Firestore merges\n * their single-field indexes in document-id order — and the messages are\n * then sorted by send time here — over a window already read, so the\n * \"most recent\" the caller is told about really is the most recent.\n *\n * One MORE than the reader can span, so the overflow is a fact rather\n * than the surface silently describing thirty messages as if they were\n * all of them.\n */\n const ceiling = EMAIL_SEND_ENGAGEMENT_MAX_SENDS + 1\n const messageDocs = emailId\n ? [await sends.doc(emailId).get()].filter(\n (snapshot: any) => snapshot.exists && sendIsOnHost(snapshot, hostId),\n )\n : (\n await sends\n .where(CAMPAIGN_SEND_HOST_FIELD, '==', hostId)\n .where('templateScreenId', '==', screenId)\n .orderBy(FieldPath.documentId())\n .limit(ceiling)\n .get()\n ).docs\n if (emailId && !messageDocs.length) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n const ordered = [...messageDocs].sort(\n (a: any, b: any) => messageTimeMs(b) - messageTimeMs(a),\n )\n const campaignIds = ordered.map((doc: any) => doc.id)\n const subjects: Record<string, string> = {}\n for (const doc of ordered) {\n subjects[doc.id] = String(doc.get('subject') ?? '')\n }\n\n const page = await readSendEngagement({\n hostId,\n sendIds: campaignIds,\n filter,\n cursor: cursor || null,\n firestore,\n })\n\n return res.status(200).json({\n /*\n * The rows, reduced to what the table renders. Not the stored document:\n * `provider`, `bounceType` and `detail` are operational fields a\n * merchant has no reading for, and shipping every field of an internal\n * record to a browser is how one becomes an accidental contract.\n */\n rows: page.rows.map((row) => ({\n messageId: row.messageId,\n to: row.to,\n subject: row.subject ?? subjects[row.campaignId ?? ''] ?? null,\n campaignId: row.campaignId,\n status: row.status,\n openCount: row.openCount,\n clickCount: row.clickCount,\n clickedLinks: row.clickedLinks,\n firstSeenAtMs: row.firstSeenAtMs,\n lastEventAtMs:\n row.timestamps.clicked ??\n row.timestamps.opened ??\n row.timestamps.delivered ??\n row.firstSeenAtMs,\n })),\n cursor: page.cursor,\n lookupFailed: page.lookupFailed,\n campaignsRead: campaignIds.length - page.sendsOmitted,\n campaignsOmitted: page.sendsOmitted,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Could not read recipients' })\n }\n}\n"],"names":["holdsStampedSiteKey","MARKETING_CAMPAIGNS_REFUSAL","MARKETING_CAMPAIGNS_SITE_ROLE_PRESET","firebaseAdmin","resolveOrgIdForHost","readSendEngagement","EMAIL_SEND_ENGAGEMENT_MAX_SENDS","isDocumentId","FieldPath","CAMPAIGN_SEND_HOST_FIELD","orgCampaignSends","sendIsOnHost","messageTimeMs","snapshot","sentAt","get","toMillis","scheduled","Number","isFinite","campaignRecipientsHandler","req","res","method","status","json","error","hostId","String","body","screenId","emailId","rawFilter","filter","cursor","Boolean","authorization","headers","idToken","startsWith","slice","length","undefined","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","exists","uid","orgId","sends","ceiling","messageDocs","where","orderBy","documentId","limit","docs","ordered","sort","a","b","campaignIds","map","id","subjects","page","sendIds","rows","row","messageId","to","subject","campaignId","openCount","clickCount","clickedLinks","firstSeenAtMs","lastEventAtMs","timestamps","clicked","opened","delivered","lookupFailed","campaignsRead","sendsOmitted","campaignsOmitted","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAE7E,SAASC,2BAA2B,EAAEC,oCAAoC,QAAQ,oCAAgC;AAClH,SAASC,aAAa,EAAEC,mBAAmB,QAAQ,2BAA0B;AAC7E,4EAA4E;AAC5E,yEAAyE;AACzE,2EAA2E;AAC3E,+CAA+C;AAC/C,SACEC,kBAAkB,EAClBC,+BAA+B,QAE1B,qDAAoD;AAC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B;;;;;OAKC,GACDgD,MAAMF,KAAKE,IAAI,CAACL,GAAG,CAAC,CAACM;oBAGVA,MAAAA,cAAwBA,iBAQ/BA,OAAAA,OAAAA;uBAX0B;oBAC5BC,WAAWD,IAAIC,SAAS;oBACxBC,IAAIF,IAAIE,EAAE;oBACVC,OAAO,GAAEH,QAAAA,eAAAA,IAAIG,OAAO,YAAXH,eAAeJ,QAAQ,EAACI,kBAAAA,IAAII,UAAU,YAAdJ,kBAAkB,GAAG,YAA7CA,OAAiD;oBAC1DI,YAAYJ,IAAII,UAAU;oBAC1BtD,QAAQkD,IAAIlD,MAAM;oBAClBuD,WAAWL,IAAIK,SAAS;oBACxBC,YAAYN,IAAIM,UAAU;oBAC1BC,cAAcP,IAAIO,YAAY;oBAC9BC,eAAeR,IAAIQ,aAAa;oBAChCC,aAAa,GACXT,SAAAA,SAAAA,0BAAAA,IAAIU,UAAU,CAACC,OAAO,YAAtBX,0BACAA,IAAIU,UAAU,CAACE,MAAM,YADrBZ,QAEAA,IAAIU,UAAU,CAACG,SAAS,YAFxBb,QAGAA,IAAIQ,aAAa;gBACrB;;YACAhD,QAAQqC,KAAKrC,MAAM;YACnBsD,cAAcjB,KAAKiB,YAAY;YAC/BC,eAAetB,YAAY1B,MAAM,GAAG8B,KAAKmB,YAAY;YACrDC,kBAAkBpB,KAAKmB,YAAY;QACrC;IACF,EAAE,OAAOhE,OAAO;QACdkE,QAAQlE,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA4B;IACnE;AACF,EAAC"}
|
|
@@ -46,6 +46,8 @@ import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
|
|
|
46
46
|
* Resolved from the module itself, the real predicate runs under every
|
|
47
47
|
* harness.
|
|
48
48
|
*/ import { isImpersonationSession } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
49
|
+
import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
50
|
+
import { MARKETING_CAMPAIGNS_REFUSAL, MARKETING_CAMPAIGNS_SITE_ROLE_PRESET } from "../model/marketing-permissions.js";
|
|
49
51
|
/*
|
|
50
52
|
* The LEAF module, not the barrel, for the reason `document-id` is imported
|
|
51
53
|
* the same way: a barrel import resolves to whatever a spec's `jest.mock` of
|
|
@@ -2929,7 +2931,7 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
|
|
|
2929
2931
|
error: 'Unauthenticated'
|
|
2930
2932
|
});
|
|
2931
2933
|
try {
|
|
2932
|
-
var
|
|
2934
|
+
var _ref11, _ref12, _ref13, _ref14, _ref15;
|
|
2933
2935
|
var _req_body15, _req_body16, _req_body17, _req_body18, _req_body19;
|
|
2934
2936
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
2935
2937
|
/*
|
|
@@ -2971,10 +2973,11 @@ function storedSendOptionsFrom(snapshot, hostId, senderUid, followUp) {
|
|
|
2971
2973
|
error: 'Unknown site'
|
|
2972
2974
|
});
|
|
2973
2975
|
}
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
+
// "Run email campaigns" (AGL-4047): the site's stamp, else the preset of
|
|
2977
|
+
// the member's site role, the Admin and Editor this asked for before.
|
|
2978
|
+
if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketing.campaigns', MARKETING_CAMPAIGNS_SITE_ROLE_PRESET)) {
|
|
2976
2979
|
return res.status(403).json({
|
|
2977
|
-
error:
|
|
2980
|
+
error: MARKETING_CAMPAIGNS_REFUSAL
|
|
2978
2981
|
});
|
|
2979
2982
|
}
|
|
2980
2983
|
/*==========================================
|