@aglyn/tenant-data-admin 1.0.0-beta.173 → 1.0.0-beta.175

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.
@@ -49,6 +49,7 @@
49
49
  * is the operator's.
50
50
  */
51
51
  import { type PlatformMarketingConsentDecision, type PlatformMarketingConsentSourceKind, type PlatformMarketingConsentState } from '@aglyn/aglyn/app-utils/platform-marketing-consent';
52
+ import { type MarketingBasis, type MarketingConsentAssertedBy, type MarketingConsentReason, type MarketingConsentVerdict } from '@aglyn/aglyn/app-utils/marketing-consent';
52
53
  import { upsertHostContact } from './upsert-contact';
53
54
  /**
54
55
  * The variable naming the host whose contacts receive product-marketing
@@ -131,3 +132,70 @@ export declare function snoozePlatformMarketingPrompt(uid: string, options?: {
131
132
  export declare function readPlatformMarketingConsentForUser(uid: string, options?: {
132
133
  firestore?: any;
133
134
  }): Promise<PlatformMarketingConsentState>;
135
+ /** An entry on one of the two lists every campaign send passes. */
136
+ export interface PlatformMarketingSuppression {
137
+ /** `site`: the marketing site's own list. `platform`: every sender's. */
138
+ list: 'site' | 'platform';
139
+ /** `unsubscribe` on the site list; `bounce`, `complaint` or `staff` platform-wide. */
140
+ reason: string;
141
+ }
142
+ /**
143
+ * What the operator's own product email would decide about one address
144
+ * (AGL-3292), read the way a campaign from the marketing site reads it.
145
+ *
146
+ * The decision the person made lives on `users/{uid}`, and nothing a send
147
+ * does looks there. A campaign from the configured marketing site reads the
148
+ * CONTACT `recordPlatformMarketingConsent` wrote into that site's
149
+ * organization — its basis for the site, under the organization's policy —
150
+ * and then drops anybody on either suppression list. Nothing syncs the two
151
+ * afterwards: an unsubscribe link writes a suppression and leaves both
152
+ * consent records as they were. So a staff reader asking "may we email
153
+ * them?" needs this half, and needs it from the sender's own readers — the
154
+ * same basis read, consent group, policy and lists — or it answers a
155
+ * question no send asks.
156
+ */
157
+ export type PlatformMarketingReach =
158
+ /** No marketing site is configured — a self-hosted install. */
159
+ {
160
+ status: 'unconfigured';
161
+ }
162
+ /** The account carries no address a contact could be keyed on. */
163
+ | {
164
+ status: 'no-email';
165
+ }
166
+ /** A read failed. Nothing about the person follows from it. */
167
+ | {
168
+ status: 'unreadable';
169
+ hostId: string;
170
+ } | {
171
+ status: 'read';
172
+ hostId: string;
173
+ orgId: string;
174
+ orgSlug: string | null;
175
+ /** `null` when the operator's CRM holds no contact for the address. */
176
+ contactId: string | null;
177
+ basis: MarketingBasis;
178
+ basisAtMs: number | null;
179
+ /** Whose act the basis is — a person's own, or an operator's assertion. */
180
+ assertedBy: MarketingConsentAssertedBy | null;
181
+ /** Which door recorded the basis (`console-signup`, a form, a backfill). */
182
+ basisKind: string | null;
183
+ /** The consent rule's answer alone, before either list is consulted. */
184
+ verdict: MarketingConsentVerdict;
185
+ reason: MarketingConsentReason;
186
+ /** The list that stops every send to the address, when one does. */
187
+ suppression: PlatformMarketingSuppression | null;
188
+ };
189
+ /**
190
+ * Reads {@link PlatformMarketingReach} for an address.
191
+ *
192
+ * Never throws: a failed read is `unreadable`, which the staff page shows as
193
+ * unknown — never as "no consent", which would be a claim about the person.
194
+ */
195
+ export declare function readPlatformMarketingReach(input: {
196
+ email: string | null | undefined;
197
+ /** Injectable for tests; defaults to {@link platformMarketingHostId}. */
198
+ hostId?: string | null;
199
+ /** Injectable for tests; defaults to the admin app's Firestore. */
200
+ firestore?: any;
201
+ }): Promise<PlatformMarketingReach>;
@@ -48,7 +48,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
48
48
  * `platform-marketing-host.ts` gives: nothing in the code knows which site
49
49
  * is the operator's.
50
50
  */ import { isPlatformMarketingConsentDecision, isPlatformMarketingConsentSourceKind, platformMarketingConsentSource, platformMarketingUserFields, readPlatformMarketingConsent, USER_MARKETING_PROMPT_DISMISSED_AT_FIELD } from "@aglyn/aglyn/app-utils/platform-marketing-consent";
