@aglyn/plugins-marketing 1.0.0-beta.172 → 1.0.0-beta.174
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/README.md +2 -1
- package/package.json +15 -15
- package/src/lib/components/campaign-detail-card.d.ts +12 -1
- package/src/lib/components/campaign-detail-card.js +146 -35
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-edit-drawer.d.ts +13 -0
- package/src/lib/components/campaign-edit-drawer.js +56 -4
- package/src/lib/components/campaign-edit-drawer.js.map +1 -1
- package/src/lib/components/campaign-glance-card.component.js +10 -2
- package/src/lib/components/campaign-glance-card.component.js.map +1 -1
- package/src/lib/components/campaign-members-section.d.ts +6 -0
- package/src/lib/components/campaign-members-section.js +2 -2
- package/src/lib/components/campaign-members-section.js.map +1 -1
- package/src/lib/components/campaign-queries.d.ts +58 -0
- package/src/lib/components/campaign-queries.js +72 -0
- package/src/lib/components/campaign-queries.js.map +1 -0
- package/src/lib/components/campaign-reach-sections.d.ts +21 -7
- package/src/lib/components/campaign-reach-sections.js +20 -17
- package/src/lib/components/campaign-reach-sections.js.map +1 -1
- package/src/lib/components/campaign-report-card.d.ts +8 -1
- package/src/lib/components/campaign-report-card.js +33 -16
- package/src/lib/components/campaign-report-card.js.map +1 -1
- package/src/lib/components/campaigns-card.d.ts +10 -1
- package/src/lib/components/campaigns-card.js +102 -19
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/email-compose-card.d.ts +3 -2
- package/src/lib/components/email-compose-card.js +18 -7
- package/src/lib/components/email-compose-card.js.map +1 -1
- package/src/lib/components/email-detail.d.ts +11 -2
- package/src/lib/components/email-detail.js +50 -23
- package/src/lib/components/email-detail.js.map +1 -1
- package/src/lib/components/emails-list-card.d.ts +10 -1
- package/src/lib/components/emails-list-card.js +129 -23
- package/src/lib/components/emails-list-card.js.map +1 -1
- package/src/lib/components/host-marketing-summary-card.component.js +9 -1
- package/src/lib/components/host-marketing-summary-card.component.js.map +1 -1
- package/src/lib/components/marketing-console-page.js +81 -4
- package/src/lib/components/marketing-console-page.js.map +1 -1
- package/src/lib/components/marketing-console-sections.d.ts +16 -1
- package/src/lib/components/marketing-console-sections.js +25 -2
- package/src/lib/components/marketing-console-sections.js.map +1 -1
- package/src/lib/components/marketing-org-mount.d.ts +71 -0
- package/src/lib/components/marketing-org-mount.js +84 -0
- package/src/lib/components/marketing-org-mount.js.map +1 -0
- package/src/lib/components/use-campaign-send-api.d.ts +2 -2
- package/src/lib/components/use-campaign-send-api.js +22 -6
- package/src/lib/components/use-campaign-send-api.js.map +1 -1
- package/src/lib/components/use-emails-hub-path.d.ts +13 -3
- package/src/lib/components/use-emails-hub-path.js +25 -4
- package/src/lib/components/use-emails-hub-path.js.map +1 -1
- package/src/lib/components/use-marketing-hub-path.d.ts +19 -16
- package/src/lib/components/use-marketing-hub-path.js +6 -32
- package/src/lib/components/use-marketing-hub-path.js.map +1 -1
- package/src/lib/model/marketing-record-routes.js +11 -4
- package/src/lib/model/marketing-record-routes.js.map +1 -1
- package/src/lib/plugin.js +31 -1
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/campaign-manage.d.ts +31 -2
- package/src/lib/server/campaign-manage.js +365 -137
- package/src/lib/server/campaign-manage.js.map +1 -1
- package/src/lib/server/campaign-org-refs.d.ts +45 -0
- package/src/lib/server/campaign-org-refs.js +83 -0
- package/src/lib/server/campaign-org-refs.js.map +1 -0
- package/src/lib/server/campaign-process-scheduled.d.ts +32 -2
- package/src/lib/server/campaign-process-scheduled.js +79 -9
- package/src/lib/server/campaign-process-scheduled.js.map +1 -1
- package/src/lib/server/campaign-recipients.js +18 -4
- package/src/lib/server/campaign-recipients.js.map +1 -1
- package/src/lib/server/campaign-send.js +139 -55
- package/src/lib/server/campaign-send.js.map +1 -1
- package/src/lib/server/email-campaign-reach.d.ts +6 -5
- package/src/lib/server/email-campaign-reach.js +14 -14
- package/src/lib/server/email-campaign-reach.js.map +1 -1
- package/src/lib/server/email-events.js +48 -17
- package/src/lib/server/email-events.js.map +1 -1
- package/src/lib/server/marketing-figures.js +12 -1
- package/src/lib/server/marketing-figures.js.map +1 -1
- package/src/lib/server.js +7 -3
- package/src/lib/server.js.map +1 -1
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
*/ import { PLUGIN_FIGURE_MAX_ROWS, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
17
17
|
import { campaignReport } from "@aglyn/shared-ui-email-campaigns/model/campaign-report";
|
|
18
18
|
import { EMAIL_CREATED_AT_FIELD, emailSendTimeMs } from "@aglyn/shared-ui-email-campaigns/model/email-record";
|
|
19
|
+
import { CAMPAIGN_SEND_HOST_FIELD } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
|
|
20
|
+
import { orgCampaignSends } from "./campaign-org-refs.js";
|
|
19
21
|
import { compareVariants, summarizeVariantStats } from "../model/experiments.js";
|
|
20
22
|
const MARKETING_PLUGIN_ID = 'marketing';
|
|
21
23
|
/** Sends a campaign table reads, newest first, before it keeps those sent in the window. */ export const CAMPAIGN_FIGURES_READ_LIMIT = 100;
|
|
@@ -54,8 +56,17 @@ export function marketingFigureReaders(firestore) {
|
|
|
54
56
|
error: 'That window is not one campaigns are read over'
|
|
55
57
|
};
|
|
56
58
|
}
|
|
59
|
+
if (!request.orgId) return {
|
|
60
|
+
ok: false,
|
|
61
|
+
status: 400,
|
|
62
|
+
error: 'This site is not part of an organization'
|
|
63
|
+
};
|
|
57
64
|
const { current } = pluginFigureWindows(request.now, request.days);
|
|
58
|
-
|
|
65
|
+
/*
|
|
66
|
+
* The organization's sends, narrowed to the ones sent as this site.
|
|
67
|
+
* Served by the composite index on the site field and the creation
|
|
68
|
+
* stamp — the equality and the ordering together are one index.
|
|
69
|
+
*/ const snapshot = await orgCampaignSends(firestore(), request.orgId).where(CAMPAIGN_SEND_HOST_FIELD, '==', request.hostId).orderBy(EMAIL_CREATED_AT_FIELD, 'desc').limit(CAMPAIGN_FIGURES_READ_LIMIT).get();
|
|
59
70
|
const sends = snapshot.docs.map((doc)=>{
|
|
60
71
|
var _doc_data;
|
|
61
72
|
return (_doc_data = doc.data()) != null ? _doc_data : {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/marketing-figures.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 {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRow,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n campaignReport,\n type CampaignRate,\n type CampaignStats,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-report'\nimport {\n EMAIL_CREATED_AT_FIELD,\n emailSendTimeMs,\n} from '@aglyn/shared-ui-email-campaigns/model/email-record'\nimport { compareVariants, summarizeVariantStats, type HostExperiment } from '../model/experiments'\n\n/**\n * A site's campaign and A/B testing results as figure tables another plugin\n * reads by id (AGL-2915).\n *\n * The campaign table is what each send's report shows — delivered, and the\n * open and click rates over delivered — through `campaignReport`, the one\n * reader of a send's counters. The experiments table is what the A/B testing\n * section shows, through the same variant comparison. No recipient, address\n * or visitor reaches either: a campaign is named by its subject, a variant by\n * its name.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst MARKETING_PLUGIN_ID = 'marketing'\n\n/** Sends a campaign table reads, newest first, before it keeps those sent in the window. */\nexport const CAMPAIGN_FIGURES_READ_LIMIT = 100\n\n/** Experiments an experiments table reads. */\nexport const EXPERIMENT_FIGURES_READ_LIMIT = 20\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\nconst percent = (rate: CampaignRate | null): number | null =>\n rate ? Math.round(rate.value * 1_000) / 10 : null\n\n/** Rates pooled across sends: every numerator over every denominator, never an average of rates. */\nfunction pooled(rates: ReadonlyArray<CampaignRate | null>): number | null {\n const known = rates.filter((rate): rate is CampaignRate => rate !== null)\n const denominator = known.reduce((sum, rate) => sum + rate.denominator, 0)\n if (!denominator) return null\n return Math.round((known.reduce((sum, rate) => sum + rate.numerator, 0) / denominator) * 1_000) / 10\n}\n\nexport function marketingFigureReaders(firestore: () => Firestore): PluginFigureReader[] {\n return [\n {\n id: 'marketing.campaigns',\n label: 'Campaigns',\n description:\n 'Each campaign email sent from the site in the window: how many were delivered and the share of delivered messages opened and clicked, with every campaign together on the first row.',\n scope: 'site',\n windows: WINDOWS,\n read: async (request) => {\n if (!request.hostId) return { ok: false, status: 400, error: 'Open a site to read its campaigns' }\n if (!WINDOWS.includes(request.days)) {\n return { ok: false, status: 400, error: 'That window is not one campaigns are read over' }\n }\n const { current } = pluginFigureWindows(request.now, request.days)\n const snapshot = await firestore()\n .collection('hosts')\n .doc(request.hostId)\n .collection('campaigns')\n .orderBy(EMAIL_CREATED_AT_FIELD, 'desc')\n .limit(CAMPAIGN_FIGURES_READ_LIMIT)\n .get()\n const sends = snapshot.docs\n .map((doc) => doc.data() ?? {})\n .filter((record) => {\n const sentAt = emailSendTimeMs(record)\n return Boolean(record['sentAt']) && sentAt >= current.startMs && sentAt < current.endMs\n })\n .map((record) => ({\n subject: String(record['subject'] ?? '').trim() || 'A campaign with no subject',\n report: campaignReport(record['stats'] as CampaignStats | undefined),\n }))\n const rows: PluginFigureRow[] = [\n {\n campaign: 'All campaigns',\n delivered: sends.every((send) => send.report.delivered === null)\n ? null\n : sends.reduce((sum, send) => sum + (send.report.delivered ?? 0), 0),\n openRate: pooled(sends.map((send) => send.report.rates.open)),\n clickRate: pooled(sends.map((send) => send.report.rates.click)),\n },\n ...sends.slice(0, PLUGIN_FIGURE_MAX_ROWS - 1).map((send) => ({\n campaign: send.subject,\n delivered: send.report.delivered,\n openRate: percent(send.report.rates.open),\n clickRate: percent(send.report.rates.click),\n })),\n ]\n return {\n ok: true,\n table: {\n title: 'Campaigns',\n source: { label: 'Campaigns', path: 'marketing/campaigns' },\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'campaign', label: 'Campaign', kind: 'text' },\n { key: 'delivered', label: 'Delivered', kind: 'count' },\n { key: 'openRate', label: 'Opened', kind: 'percent' },\n { key: 'clickRate', label: 'Clicked', kind: 'percent' },\n ],\n rows,\n omitted: Math.max(0, sends.length - (PLUGIN_FIGURE_MAX_ROWS - 1)),\n notes: [\n 'Rates are over delivered messages, and a campaign with no delivery recorded has none.',\n ...(snapshot.docs.length === CAMPAIGN_FIGURES_READ_LIMIT\n ? [`Only the ${CAMPAIGN_FIGURES_READ_LIMIT} most recent emails were looked at.`]\n : []),\n ],\n },\n }\n },\n },\n {\n id: 'marketing.experiments',\n label: 'A/B tests',\n description:\n 'Each running or finished A/B test on the site: every variant’s visitors shown it, conversions and conversion rate, with the lift over the first variant and how confident that lift is.',\n scope: 'site',\n windows: [],\n feature: 'abTesting',\n read: async (request) => {\n if (!request.hostId) return { ok: false, status: 400, error: 'Open a site to read its A/B tests' }\n const experimentsRef = firestore().collection('hosts').doc(request.hostId).collection('experiments')\n const snapshot = await experimentsRef.limit(EXPERIMENT_FIGURES_READ_LIMIT).get()\n const rows: PluginFigureRow[] = []\n for (const doc of snapshot.docs) {\n const experiment = (doc.data() ?? {}) as Partial<HostExperiment>\n if (experiment.status !== 'running' && experiment.status !== 'done') continue\n const variants = (experiment.variants ?? []).slice(0, 4)\n if (!variants.length) continue\n const stats = await doc.ref.collection('stats').get()\n const byVariant = new Map(stats.docs.map((entry) => [entry.id, entry.data() ?? {}]))\n const control = byVariant.get(variants[0].id) ?? {}\n variants.forEach((variant, index) => {\n const own = byVariant.get(variant.id) ?? {}\n const summary = summarizeVariantStats(own)\n const comparison = index === 0 ? null : compareVariants(control, own)\n rows.push({\n test: String(experiment.name ?? '').trim() || doc.id,\n variant: String(variant.name ?? '').trim() || variant.id,\n shown: summary.exposures,\n conversions: summary.conversions,\n rate: summary.exposures ? Math.round(summary.rate * 1_000) / 10 : null,\n lift: comparison?.lift === null || comparison === null ? null : Math.round(comparison.lift * 1_000) / 10,\n confidence:\n comparison?.confidence === null || comparison === null\n ? null\n : Math.round(comparison.confidence * 1_000) / 10,\n })\n })\n }\n return {\n ok: true,\n table: {\n title: 'A/B tests',\n source: { label: 'A/B testing', path: 'marketing/experiments' },\n period: null,\n columns: [\n { key: 'test', label: 'Test', kind: 'text' },\n { key: 'variant', label: 'Variant', kind: 'text' },\n { key: 'shown', label: 'Shown', kind: 'count' },\n { key: 'conversions', label: 'Conversions', kind: 'count' },\n { key: 'rate', label: 'Conversion rate', kind: 'percent' },\n { key: 'lift', label: 'Lift over the first variant', kind: 'change' },\n { key: 'confidence', label: 'Confidence in the lift', kind: 'percent' },\n ],\n rows: rows.slice(0, PLUGIN_FIGURE_MAX_ROWS),\n omitted: Math.max(0, rows.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: ['Figures are totals since each test started; the first variant of a test is its control.'],\n },\n }\n },\n },\n ]\n}\n\n/** Registers the campaign and A/B testing readers from the console surface, where insight jobs run. */\nexport function registerMarketingFigureReaders(firestore: () => Firestore): void {\n for (const reader of marketingFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: MARKETING_PLUGIN_ID })\n }\n}\n"],"names":["PLUGIN_FIGURE_MAX_ROWS","pluginFigureWindows","registerPluginFigureReader","campaignReport","EMAIL_CREATED_AT_FIELD","emailSendTimeMs","compareVariants","summarizeVariantStats","MARKETING_PLUGIN_ID","CAMPAIGN_FIGURES_READ_LIMIT","EXPERIMENT_FIGURES_READ_LIMIT","WINDOWS","percent","rate","Math","round","value","pooled","rates","known","filter","denominator","reduce","sum","numerator","marketingFigureReaders","firestore","id","label","description","scope","windows","read","request","hostId","ok","status","error","includes","days","current","now","snapshot","collection","doc","orderBy","limit","get","sends","docs","map","data","record","sentAt","Boolean","startMs","endMs","subject","String","trim","report","rows","campaign","delivered","every","send","openRate","open","clickRate","click","slice","table","title","source","path","period","from","to","columns","key","kind","omitted","max","length","notes","feature","experimentsRef","experiment","byVariant","variants","stats","ref","Map","entry","control","forEach","variant","index","own","summary","comparison","push","test","name","shown","exposures","conversions","lift","confidence","registerMarketingFigureReaders","reader","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,mBAAmB,EACnBC,0BAA0B,QAGrB,6CAA4C;AACnD,SACEC,cAAc,QAGT,yDAAwD;AAC/D,SACEC,sBAAsB,EACtBC,eAAe,QACV,sDAAqD;AAC5D,SAASC,eAAe,EAAEC,qBAAqB,QAA6B,0BAAsB;AAgBlG,MAAMC,sBAAsB;AAE5B,0FAA0F,GAC1F,OAAO,MAAMC,8BAA8B,IAAG;AAE9C,4CAA4C,GAC5C,OAAO,MAAMC,gCAAgC,GAAE;AAE/C,MAAMC,UAA6B;IAAC;IAAG;IAAI;IAAI;CAAG;AAElD,MAAMC,UAAU,CAACC,OACfA,OAAOC,KAAKC,KAAK,CAACF,KAAKG,KAAK,GAAG,QAAS,KAAK;AAE/C,kGAAkG,GAClG,SAASC,OAAOC,KAAyC;IACvD,MAAMC,QAAQD,MAAME,MAAM,CAAC,CAACP,OAA+BA,SAAS;IACpE,MAAMQ,cAAcF,MAAMG,MAAM,CAAC,CAACC,KAAKV,OAASU,MAAMV,KAAKQ,WAAW,EAAE;IACxE,IAAI,CAACA,aAAa,OAAO;IACzB,OAAOP,KAAKC,KAAK,CAAC,AAACI,MAAMG,MAAM,CAAC,CAACC,KAAKV,OAASU,MAAMV,KAAKW,SAAS,EAAE,KAAKH,cAAe,QAAS;AACpG;AAEA,OAAO,SA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BAC1D;gCAAED,KAAK;gCAAQnD,OAAO;gCAAmBoD,MAAM;4BAAU;4BACzD;gCAAED,KAAK;gCAAQnD,OAAO;gCAA+BoD,MAAM;4BAAS;4BACpE;gCAAED,KAAK;gCAAcnD,OAAO;gCAA0BoD,MAAM;4BAAU;yBACvE;wBACDnB,MAAMA,KAAKS,KAAK,CAAC,GAAGtE;wBACpBiF,SAASnE,KAAKoE,GAAG,CAAC,GAAGrB,KAAKsB,MAAM,GAAGnF;wBACnCoF,OAAO;4BAAC;yBAA0F;oBACpG;gBACF;YACF;QACF;KACD;AACH;AAEA,qGAAqG,GACrG,OAAO,SAASyB,+BAA+BnF,SAA0B;IACvE,KAAK,MAAMoF,UAAUrF,uBAAuBC,WAAY;QACtDxB,2BAA2B4G,QAAQ;YAAEC,UAAUvG;QAAoB;IACrE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/marketing-figures.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 {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRow,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n campaignReport,\n type CampaignRate,\n type CampaignStats,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-report'\nimport {\n EMAIL_CREATED_AT_FIELD,\n emailSendTimeMs,\n} from '@aglyn/shared-ui-email-campaigns/model/email-record'\nimport { CAMPAIGN_SEND_HOST_FIELD } from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport { orgCampaignSends } from './campaign-org-refs'\nimport { compareVariants, summarizeVariantStats, type HostExperiment } from '../model/experiments'\n\n/**\n * A site's campaign and A/B testing results as figure tables another plugin\n * reads by id (AGL-2915).\n *\n * The campaign table is what each send's report shows — delivered, and the\n * open and click rates over delivered — through `campaignReport`, the one\n * reader of a send's counters. The experiments table is what the A/B testing\n * section shows, through the same variant comparison. No recipient, address\n * or visitor reaches either: a campaign is named by its subject, a variant by\n * its name.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst MARKETING_PLUGIN_ID = 'marketing'\n\n/** Sends a campaign table reads, newest first, before it keeps those sent in the window. */\nexport const CAMPAIGN_FIGURES_READ_LIMIT = 100\n\n/** Experiments an experiments table reads. */\nexport const EXPERIMENT_FIGURES_READ_LIMIT = 20\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\nconst percent = (rate: CampaignRate | null): number | null =>\n rate ? Math.round(rate.value * 1_000) / 10 : null\n\n/** Rates pooled across sends: every numerator over every denominator, never an average of rates. */\nfunction pooled(rates: ReadonlyArray<CampaignRate | null>): number | null {\n const known = rates.filter((rate): rate is CampaignRate => rate !== null)\n const denominator = known.reduce((sum, rate) => sum + rate.denominator, 0)\n if (!denominator) return null\n return Math.round((known.reduce((sum, rate) => sum + rate.numerator, 0) / denominator) * 1_000) / 10\n}\n\nexport function marketingFigureReaders(firestore: () => Firestore): PluginFigureReader[] {\n return [\n {\n id: 'marketing.campaigns',\n label: 'Campaigns',\n description:\n 'Each campaign email sent from the site in the window: how many were delivered and the share of delivered messages opened and clicked, with every campaign together on the first row.',\n scope: 'site',\n windows: WINDOWS,\n read: async (request) => {\n if (!request.hostId) return { ok: false, status: 400, error: 'Open a site to read its campaigns' }\n if (!WINDOWS.includes(request.days)) {\n return { ok: false, status: 400, error: 'That window is not one campaigns are read over' }\n }\n if (!request.orgId) return { ok: false, status: 400, error: 'This site is not part of an organization' }\n const { current } = pluginFigureWindows(request.now, request.days)\n /*\n * The organization's sends, narrowed to the ones sent as this site.\n * Served by the composite index on the site field and the creation\n * stamp — the equality and the ordering together are one index.\n */\n const snapshot = await orgCampaignSends(firestore(), request.orgId)\n .where(CAMPAIGN_SEND_HOST_FIELD, '==', request.hostId)\n .orderBy(EMAIL_CREATED_AT_FIELD, 'desc')\n .limit(CAMPAIGN_FIGURES_READ_LIMIT)\n .get()\n const sends = snapshot.docs\n .map((doc) => doc.data() ?? {})\n .filter((record) => {\n const sentAt = emailSendTimeMs(record)\n return Boolean(record['sentAt']) && sentAt >= current.startMs && sentAt < current.endMs\n })\n .map((record) => ({\n subject: String(record['subject'] ?? '').trim() || 'A campaign with no subject',\n report: campaignReport(record['stats'] as CampaignStats | undefined),\n }))\n const rows: PluginFigureRow[] = [\n {\n campaign: 'All campaigns',\n delivered: sends.every((send) => send.report.delivered === null)\n ? null\n : sends.reduce((sum, send) => sum + (send.report.delivered ?? 0), 0),\n openRate: pooled(sends.map((send) => send.report.rates.open)),\n clickRate: pooled(sends.map((send) => send.report.rates.click)),\n },\n ...sends.slice(0, PLUGIN_FIGURE_MAX_ROWS - 1).map((send) => ({\n campaign: send.subject,\n delivered: send.report.delivered,\n openRate: percent(send.report.rates.open),\n clickRate: percent(send.report.rates.click),\n })),\n ]\n return {\n ok: true,\n table: {\n title: 'Campaigns',\n source: { label: 'Campaigns', path: 'marketing/campaigns' },\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'campaign', label: 'Campaign', kind: 'text' },\n { key: 'delivered', label: 'Delivered', kind: 'count' },\n { key: 'openRate', label: 'Opened', kind: 'percent' },\n { key: 'clickRate', label: 'Clicked', kind: 'percent' },\n ],\n rows,\n omitted: Math.max(0, sends.length - (PLUGIN_FIGURE_MAX_ROWS - 1)),\n notes: [\n 'Rates are over delivered messages, and a campaign with no delivery recorded has none.',\n ...(snapshot.docs.length === CAMPAIGN_FIGURES_READ_LIMIT\n ? [`Only the ${CAMPAIGN_FIGURES_READ_LIMIT} most recent emails were looked at.`]\n : []),\n ],\n },\n }\n },\n },\n {\n id: 'marketing.experiments',\n label: 'A/B tests',\n description:\n 'Each running or finished A/B test on the site: every variant’s visitors shown it, conversions and conversion rate, with the lift over the first variant and how confident that lift is.',\n scope: 'site',\n windows: [],\n feature: 'abTesting',\n read: async (request) => {\n if (!request.hostId) return { ok: false, status: 400, error: 'Open a site to read its A/B tests' }\n const experimentsRef = firestore().collection('hosts').doc(request.hostId).collection('experiments')\n const snapshot = await experimentsRef.limit(EXPERIMENT_FIGURES_READ_LIMIT).get()\n const rows: PluginFigureRow[] = []\n for (const doc of snapshot.docs) {\n const experiment = (doc.data() ?? {}) as Partial<HostExperiment>\n if (experiment.status !== 'running' && experiment.status !== 'done') continue\n const variants = (experiment.variants ?? []).slice(0, 4)\n if (!variants.length) continue\n const stats = await doc.ref.collection('stats').get()\n const byVariant = new Map(stats.docs.map((entry) => [entry.id, entry.data() ?? {}]))\n const control = byVariant.get(variants[0].id) ?? {}\n variants.forEach((variant, index) => {\n const own = byVariant.get(variant.id) ?? {}\n const summary = summarizeVariantStats(own)\n const comparison = index === 0 ? null : compareVariants(control, own)\n rows.push({\n test: String(experiment.name ?? '').trim() || doc.id,\n variant: String(variant.name ?? '').trim() || variant.id,\n shown: summary.exposures,\n conversions: summary.conversions,\n rate: summary.exposures ? Math.round(summary.rate * 1_000) / 10 : null,\n lift: comparison?.lift === null || comparison === null ? null : Math.round(comparison.lift * 1_000) / 10,\n confidence:\n comparison?.confidence === null || comparison === null\n ? null\n : Math.round(comparison.confidence * 1_000) / 10,\n })\n })\n }\n return {\n ok: true,\n table: {\n title: 'A/B tests',\n source: { label: 'A/B testing', path: 'marketing/experiments' },\n period: null,\n columns: [\n { key: 'test', label: 'Test', kind: 'text' },\n { key: 'variant', label: 'Variant', kind: 'text' },\n { key: 'shown', label: 'Shown', kind: 'count' },\n { key: 'conversions', label: 'Conversions', kind: 'count' },\n { key: 'rate', label: 'Conversion rate', kind: 'percent' },\n { key: 'lift', label: 'Lift over the first variant', kind: 'change' },\n { key: 'confidence', label: 'Confidence in the lift', kind: 'percent' },\n ],\n rows: rows.slice(0, PLUGIN_FIGURE_MAX_ROWS),\n omitted: Math.max(0, rows.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: ['Figures are totals since each test started; the first variant of a test is its control.'],\n },\n }\n },\n },\n ]\n}\n\n/** Registers the campaign and A/B testing readers from the console surface, where insight jobs run. */\nexport function registerMarketingFigureReaders(firestore: () => Firestore): void {\n for (const reader of marketingFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: MARKETING_PLUGIN_ID })\n }\n}\n"],"names":["PLUGIN_FIGURE_MAX_ROWS","pluginFigureWindows","registerPluginFigureReader","campaignReport","EMAIL_CREATED_AT_FIELD","emailSendTimeMs","CAMPAIGN_SEND_HOST_FIELD","orgCampaignSends","compareVariants","summarizeVariantStats","MARKETING_PLUGIN_ID","CAMPAIGN_FIGURES_READ_LIMIT","EXPERIMENT_FIGURES_READ_LIMIT","WINDOWS","percent","rate","Math","round","value","pooled","rates","known","filter","denominator","reduce","sum","numerator","marketingFigureReaders","firestore","id","label","description","scope","windows","read","request","hostId","ok","status","error","includes","days","orgId","current","now","snapshot","where","orderBy","limit","get","sends","docs","map","doc","data","record","sentAt","Boolean","startMs","endMs","subject","String","trim","report","rows","campaign","delivered","every","send","openRate","open","clickRate","click","slice","table","title","source","path","period","from","to","columns","key","kind","omitted","max","length","notes","feature","experimentsRef","collection","experiment","byVariant","variants","stats","ref","Map","entry","control","forEach","variant","index","own","summary","comparison","push","test","name","shown","exposures","conversions","lift","confidence","registerMarketingFigureReaders","reader","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,mBAAmB,EACnBC,0BAA0B,QAGrB,6CAA4C;AACnD,SACEC,cAAc,QAGT,yDAAwD;AAC/D,SACEC,sBAAsB,EACtBC,eAAe,QACV,sDAAqD;AAC5D,SAASC,wBAAwB,QAAQ,4DAA2D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G,OAAO,SAAS0B,+BAA+BrF,SAA0B;IACvE,KAAK,MAAMsF,UAAUvF,uBAAuBC,WAAY;QACtD1B,2BAA2BgH,QAAQ;YAAEC,UAAUzG;QAAoB;IACrE;AACF"}
|
package/src/lib/server.js
CHANGED
|
@@ -23,7 +23,7 @@ import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
|
23
23
|
import { FieldValue } from "firebase-admin/firestore";
|
|
24
24
|
import { campaignProcessScheduledHandler } from "./server/campaign-process-scheduled.js";
|
|
25
25
|
import { listsMaterializeHandler } from "./server/lists-materialize.js";
|
|
26
|
-
import { campaignManageHandler, registerCampaignDraftWriter } from "./server/campaign-manage.js";
|
|
26
|
+
import { campaignManageHandler, campaignManageSubject, registerCampaignDraftWriter } from "./server/campaign-manage.js";
|
|
27
27
|
import { campaignSendHandler } from "./server/campaign-send.js";
|
|
28
28
|
import { campaignRecipientsHandler } from "./server/campaign-recipients.js";
|
|
29
29
|
/**
|
|
@@ -132,8 +132,12 @@ import { campaignRecipientsHandler } from "./server/campaign-recipients.js";
|
|
|
132
132
|
registerPluginApiRoute('campaigns/send', campaignSendHandler);
|
|
133
133
|
// Taking a campaign or an abandoned draft away, which is the one class of
|
|
134
134
|
// change the send route may not carry: both write to the SEND collection,
|
|
135
|
-
// which no client may touch, and neither of them mails anything.
|
|
136
|
-
|
|
135
|
+
// which no client may touch, and neither of them mails anything. The
|
|
136
|
+
// organization hub reaches it naming its org and no site, so the route
|
|
137
|
+
// names that org as its subject for the release gate.
|
|
138
|
+
registerPluginApiRoute('campaigns/manage', campaignManageHandler, {
|
|
139
|
+
subject: campaignManageSubject
|
|
140
|
+
});
|
|
137
141
|
// The other direction through the per-recipient delivery log: not "what did
|
|
138
142
|
// we send this person" but "who did this design reach, and which of them
|
|
139
143
|
// opened it". Server-side because the log is a platform-level collection no
|
package/src/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/marketing/src/lib/server.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 { checkEntitlement } from '@aglyn/aglyn/server'\nimport { evaluateAutoWinner, type HostExperiment } from './model'\nimport {\n registerPluginApiRoute,\n registerSitePageEnricher,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { emailEventsHandler } from './server/email-events'\nimport { registerMarketingFigureReaders } from './server/marketing-figures'\nimport { marketingSitePageEnricher } from './server/site-page-enricher'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { campaignProcessScheduledHandler } from './server/campaign-process-scheduled'\nimport { listsMaterializeHandler } from './server/lists-materialize'\nimport {\n campaignManageHandler,\n registerCampaignDraftWriter,\n} from './server/campaign-manage'\nimport { campaignSendHandler } from './server/campaign-send'\nimport { campaignRecipientsHandler } from './server/campaign-recipients'\n\n/**\n * Experiment beacon (AGL-252): counts an exposure or conversion on\n * `hosts/{hostId}/experiments/{id}/stats/{variantId}`. Sampled counters —\n * fire-and-forget from the page, abTesting-gated, no visitor identity\n * stored server-side (assignment is deterministic client-side).\n */\nconst trackHandler: 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 experimentId = String(req.body?.experimentId ?? '')\n const variantId = String(req.body?.variantId ?? '')\n const kind = String(req.body?.kind ?? '')\n if (\n !hostId ||\n !experimentId ||\n !variantId ||\n !['exposure', 'conversion'].includes(kind)\n ) {\n return res.status(400).json({ error: 'Bad beacon' })\n }\n try {\n const org = (await getOrgForHost(hostId))?.org\n if (!checkEntitlement(org as any, 'abTesting')) {\n return res.status(200).json({ ok: true })\n }\n const experimentRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('experiments')\n .doc(experimentId)\n const experiment = await experimentRef.get()\n if (!experiment.exists || experiment.get('status') !== 'running') {\n return res.status(200).json({ ok: true })\n }\n // Ended experiments (AGL-273) stop counting: stale cached pages may\n // still beacon briefly, and post-end stats would skew the decision.\n const endAtMs = Number(experiment.get('endAtMs') ?? 0)\n if (endAtMs && Date.now() > endAtMs) {\n return res.status(200).json({ ok: true })\n }\n await experimentRef\n .collection('stats')\n .doc(variantId)\n .set(\n {\n [kind === 'exposure' ? 'exposures' : 'conversions']:\n FieldValue.increment(1),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // Auto-winner (AGL-273): conversions re-evaluate the opt-in decision\n // rule; a decided experiment finishes itself and serves the winner.\n const data = experiment.data() as HostExperiment\n if (kind === 'conversion' && data.autoWinner) {\n const statsSnapshot = await experimentRef.collection('stats').get()\n const statsByVariant: Record<\n string,\n { exposures?: number; conversions?: number }\n > = {}\n for (const doc of statsSnapshot.docs) {\n statsByVariant[doc.id] = {\n exposures: Number(doc.get('exposures') ?? 0),\n conversions: Number(doc.get('conversions') ?? 0),\n }\n }\n const decision = evaluateAutoWinner(data, statsByVariant)\n if (decision) {\n await experimentRef.update({\n status: 'done',\n winnerVariantId: decision.variantId,\n autoCompleted: true,\n completedAt: FieldValue.serverTimestamp(),\n })\n }\n }\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(200).json({ ok: true }) // beacons never error the page\n }\n}\n\n/** Registers the marketing plugin's public (site-facing) API routes (AGL-396). */\nexport function registerMarketingApi(): void {\n registerPluginApiRoute('experiments/track', trackHandler)\n // Site-page contributions (AGL-418): overlays, automations, experiments.\n registerSitePageEnricher(marketingSitePageEnricher)\n}\n\n/** Registers the marketing plugin's console-side API routes (AGL-396). */\nexport function registerMarketingConsoleApi(): void {\n // The campaign draft writer another plugin reaches through the core's\n // resource-drafts seam (AGL-2912). Registered here alone: the AI jobs that\n // write through it run only on the console, inline and on the beat\n // (AGL-3026).\n registerCampaignDraftWriter()\n // Campaign and A/B testing results as figure tables (AGL-2915), for the AI\n // plugin's insights to read by id; the console runs insight jobs.\n registerMarketingFigureReaders(() => firebaseAdmin.app().firestore())\n registerPluginApiRoute('campaigns/send', campaignSendHandler)\n // Taking a campaign or an abandoned draft away, which is the one class of\n // change the send route may not carry: both write to the SEND collection,\n // which no client may touch, and neither of them mails anything.\n registerPluginApiRoute('campaigns/manage', campaignManageHandler)\n // The other direction through the per-recipient delivery log: not \"what did\n // we send this person\" but \"who did this design reach, and which of them\n // opened it\". Server-side because the log is a platform-level collection no\n // security rule can scope to one site's campaigns.\n registerPluginApiRoute('campaigns/recipients', campaignRecipientsHandler)\n // Relocated console route (AGL-418): the Resend/Svix webhook keeps its\n // /api/email/events URL via the dispatcher; ownership is recorded at\n // registration so the org gate attributes it to marketing, not email.\n registerPluginApiRoute('email/events', emailEventsHandler)\n registerPluginApiRoute(\n 'campaigns/process-scheduled',\n campaignProcessScheduledHandler,\n )\n // The dynamic-list sweep rides the same `*/15` fast-cron as the campaign\n // processor rather than provisioning a scheduler job of its own.\n registerPluginApiRoute('lists/materialize', listsMaterializeHandler)\n}\n"],"names":["checkEntitlement","evaluateAutoWinner","registerPluginApiRoute","registerSitePageEnricher","emailEventsHandler","registerMarketingFigureReaders","marketingSitePageEnricher","firebaseAdmin","getOrgForHost","FieldValue","campaignProcessScheduledHandler","listsMaterializeHandler","campaignManageHandler","registerCampaignDraftWriter","campaignSendHandler","campaignRecipientsHandler","trackHandler","req","res","method","status","json","error","hostId","String","body","experimentId","variantId","kind","includes","experiment","org","ok","experimentRef","app","firestore","collection","doc","get","exists","endAtMs","Number","Date","now","set","increment","updatedAt","serverTimestamp","merge","data","autoWinner","statsSnapshot","statsByVariant","docs","id","exposures","conversions","decision","update","winnerVariantId","autoCompleted","completedAt","console","registerMarketingApi","registerMarketingConsoleApi"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,kBAAkB,QAA6B,mBAAS;AACjE,SACEC,sBAAsB,EACtBC,wBAAwB,QAEnB,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,2BAAuB;AAC1D,SAASC,8BAA8B,QAAQ,gCAA4B;AAC3E,SAASC,yBAAyB,QAAQ,iCAA6B;AACvE,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,+BAA+B,QAAQ,yCAAqC;AACrF,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SACEC,qBAAqB,EACrBC,2BAA2B,QACtB,8BAA0B;AACjC,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,yBAAyB,QAAQ,kCAA8B;AAExE;;;;;CAKC,GACD,MAAMC,eAAiC,OAAOC,KAAKC;;QAI3BD,WACMA,YACHA,YACLA;IANpB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,eAAeF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,YAAY,oBAAI;IACtD,MAAMC,YAAYH,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUU,SAAS,oBAAI;IAChD,MAAMC,OAAOJ,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUW,IAAI,oBAAI;IACtC,IACE,CAACL,UACD,CAACG,gBACD,CAACC,aACD,CAAC;QAAC;QAAY;KAAa,CAAC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gBE;IACvCF,uBACE,+BACAQ;IAEF,yEAAyE;IACzE,iEAAiE;IACjER,uBAAuB,qBAAqBS;AAC9C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/marketing/src/lib/server.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 { checkEntitlement } from '@aglyn/aglyn/server'\nimport { evaluateAutoWinner, type HostExperiment } from './model'\nimport {\n registerPluginApiRoute,\n registerSitePageEnricher,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { emailEventsHandler } from './server/email-events'\nimport { registerMarketingFigureReaders } from './server/marketing-figures'\nimport { marketingSitePageEnricher } from './server/site-page-enricher'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { campaignProcessScheduledHandler } from './server/campaign-process-scheduled'\nimport { listsMaterializeHandler } from './server/lists-materialize'\nimport {\n campaignManageHandler,\n campaignManageSubject,\n registerCampaignDraftWriter,\n} from './server/campaign-manage'\nimport { campaignSendHandler } from './server/campaign-send'\nimport { campaignRecipientsHandler } from './server/campaign-recipients'\n\n/**\n * Experiment beacon (AGL-252): counts an exposure or conversion on\n * `hosts/{hostId}/experiments/{id}/stats/{variantId}`. Sampled counters —\n * fire-and-forget from the page, abTesting-gated, no visitor identity\n * stored server-side (assignment is deterministic client-side).\n */\nconst trackHandler: 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 experimentId = String(req.body?.experimentId ?? '')\n const variantId = String(req.body?.variantId ?? '')\n const kind = String(req.body?.kind ?? '')\n if (\n !hostId ||\n !experimentId ||\n !variantId ||\n !['exposure', 'conversion'].includes(kind)\n ) {\n return res.status(400).json({ error: 'Bad beacon' })\n }\n try {\n const org = (await getOrgForHost(hostId))?.org\n if (!checkEntitlement(org as any, 'abTesting')) {\n return res.status(200).json({ ok: true })\n }\n const experimentRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('experiments')\n .doc(experimentId)\n const experiment = await experimentRef.get()\n if (!experiment.exists || experiment.get('status') !== 'running') {\n return res.status(200).json({ ok: true })\n }\n // Ended experiments (AGL-273) stop counting: stale cached pages may\n // still beacon briefly, and post-end stats would skew the decision.\n const endAtMs = Number(experiment.get('endAtMs') ?? 0)\n if (endAtMs && Date.now() > endAtMs) {\n return res.status(200).json({ ok: true })\n }\n await experimentRef\n .collection('stats')\n .doc(variantId)\n .set(\n {\n [kind === 'exposure' ? 'exposures' : 'conversions']:\n FieldValue.increment(1),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // Auto-winner (AGL-273): conversions re-evaluate the opt-in decision\n // rule; a decided experiment finishes itself and serves the winner.\n const data = experiment.data() as HostExperiment\n if (kind === 'conversion' && data.autoWinner) {\n const statsSnapshot = await experimentRef.collection('stats').get()\n const statsByVariant: Record<\n string,\n { exposures?: number; conversions?: number }\n > = {}\n for (const doc of statsSnapshot.docs) {\n statsByVariant[doc.id] = {\n exposures: Number(doc.get('exposures') ?? 0),\n conversions: Number(doc.get('conversions') ?? 0),\n }\n }\n const decision = evaluateAutoWinner(data, statsByVariant)\n if (decision) {\n await experimentRef.update({\n status: 'done',\n winnerVariantId: decision.variantId,\n autoCompleted: true,\n completedAt: FieldValue.serverTimestamp(),\n })\n }\n }\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error(error)\n return res.status(200).json({ ok: true }) // beacons never error the page\n }\n}\n\n/** Registers the marketing plugin's public (site-facing) API routes (AGL-396). */\nexport function registerMarketingApi(): void {\n registerPluginApiRoute('experiments/track', trackHandler)\n // Site-page contributions (AGL-418): overlays, automations, experiments.\n registerSitePageEnricher(marketingSitePageEnricher)\n}\n\n/** Registers the marketing plugin's console-side API routes (AGL-396). */\nexport function registerMarketingConsoleApi(): void {\n // The campaign draft writer another plugin reaches through the core's\n // resource-drafts seam (AGL-2912). Registered here alone: the AI jobs that\n // write through it run only on the console, inline and on the beat\n // (AGL-3026).\n registerCampaignDraftWriter()\n // Campaign and A/B testing results as figure tables (AGL-2915), for the AI\n // plugin's insights to read by id; the console runs insight jobs.\n registerMarketingFigureReaders(() => firebaseAdmin.app().firestore())\n registerPluginApiRoute('campaigns/send', campaignSendHandler)\n // Taking a campaign or an abandoned draft away, which is the one class of\n // change the send route may not carry: both write to the SEND collection,\n // which no client may touch, and neither of them mails anything. The\n // organization hub reaches it naming its org and no site, so the route\n // names that org as its subject for the release gate.\n registerPluginApiRoute('campaigns/manage', campaignManageHandler, {\n subject: campaignManageSubject,\n })\n // The other direction through the per-recipient delivery log: not \"what did\n // we send this person\" but \"who did this design reach, and which of them\n // opened it\". Server-side because the log is a platform-level collection no\n // security rule can scope to one site's campaigns.\n registerPluginApiRoute('campaigns/recipients', campaignRecipientsHandler)\n // Relocated console route (AGL-418): the Resend/Svix webhook keeps its\n // /api/email/events URL via the dispatcher; ownership is recorded at\n // registration so the org gate attributes it to marketing, not email.\n registerPluginApiRoute('email/events', emailEventsHandler)\n registerPluginApiRoute(\n 'campaigns/process-scheduled',\n campaignProcessScheduledHandler,\n )\n // The dynamic-list sweep rides the same `*/15` fast-cron as the campaign\n // processor rather than provisioning a scheduler job of its own.\n registerPluginApiRoute('lists/materialize', listsMaterializeHandler)\n}\n"],"names":["checkEntitlement","evaluateAutoWinner","registerPluginApiRoute","registerSitePageEnricher","emailEventsHandler","registerMarketingFigureReaders","marketingSitePageEnricher","firebaseAdmin","getOrgForHost","FieldValue","campaignProcessScheduledHandler","listsMaterializeHandler","campaignManageHandler","campaignManageSubject","registerCampaignDraftWriter","campaignSendHandler","campaignRecipientsHandler","trackHandler","req","res","method","status","json","error","hostId","String","body","experimentId","variantId","kind","includes","experiment","org","ok","experimentRef","app","firestore","collection","doc","get","exists","endAtMs","Number","Date","now","set","increment","updatedAt","serverTimestamp","merge","data","autoWinner","statsSnapshot","statsByVariant","docs","id","exposures","conversions","decision","update","winnerVariantId","autoCompleted","completedAt","console","registerMarketingApi","registerMarketingConsoleApi","subject"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,kBAAkB,QAA6B,mBAAS;AACjE,SACEC,sBAAsB,EACtBC,wBAAwB,QAEnB,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,2BAAuB;AAC1D,SAASC,8BAA8B,QAAQ,gCAA4B;AAC3E,SAASC,yBAAyB,QAAQ,iCAA6B;AACvE,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,+BAA+B,QAAQ,yCAAqC;AACrF,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SACEC,qBAAqB,EACrBC,qBAAqB,EACrBC,2BAA2B,QACtB,8BAA0B;AACjC,SAASC,mBAAmB,QAAQ,4BAAwB;AAC5D,SAASC,yBAAyB,QAAQ,kCAA8B;AAExE;;;;;CAKC,GACD,MAAMC,eAAiC,OAAOC,KAAKC;;QAI3BD,WACMA,YACHA,YACLA;IANpB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,eAAeF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,Y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