51
+ import { marketingConsentDecision, readMarketingBasis, resolveMarketingConsentPolicy } from "@aglyn/aglyn/app-utils/marketing-consent";
52
+ import { findContactByEmail } from "./contact-email-index.js";
53
+ import { EMAIL_SUPPRESSIONS_COLLECTION, emailSuppressionKey, HOST_SUPPRESSIONS_SUBCOLLECTION } from "./email-suppression.js";
51
54
  import firebaseAdmin from "./firebase-admin.js";
55
+ import { consentGroupForSite, getOrgForHost, orgDataCollectionForHost } from "./organizations.js";
52
56
  import { upsertHostContact } from "./upsert-contact.js";
53
57
  const firestore = ()=>firebaseAdmin.app().firestore();
54
58
  /**
@@ -205,5 +209,90 @@ const firestore = ()=>firebaseAdmin.app().firestore();
205
209
  const snapshot = await ((_options_firestore = options.firestore) != null ? _options_firestore : firestore()).collection('users').doc(trimmed).get();
206
210
  return readPlatformMarketingConsent((_ref = snapshot == null ? void 0 : (_snapshot_data = snapshot.data) == null ? void 0 : _snapshot_data.call(snapshot)) != null ? _ref : null);
207
211
  }
212
+ /**
213
+ * The entry that suppresses `email` for sends from `hostId`, if any.
214
+ *
215
+ * The site's own list first, because it is the one a person puts themselves
216
+ * on from this sender's footer; the platform list second. The same two reads
217
+ * `filterSendableForHost` makes: a site entry suppresses by existing, and a
218
+ * platform entry until it is released.
219
+ */ async function readPlatformMarketingSuppression(db, hostId, email) {
220
+ const key = emailSuppressionKey(email);
221
+ if (!key) return null;
222
+ const [site, platform] = await Promise.all([
223
+ db.collection('hosts').doc(hostId).collection(HOST_SUPPRESSIONS_SUBCOLLECTION).doc(key).get(),
224
+ db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key).get()
225
+ ]);
226
+ if (site == null ? void 0 : site.exists) {
227
+ var _site_get;
228
+ return {
229
+ list: 'site',
230
+ reason: String((_site_get = site.get('reason')) != null ? _site_get : 'unsubscribe')
231
+ };
232
+ }
233
+ if ((platform == null ? void 0 : platform.exists) && !platform.get('releasedAt')) {
234
+ var _platform_get;
235
+ return {
236
+ list: 'platform',
237
+ reason: String((_platform_get = platform.get('reason')) != null ? _platform_get : 'staff')
238
+ };
239
+ }
240
+ return null;
241
+ }
242
+ /**
243
+ * Reads {@link PlatformMarketingReach} for an address.
244
+ *
245
+ * Never throws: a failed read is `unreadable`, which the staff page shows as
246
+ * unknown — never as "no consent", which would be a claim about the person.
247
+ */ export async function readPlatformMarketingReach(input) {
248
+ var _input_email, _input_firestore;
249
+ const hostId = input.hostId === undefined ? platformMarketingHostId() : input.hostId;
250
+ if (!hostId) return {
251
+ status: 'unconfigured'
252
+ };
253
+ const email = String((_input_email = input.email) != null ? _input_email : '').trim().toLowerCase();
254
+ if (!email) return {
255
+ status: 'no-email'
256
+ };
257
+ const db = (_input_firestore = input.firestore) != null ? _input_firestore : firestore();
258
+ try {
259
+ var _ref, _ref1, _ref2;
260
+ var _contact_data, _record_source;
261
+ const owner = await getOrgForHost(hostId);
262
+ if (!owner) return {
263
+ status: 'unreadable',
264
+ hostId
265
+ };
266
+ const org = owner.org;
267
+ const [contact, group, suppression] = await Promise.all([
268
+ // Through the org-data seam, as the capture door finds the same row.
269
+ orgDataCollectionForHost(hostId, 'contacts').then((contacts)=>findContactByEmail(contacts, email)),
270
+ consentGroupForSite(hostId, org),
271
+ readPlatformMarketingSuppression(db, hostId, email)
272
+ ]);
273
+ const record = readMarketingBasis((_ref = contact == null ? void 0 : (_contact_data = contact.data) == null ? void 0 : _contact_data.call(contact)) != null ? _ref : null, group);
274
+ const decision = marketingConsentDecision(record, resolveMarketingConsentPolicy(org['marketingConsentPolicy']));
275
+ return {
276
+ status: 'read',
277
+ hostId,
278
+ orgId: owner.orgId,
279
+ orgSlug: typeof org['slug'] === 'string' ? org['slug'] : null,
280
+ contactId: (_ref1 = contact == null ? void 0 : contact.id) != null ? _ref1 : null,
281
+ basis: record.basis,
282
+ basisAtMs: record.basisAtMs,
283
+ assertedBy: record.assertedBy,
284
+ basisKind: (_ref2 = (_record_source = record.source) == null ? void 0 : _record_source.kind) != null ? _ref2 : null,
285
+ verdict: decision.verdict,
286
+ reason: decision.reason,
287
+ suppression
288
+ };
289
+ } catch (error) {
290
+ console.error('[platform-marketing-consent] reach read failed', error);
291
+ return {
292
+ status: 'unreadable',
293
+ hostId
294
+ };
295
+ }
296
+ }
208
297
 
209
298
  //# sourceMappingURL=platform-marketing-consent.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/platform-marketing-consent.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 * The record a console door writes when a person decides about the\n * platform's own product email (AGL-3185).\n *\n * ## Two documents, one decision\n *\n * The decision goes onto the person's own `users/{uid}` first — the console\n * shows the preference from there, and it must not depend on the operator's\n * CRM accepting a row — and then onto the operator's marketing contact for\n * the same address through `upsertHostContact`, which is every other capture\n * door's path and the only one the send-time consent join reads. The contact\n * half carries the decision AND its provenance, so a campaign's audience\n * count reports this basis as the person's own click and never as something\n * asserted on their behalf.\n *\n * ## Server-side, because the client cannot and should not\n *\n * The sign-up page is a client of the person's own project; the operator's\n * marketing org is somebody else's data. Only the Admin SDK writes there, and\n * only after the person's ID token has been verified by the route in front\n * of this module. The user-document half could be a client write — the rules\n * make it owner-writable — but a mirror the client writes and the server\n * reads back is two writers of one fact, so both halves are written here.\n *\n * ## Which host, and why it is a setting\n *\n * The marketing host is the deployment's, not the code's: this repository is\n * what a self-hosted install runs, and an install with no product audience of\n * its own has nowhere for a contact to go. `PLATFORM_MARKETING_HOST_ID` names\n * it, and when it is unset the decision is recorded on the person's document\n * alone. No hostname or document id is hardcoded here for the same reason\n * `platform-marketing-host.ts` gives: nothing in the code knows which site\n * is the operator's.\n */\n\nimport {\n isPlatformMarketingConsentDecision,\n isPlatformMarketingConsentSourceKind,\n type PlatformMarketingConsentDecision,\n type PlatformMarketingConsentSourceKind,\n type PlatformMarketingConsentState,\n platformMarketingConsentSource,\n platformMarketingUserFields,\n readPlatformMarketingConsent,\n USER_MARKETING_PROMPT_DISMISSED_AT_FIELD,\n} from '@aglyn/aglyn/app-utils/platform-marketing-consent'\nimport firebaseAdmin from './firebase-admin'\nimport { upsertHostContact } from './upsert-contact'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * The variable naming the host whose contacts receive product-marketing\n * consent — the operator's own marketing site. Unset on a self-hosted\n * install, and honored as \"record the preference, capture no contact\".\n */\nexport const PLATFORM_MARKETING_HOST_ID_ENV = 'PLATFORM_MARKETING_HOST_ID'\n\n/**\n * The configured marketing host, or `null` when the deployment names none.\n *\n * Read at call time rather than at module load, so a test can set it and a\n * process that started without it picks up a later value the same way every\n * other runtime setting here does.\n */\nexport function platformMarketingHostId(): string | null {\n const value = String(process.env.PLATFORM_MARKETING_HOST_ID ?? '').trim()\n return value || null\n}\n\n/** What became of the contact half of the record. */\nexport type PlatformMarketingContactOutcome =\n | { status: 'recorded'; contactId: string; created: boolean }\n /** No marketing host is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** The capture door refused the row — its band, an erasure, or an error. */\n | { status: 'refused'; reason: string }\n\nexport interface RecordPlatformMarketingConsentInput {\n uid: string\n /** The account's address, from the verified token. */\n email: string | null | undefined\n /** The name the token carries, for an account whose document holds none. */\n name?: string | null\n decision: PlatformMarketingConsentDecision\n source: PlatformMarketingConsentSourceKind\n /** The wording version the door showed, stamped by the route. */\n textVersion: string\n /** Injectable for tests; defaults to the clock. */\n now?: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the real capture door. */\n upsert?: typeof upsertHostContact\n}\n\nexport interface RecordPlatformMarketingConsentResult {\n /** The timestamp both documents carry. */\n atMs: number\n contact: PlatformMarketingContactOutcome\n}\n\n/**\n * The name the person's own document holds, else the one the caller has.\n *\n * The sign-up form writes `firstName`/`lastName` onto the document; a Google\n * account carries its name on the token instead. Either is the name the\n * contact row should show, and a blank is left blank rather than invented.\n */\nfunction accountName(\n snapshot: { get?: (field: string) => unknown } | null | undefined,\n fallback: string | null | undefined,\n): string | undefined {\n const first = String(snapshot?.get?.('firstName') ?? '').trim()\n const last = String(snapshot?.get?.('lastName') ?? '').trim()\n const stored = [first, last].filter(Boolean).join(' ')\n return stored || String(fallback ?? '').trim() || undefined\n}\n\n/**\n * Records a decision on both documents.\n *\n * Loud on bad input, like `recordLegalAcceptance`: a decision that cannot be\n * attributed to an account, a door and a wording is not a record of anything.\n * Quiet on the contact half — a refused row is returned, not thrown — because\n * the person's own preference has already been recorded by then, and the\n * operator's CRM band is not a reason to tell them their choice failed.\n */\nexport async function recordPlatformMarketingConsent(\n input: RecordPlatformMarketingConsentInput,\n): Promise<RecordPlatformMarketingConsentResult> {\n const uid = String(input.uid ?? '').trim()\n if (!uid) throw new Error('recordPlatformMarketingConsent: uid is required')\n if (!isPlatformMarketingConsentDecision(input.decision)) {\n throw new Error('recordPlatformMarketingConsent: decision is required')\n }\n if (!isPlatformMarketingConsentSourceKind(input.source)) {\n throw new Error('recordPlatformMarketingConsent: source is required')\n }\n const textVersion = String(input.textVersion ?? '').trim()\n if (!textVersion) {\n throw new Error('recordPlatformMarketingConsent: textVersion is required')\n }\n\n const atMs = input.now ?? Date.now()\n const source = platformMarketingConsentSource({\n kind: input.source,\n decision: input.decision,\n uid,\n atMs,\n textVersion,\n })\n\n const userRef = (input.firestore ?? firestore()).collection('users').doc(uid)\n const snapshot = await userRef.get()\n await userRef.set(\n platformMarketingUserFields({ decision: input.decision, atMs, source }),\n { merge: true },\n )\n\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { atMs, contact: { status: 'unconfigured' } }\n const email = String(input.email ?? '').trim()\n if (!email) return { atMs, contact: { status: 'no-email' } }\n\n const name = accountName(snapshot, input.name)\n const verdict = await (input.upsert ?? upsertHostContact)({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'account',\n // The sentence the provenance carries is also the timeline row's: what\n // the person did, in the words an auditor reads.\n interaction: { atMs, summary: source.reason },\n ...(input.decision === 'granted'\n ? { marketingConsent: true }\n : { declineMarketingConsent: true }),\n marketingConsentSource: source,\n // An account on the platform is at least a lead for the platform's own\n // CRM, whichever way the marketing decision went; the floor never moves\n // a customer back.\n initialLifecycleStage: 'lead',\n })\n if ('refused' in verdict) {\n return { atMs, contact: { status: 'refused', reason: verdict.refused } }\n }\n return {\n atMs,\n contact: {\n status: 'recorded',\n contactId: verdict.contactId,\n created: verdict.created,\n },\n }\n}\n\n/**\n * Stamps a prompt dismissal — no decision — so the console stays quiet for\n * the snooze window and asks once more after it.\n */\nexport async function snoozePlatformMarketingPrompt(\n uid: string,\n options: { now?: number; firestore?: any } = {},\n): Promise<{ atMs: number }> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('snoozePlatformMarketingPrompt: uid is required')\n const atMs = options.now ?? Date.now()\n await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .set({ [USER_MARKETING_PROMPT_DISMISSED_AT_FIELD]: atMs }, { merge: true })\n return { atMs }\n}\n\n/** The decision the person's own document holds, for the console to show. */\nexport async function readPlatformMarketingConsentForUser(\n uid: string,\n options: { firestore?: any } = {},\n): Promise<PlatformMarketingConsentState> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('readPlatformMarketingConsentForUser: uid is required')\n const snapshot = await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .get()\n return readPlatformMarketingConsent(\n (snapshot?.data?.() as Record<string, unknown> | undefined) ?? null,\n )\n}\n"],"names":["isPlatformMarketingConsentDecision","isPlatformMarketingConsentSourceKind","platformMarketingConsentSource","platformMarketingUserFields","readPlatformMarketingConsent","USER_MARKETING_PROMPT_DISMISSED_AT_FIELD","firebaseAdmin","upsertHostContact","firestore","app","PLATFORM_MARKETING_HOST_ID_ENV","platformMarketingHostId","process","value","String","env","PLATFORM_MARKETING_HOST_ID","trim","accountName","snapshot","fallback","first","get","last","stored","filter","Boolean","join","undefined","recordPlatformMarketingConsent","input","uid","Error","decision","source","textVersion","atMs","now","Date","kind","userRef","collection","doc","set","merge","hostId","contact","status","email","name","verdict","upsert","interaction","summary","reason","marketingConsent","declineMarketingConsent","marketingConsentSource","initialLifecycleStage","refused","contactId","created","snoozePlatformMarketingPrompt","options","trimmed","readPlatformMarketingConsentForUser","data"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GAED,SACEA,kCAAkC,EAClCC,oCAAoC,EAIpCC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,wCAAwC,QACnC,oDAAmD;AAC1D,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,iBAAiB,QAAQ,sBAAkB;AAEpD,MAAMC,YAAY,IAAMF,cAAcG,GAAG,GAAGD,SAAS;AAErD;;;;CAIC,GACD,OAAO,MAAME,iCAAiC,6BAA4B;AAE1E;;;;;;CAMC,GACD,OAAO,SAASC;QACOC;IAArB,MAAMC,QAAQC,QAAOF,0CAAAA,QAAQG,GAAG,CAACC,0BAA0B,YAAtCJ,0CAA0C,IAAIK,IAAI;IACvE,OAAOJ,SAAS;AAClB;AAsCA;;;;;;CAMC,GACD,SAASK,YACPC,QAAiE,EACjEC,QAAmC;;QAEdD,eACDA;IADpB,MAAME,QAAQP,eAAOK,6BAAAA,gBAAAA,SAAUG,GAAG,qBAAbH,mBAAAA,UAAgB,+BAAgB,IAAIF,IAAI;IAC7D,MAAMM,OAAOT,gBAAOK,6BAAAA,iBAAAA,SAAUG,GAAG,qBAAbH,oBAAAA,UAAgB,+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ACzBiC,UAAU,CAAC,SACXC,GAAG,CAACsB,SACJrB,GAAG,CAAC;QAAE,CAACtC,yCAAyC,EAAE+B;IAAK,GAAG;QAAEQ,OAAO;IAAK;IAC3E,OAAO;QAAER;IAAK;AAChB;AAEA,2EAA2E,GAC3E,OAAO,eAAe6B,oCACpBlC,GAAW,EACXgC,UAA+B,CAAC,CAAC;QAITA;QAKrB5C;IAPH,MAAM6C,UAAUlD,OAAOiB,cAAAA,MAAO,IAAId,IAAI;IACtC,IAAI,CAAC+C,SAAS,MAAM,IAAIhC,MAAM;IAC9B,MAAMb,WAAW,MAAM,EAAC4C,qBAAAA,QAAQvD,SAAS,YAAjBuD,qBAAqBvD,aAC1CiC,UAAU,CAAC,SACXC,GAAG,CAACsB,SACJ1C,GAAG;IACN,OAAOlB,qCACJe,6BAAAA,iBAAAA,SAAU+C,IAAI,qBAAd/C,oBAAAA,4BAA8D;AAEnE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/platform-marketing-consent.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 * The record a console door writes when a person decides about the\n * platform's own product email (AGL-3185).\n *\n * ## Two documents, one decision\n *\n * The decision goes onto the person's own `users/{uid}` first — the console\n * shows the preference from there, and it must not depend on the operator's\n * CRM accepting a row — and then onto the operator's marketing contact for\n * the same address through `upsertHostContact`, which is every other capture\n * door's path and the only one the send-time consent join reads. The contact\n * half carries the decision AND its provenance, so a campaign's audience\n * count reports this basis as the person's own click and never as something\n * asserted on their behalf.\n *\n * ## Server-side, because the client cannot and should not\n *\n * The sign-up page is a client of the person's own project; the operator's\n * marketing org is somebody else's data. Only the Admin SDK writes there, and\n * only after the person's ID token has been verified by the route in front\n * of this module. The user-document half could be a client write — the rules\n * make it owner-writable — but a mirror the client writes and the server\n * reads back is two writers of one fact, so both halves are written here.\n *\n * ## Which host, and why it is a setting\n *\n * The marketing host is the deployment's, not the code's: this repository is\n * what a self-hosted install runs, and an install with no product audience of\n * its own has nowhere for a contact to go. `PLATFORM_MARKETING_HOST_ID` names\n * it, and when it is unset the decision is recorded on the person's document\n * alone. No hostname or document id is hardcoded here for the same reason\n * `platform-marketing-host.ts` gives: nothing in the code knows which site\n * is the operator's.\n */\n\nimport {\n isPlatformMarketingConsentDecision,\n isPlatformMarketingConsentSourceKind,\n type PlatformMarketingConsentDecision,\n type PlatformMarketingConsentSourceKind,\n type PlatformMarketingConsentState,\n platformMarketingConsentSource,\n platformMarketingUserFields,\n readPlatformMarketingConsent,\n USER_MARKETING_PROMPT_DISMISSED_AT_FIELD,\n} from '@aglyn/aglyn/app-utils/platform-marketing-consent'\nimport {\n marketingConsentDecision,\n type MarketingBasis,\n type MarketingConsentAssertedBy,\n type MarketingConsentReason,\n type MarketingConsentVerdict,\n readMarketingBasis,\n resolveMarketingConsentPolicy,\n} from '@aglyn/aglyn/app-utils/marketing-consent'\nimport { findContactByEmail } from './contact-email-index'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n emailSuppressionKey,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from './email-suppression'\nimport firebaseAdmin from './firebase-admin'\nimport {\n consentGroupForSite,\n getOrgForHost,\n orgDataCollectionForHost,\n} from './organizations'\nimport { upsertHostContact } from './upsert-contact'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * The variable naming the host whose contacts receive product-marketing\n * consent — the operator's own marketing site. Unset on a self-hosted\n * install, and honored as \"record the preference, capture no contact\".\n */\nexport const PLATFORM_MARKETING_HOST_ID_ENV = 'PLATFORM_MARKETING_HOST_ID'\n\n/**\n * The configured marketing host, or `null` when the deployment names none.\n *\n * Read at call time rather than at module load, so a test can set it and a\n * process that started without it picks up a later value the same way every\n * other runtime setting here does.\n */\nexport function platformMarketingHostId(): string | null {\n const value = String(process.env.PLATFORM_MARKETING_HOST_ID ?? '').trim()\n return value || null\n}\n\n/** What became of the contact half of the record. */\nexport type PlatformMarketingContactOutcome =\n | { status: 'recorded'; contactId: string; created: boolean }\n /** No marketing host is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** The capture door refused the row — its band, an erasure, or an error. */\n | { status: 'refused'; reason: string }\n\nexport interface RecordPlatformMarketingConsentInput {\n uid: string\n /** The account's address, from the verified token. */\n email: string | null | undefined\n /** The name the token carries, for an account whose document holds none. */\n name?: string | null\n decision: PlatformMarketingConsentDecision\n source: PlatformMarketingConsentSourceKind\n /** The wording version the door showed, stamped by the route. */\n textVersion: string\n /** Injectable for tests; defaults to the clock. */\n now?: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the real capture door. */\n upsert?: typeof upsertHostContact\n}\n\nexport interface RecordPlatformMarketingConsentResult {\n /** The timestamp both documents carry. */\n atMs: number\n contact: PlatformMarketingContactOutcome\n}\n\n/**\n * The name the person's own document holds, else the one the caller has.\n *\n * The sign-up form writes `firstName`/`lastName` onto the document; a Google\n * account carries its name on the token instead. Either is the name the\n * contact row should show, and a blank is left blank rather than invented.\n */\nfunction accountName(\n snapshot: { get?: (field: string) => unknown } | null | undefined,\n fallback: string | null | undefined,\n): string | undefined {\n const first = String(snapshot?.get?.('firstName') ?? '').trim()\n const last = String(snapshot?.get?.('lastName') ?? '').trim()\n const stored = [first, last].filter(Boolean).join(' ')\n return stored || String(fallback ?? '').trim() || undefined\n}\n\n/**\n * Records a decision on both documents.\n *\n * Loud on bad input, like `recordLegalAcceptance`: a decision that cannot be\n * attributed to an account, a door and a wording is not a record of anything.\n * Quiet on the contact half — a refused row is returned, not thrown — because\n * the person's own preference has already been recorded by then, and the\n * operator's CRM band is not a reason to tell them their choice failed.\n */\nexport async function recordPlatformMarketingConsent(\n input: RecordPlatformMarketingConsentInput,\n): Promise<RecordPlatformMarketingConsentResult> {\n const uid = String(input.uid ?? '').trim()\n if (!uid) throw new Error('recordPlatformMarketingConsent: uid is required')\n if (!isPlatformMarketingConsentDecision(input.decision)) {\n throw new Error('recordPlatformMarketingConsent: decision is required')\n }\n if (!isPlatformMarketingConsentSourceKind(input.source)) {\n throw new Error('recordPlatformMarketingConsent: source is required')\n }\n const textVersion = String(input.textVersion ?? '').trim()\n if (!textVersion) {\n throw new Error('recordPlatformMarketingConsent: textVersion is required')\n }\n\n const atMs = input.now ?? Date.now()\n const source = platformMarketingConsentSource({\n kind: input.source,\n decision: input.decision,\n uid,\n atMs,\n textVersion,\n })\n\n const userRef = (input.firestore ?? firestore()).collection('users').doc(uid)\n const snapshot = await userRef.get()\n await userRef.set(\n platformMarketingUserFields({ decision: input.decision, atMs, source }),\n { merge: true },\n )\n\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { atMs, contact: { status: 'unconfigured' } }\n const email = String(input.email ?? '').trim()\n if (!email) return { atMs, contact: { status: 'no-email' } }\n\n const name = accountName(snapshot, input.name)\n const verdict = await (input.upsert ?? upsertHostContact)({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'account',\n // The sentence the provenance carries is also the timeline row's: what\n // the person did, in the words an auditor reads.\n interaction: { atMs, summary: source.reason },\n ...(input.decision === 'granted'\n ? { marketingConsent: true }\n : { declineMarketingConsent: true }),\n marketingConsentSource: source,\n // An account on the platform is at least a lead for the platform's own\n // CRM, whichever way the marketing decision went; the floor never moves\n // a customer back.\n initialLifecycleStage: 'lead',\n })\n if ('refused' in verdict) {\n return { atMs, contact: { status: 'refused', reason: verdict.refused } }\n }\n return {\n atMs,\n contact: {\n status: 'recorded',\n contactId: verdict.contactId,\n created: verdict.created,\n },\n }\n}\n\n/**\n * Stamps a prompt dismissal — no decision — so the console stays quiet for\n * the snooze window and asks once more after it.\n */\nexport async function snoozePlatformMarketingPrompt(\n uid: string,\n options: { now?: number; firestore?: any } = {},\n): Promise<{ atMs: number }> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('snoozePlatformMarketingPrompt: uid is required')\n const atMs = options.now ?? Date.now()\n await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .set({ [USER_MARKETING_PROMPT_DISMISSED_AT_FIELD]: atMs }, { merge: true })\n return { atMs }\n}\n\n/** The decision the person's own document holds, for the console to show. */\nexport async function readPlatformMarketingConsentForUser(\n uid: string,\n options: { firestore?: any } = {},\n): Promise<PlatformMarketingConsentState> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('readPlatformMarketingConsentForUser: uid is required')\n const snapshot = await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .get()\n return readPlatformMarketingConsent(\n (snapshot?.data?.() as Record<string, unknown> | undefined) ?? null,\n )\n}\n\n/** An entry on one of the two lists every campaign send passes. */\nexport interface PlatformMarketingSuppression {\n /** `site`: the marketing site's own list. `platform`: every sender's. */\n list: 'site' | 'platform'\n /** `unsubscribe` on the site list; `bounce`, `complaint` or `staff` platform-wide. */\n reason: string\n}\n\n/**\n * What the operator's own product email would decide about one address\n * (AGL-3292), read the way a campaign from the marketing site reads it.\n *\n * The decision the person made lives on `users/{uid}`, and nothing a send\n * does looks there. A campaign from the configured marketing site reads the\n * CONTACT `recordPlatformMarketingConsent` wrote into that site's\n * organization — its basis for the site, under the organization's policy —\n * and then drops anybody on either suppression list. Nothing syncs the two\n * afterwards: an unsubscribe link writes a suppression and leaves both\n * consent records as they were. So a staff reader asking \"may we email\n * them?\" needs this half, and needs it from the sender's own readers — the\n * same basis read, consent group, policy and lists — or it answers a\n * question no send asks.\n */\nexport type PlatformMarketingReach =\n /** No marketing site is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** A read failed. Nothing about the person follows from it. */\n | { status: 'unreadable'; hostId: string }\n | {\n status: 'read'\n hostId: string\n orgId: string\n orgSlug: string | null\n /** `null` when the operator's CRM holds no contact for the address. */\n contactId: string | null\n basis: MarketingBasis\n basisAtMs: number | null\n /** Whose act the basis is — a person's own, or an operator's assertion. */\n assertedBy: MarketingConsentAssertedBy | null\n /** Which door recorded the basis (`console-signup`, a form, a backfill). */\n basisKind: string | null\n /** The consent rule's answer alone, before either list is consulted. */\n verdict: MarketingConsentVerdict\n reason: MarketingConsentReason\n /** The list that stops every send to the address, when one does. */\n suppression: PlatformMarketingSuppression | null\n }\n\n/**\n * The entry that suppresses `email` for sends from `hostId`, if any.\n *\n * The site's own list first, because it is the one a person puts themselves\n * on from this sender's footer; the platform list second. The same two reads\n * `filterSendableForHost` makes: a site entry suppresses by existing, and a\n * platform entry until it is released.\n */\nasync function readPlatformMarketingSuppression(\n db: any,\n hostId: string,\n email: string,\n): Promise<PlatformMarketingSuppression | null> {\n const key = emailSuppressionKey(email)\n if (!key) return null\n const [site, platform] = await Promise.all([\n db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n .get(),\n db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key).get(),\n ])\n if (site?.exists) {\n return { list: 'site', reason: String(site.get('reason') ?? 'unsubscribe') }\n }\n if (platform?.exists && !platform.get('releasedAt')) {\n return { list: 'platform', reason: String(platform.get('reason') ?? 'staff') }\n }\n return null\n}\n\n/**\n * Reads {@link PlatformMarketingReach} for an address.\n *\n * Never throws: a failed read is `unreadable`, which the staff page shows as\n * unknown — never as \"no consent\", which would be a claim about the person.\n */\nexport async function readPlatformMarketingReach(input: {\n email: string | null | undefined\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n}): Promise<PlatformMarketingReach> {\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { status: 'unconfigured' }\n const email = String(input.email ?? '').trim().toLowerCase()\n if (!email) return { status: 'no-email' }\n const db = input.firestore ?? firestore()\n try {\n const owner = await getOrgForHost(hostId)\n if (!owner) return { status: 'unreadable', hostId }\n const org = owner.org as Record<string, unknown>\n const [contact, group, suppression] = await Promise.all([\n // Through the org-data seam, as the capture door finds the same row.\n orgDataCollectionForHost(hostId, 'contacts').then((contacts) =>\n findContactByEmail(contacts, email),\n ),\n consentGroupForSite(hostId, org),\n readPlatformMarketingSuppression(db, hostId, email),\n ])\n const record = readMarketingBasis(\n (contact?.data?.() as Record<string, unknown> | undefined) ?? null,\n group,\n )\n const decision = marketingConsentDecision(\n record,\n resolveMarketingConsentPolicy(org['marketingConsentPolicy']),\n )\n return {\n status: 'read',\n hostId,\n orgId: owner.orgId,\n orgSlug: typeof org['slug'] === 'string' ? org['slug'] : null,\n contactId: contact?.id ?? null,\n basis: record.basis,\n basisAtMs: record.basisAtMs,\n assertedBy: record.assertedBy,\n basisKind: record.source?.kind ?? null,\n verdict: decision.verdict,\n reason: decision.reason,\n suppression,\n }\n } catch (error) {\n console.error('[platform-marketing-consent] reach read failed', error)\n return { status: 'unreadable', hostId }\n }\n}\n"],"names":["isPlatformMarketingConsentDecision","isPlatformMarketingConsentSourceKind","platformMarketingConsentSource","platformMarketingUserFields","readPlatformMarketingConsent","USER_MARKETING_PROMPT_DISMISSED_AT_FIELD","marketingConsentDecision","readMarketingBasis","resolveMarketingConsentPolicy","findContactByEmail","EMAIL_SUPPRESSIONS_COLLECTION","emailSuppressionKey","HOST_SUPPRESSIONS_SUBCOLLECTION","firebaseAdmin","consentGroupForSite","getOrgForHost","orgDataCollectionForHost","upsertHostContact","firestore","app","PLATFORM_MARKETING_HOST_ID_ENV","platformMarketingHostId","process","value","String","env","PLATFORM_MARKETING_HOST_ID","trim","accountName","snapshot","fallback","first","get","last","stored","filter","Boolean","join","undefined","recordPlatformMarketingConsent","input","uid","Error","decision","source","textVersion","atMs","now","Date","kind","userRef","collection","doc","set","merge","hostId","contact","status","email","name","verdict","upsert","interaction","summary","reason","marketingConsent","declineMarketingConsent","marketingConsentSource","initialLifecycleStage","refused","contactId","created","snoozePlatformMarketingPrompt","options","trimmed","readPlatformMarketingConsentForUser","data","readPlatformMarketingSuppression","db","key","site","platform","Promise","all","exists","list","readPlatformMarketingReach","toLowerCase","record","owner","org","group","suppression","then","contacts","orgId","orgSlug","id","basis","basisAtMs","assertedBy","basisKind","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GAED,SACEA,kCAAkC,EAClCC,oCAAoC,EAIpCC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,wCAAwC,QACnC,oDAAmD;AAC1D,SACEC,wBAAwB,EAKxBC,kBAAkB,EAClBC,6BAA6B,QACxB,2CAA0C;AACjD,SAASC,kBAAkB,QAAQ,2BAAuB;AAC1D,SACEC,6BAA6B,EAC7BC,mBAAmB,EACnBC,+BAA+B,QAC1B,yBAAqB;AAC5B,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,QACnB,qBAAiB;AACxB,SAASC,iBAAiB,QAAQ,sBAAkB;AAEpD,MAAMC,YAAY,IAAML,cAAcM,GAAG,GAAGD,SAAS;AAErD;;;;CAIC,GACD,OAAO,MAAME,iCAAiC,6BAA4B;AAE1E;;;;;;CAMC,GACD,OAAO,SAASC;QACOC;IAArB,MAAMC,QAAQC,QAAOF,0CAAAA,QAAQG,GAAG,CAACC,0BAA0B,YAAtCJ,0CAA0C,IAAIK,IAAI;IACvE,OAAOJ,SAAS;AAClB;AAsCA;;;;;;CAMC,GACD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