@aglyn/tenant-data-admin 1.0.0-beta.250 → 1.0.0-beta.252
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 +7 -7
- package/src/lib/server/ad-audience-sync-run.d.ts +134 -0
- package/src/lib/server/ad-audience-sync-run.js +364 -0
- package/src/lib/server/ad-audience-sync-run.js.map +1 -0
- package/src/lib/server/ad-audience-sync.d.ts +250 -0
- package/src/lib/server/ad-audience-sync.js +446 -0
- package/src/lib/server/ad-audience-sync.js.map +1 -0
- package/src/lib/server/consent-by-address.d.ts +101 -0
- package/src/lib/server/consent-by-address.js +178 -0
- package/src/lib/server/consent-by-address.js.map +1 -0
- package/src/lib/server/notifications.d.ts +23 -0
- package/src/lib/server/notifications.js +35 -16
- package/src/lib/server/notifications.js.map +1 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /**
|
|
17
|
+
* A person's consent as their CONTACT records it, read by address.
|
|
18
|
+
*
|
|
19
|
+
* Three surfaces ask this, and they must get one answer:
|
|
20
|
+
*
|
|
21
|
+
* - the list gate (`email/list-members-preview` and `-add`), deciding
|
|
22
|
+
* whether an address can be enrolled and on what basis;
|
|
23
|
+
* - `performCampaignSend`, for a list member a rule enrolled — the
|
|
24
|
+
* materializer writes no basis onto those rows, because matching a rule is
|
|
25
|
+
* not an opt-in, so the person's real basis is the one on their contact;
|
|
26
|
+
* - the list's Consent column, which shows what the send will act on.
|
|
27
|
+
*
|
|
28
|
+
* A copy per surface agrees only until the shape moves, which is how the
|
|
29
|
+
* Consent column once reported every member as having no basis while the
|
|
30
|
+
* sender mailed them.
|
|
31
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
32
|
+
import { normalizeContactEmail } from "@aglyn/aglyn/app-utils/contacts";
|
|
33
|
+
import { grantEntriesAsRecorded, readMarketingBasis } from "@aglyn/aglyn/app-utils/marketing-consent";
|
|
34
|
+
import { refusalsOf, withRetainedRefusals } from "@aglyn/aglyn/app-utils/retained-refusals";
|
|
35
|
+
import { readRetainedRefusals } from "./retained-refusals.js";
|
|
36
|
+
/** Addresses per `in` query — Firestore's disjunction limit. */ export const CONTACT_LOOKUP_CHUNK = 30;
|
|
37
|
+
/**
|
|
38
|
+
* The stored consent facts for these addresses, off the org's contacts.
|
|
39
|
+
*
|
|
40
|
+
* Read UNSCOPED, deliberately, exactly as the Inbox route reads it:
|
|
41
|
+
* `scopedToHost` narrows an org collection to what one site may see, and a
|
|
42
|
+
* refusal filtered out by that narrowing is a refusal the caller would then
|
|
43
|
+
* step over — the failure mode is mailing or enrolling somebody who said no.
|
|
44
|
+
* A grant cannot leak across sites through this read either: the record is
|
|
45
|
+
* read for `group`, so another site's opt-in answers `otherGrant`, never
|
|
46
|
+
* `granted`. Callers serving a browser must still prove the requester is an
|
|
47
|
+
* org-wide member, which is the tier the rules grant the whole org's
|
|
48
|
+
* contacts to.
|
|
49
|
+
*
|
|
50
|
+
* ## A refusal wins over an opt-in when the CRM holds both
|
|
51
|
+
*
|
|
52
|
+
* Nothing guarantees one contact per address — the collection is keyed by
|
|
53
|
+
* resource id, not by email — so two records for one person can disagree.
|
|
54
|
+
* Taking whichever the query happened to answer first would make the outcome
|
|
55
|
+
* depend on document order. A recorded refusal is the answer whenever one
|
|
56
|
+
* exists, which is the same precedence `assignmentBasis` applies within a
|
|
57
|
+
* single record.
|
|
58
|
+
*
|
|
59
|
+
* ## A refusal outlives the contact it was written on (AGL-3338)
|
|
60
|
+
*
|
|
61
|
+
* Deleting a contact keeps every refusal it held in the org's retained store,
|
|
62
|
+
* so the address is read with what was retained laid over whatever record is
|
|
63
|
+
* left — `withRetainedRefusals` — and an address with no contact at all still
|
|
64
|
+
* reads `declined` when its person said no. A grant given after the refusal,
|
|
65
|
+
* on a contact the person signed up again through, is the person changing
|
|
66
|
+
* their mind and reads `granted`. The grants carried onto a membership come
|
|
67
|
+
* off the same merged record.
|
|
68
|
+
*
|
|
69
|
+
* A failed read falls to `declined` for the whole batch: a read that throws
|
|
70
|
+
* can neither say the person consented nor that they refused, and the
|
|
71
|
+
* direction that costs a retry is the one that does not reach somebody whose
|
|
72
|
+
* stored refusal we simply failed to see. The retained store is read the
|
|
73
|
+
* same way, and fails the same way.
|
|
74
|
+
*
|
|
75
|
+
* @param contacts the org's contacts collection
|
|
76
|
+
* (`orgDataCollectionForHost(hostId, 'contacts')`), passed
|
|
77
|
+
* as the pending lookup so a failure to resolve it reads as
|
|
78
|
+
* the same `declined` as a failed query.
|
|
79
|
+
* @param addresses normalized addresses (`normalizeContactEmail`).
|
|
80
|
+
*/ export async function readContactConsent(contacts, group, addresses) {
|
|
81
|
+
const found = new Map();
|
|
82
|
+
const grants = new Map();
|
|
83
|
+
if (!addresses.length) {
|
|
84
|
+
// Nothing to read, so the pending lookup is never awaited; a rejection
|
|
85
|
+
// it carries is settled here rather than surfacing as unhandled.
|
|
86
|
+
Promise.resolve(contacts).catch(()=>undefined);
|
|
87
|
+
return {
|
|
88
|
+
stored: found,
|
|
89
|
+
grants
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const collection = await contacts;
|
|
94
|
+
const chunks = [];
|
|
95
|
+
for(let at = 0; at < addresses.length; at += CONTACT_LOOKUP_CHUNK){
|
|
96
|
+
chunks.push(addresses.slice(at, at + CONTACT_LOOKUP_CHUNK));
|
|
97
|
+
}
|
|
98
|
+
const [snapshots, retained] = await Promise.all([
|
|
99
|
+
Promise.all(chunks.map((chunk)=>collection.where('email', 'in', chunk).get())),
|
|
100
|
+
readRetainedRefusals(collection, addresses)
|
|
101
|
+
]);
|
|
102
|
+
const consider = (email, data)=>{
|
|
103
|
+
const merged = withRetainedRefusals(data, refusalsOf(retained.get(email)));
|
|
104
|
+
const record = readMarketingBasis(merged, group);
|
|
105
|
+
const already = found.get(email);
|
|
106
|
+
if ((already == null ? void 0 : already.basis) === 'declined') return;
|
|
107
|
+
if (already && record.basis !== 'declined') return;
|
|
108
|
+
found.set(email, record);
|
|
109
|
+
grants.set(email, grantEntriesAsRecorded(merged, group));
|
|
110
|
+
};
|
|
111
|
+
for (const snapshot of snapshots){
|
|
112
|
+
for (const doc of snapshot.docs){
|
|
113
|
+
const email = normalizeContactEmail(doc.get('email'));
|
|
114
|
+
if (email) consider(email, doc.data());
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// What was retained for an address no contact answers any more.
|
|
118
|
+
for (const email of retained.keys()){
|
|
119
|
+
if (!found.has(email)) consider(email, null);
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
stored: found,
|
|
123
|
+
grants
|
|
124
|
+
};
|
|
125
|
+
} catch (error) {
|
|
126
|
+
console.error('[email] consent lookup failed', error);
|
|
127
|
+
const refused = _extends({}, readMarketingBasis(null, group), {
|
|
128
|
+
basis: 'declined',
|
|
129
|
+
// Attributed to nobody: this is what a failed read falls back to, not a
|
|
130
|
+
// refusal anybody recorded.
|
|
131
|
+
assertedBy: null,
|
|
132
|
+
source: null,
|
|
133
|
+
basisAtMs: null,
|
|
134
|
+
capturedAtMs: null
|
|
135
|
+
});
|
|
136
|
+
return {
|
|
137
|
+
stored: new Map(addresses.map((email)=>[
|
|
138
|
+
email,
|
|
139
|
+
refused
|
|
140
|
+
])),
|
|
141
|
+
// Nobody is reachable on a failed read, so nobody's grants travel.
|
|
142
|
+
grants: new Map()
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Lays each rule-enrolled member's contact basis over the basis its row
|
|
148
|
+
* carries, where the row carries none.
|
|
149
|
+
*
|
|
150
|
+
* A row the dynamic-list materializer wrote (`via: 'rule'`) never holds a
|
|
151
|
+
* basis of its own — see the ⛔ in `dynamic-list-materialize.ts` — so for
|
|
152
|
+
* those rows the person's contact is the record. Only an `unrecorded` row
|
|
153
|
+
* is filled: a basis stored on the membership (an attestation, an opt-in an
|
|
154
|
+
* automation carried, a refusal) is a fact about that membership and stays
|
|
155
|
+
* the answer. Rows enrolled any other way are untouched.
|
|
156
|
+
*
|
|
157
|
+
* @param contacts as for {@link readContactConsent}.
|
|
158
|
+
* @param records the members' own records, keyed by normalized address;
|
|
159
|
+
* updated in place.
|
|
160
|
+
* @param ruleMembers the normalized addresses of the `via: 'rule'` rows.
|
|
161
|
+
*/ export async function withContactConsentForRuleMembers(contacts, group, records, ruleMembers) {
|
|
162
|
+
const unrecorded = [
|
|
163
|
+
...ruleMembers
|
|
164
|
+
].filter((email)=>{
|
|
165
|
+
var _ref;
|
|
166
|
+
var _records_get;
|
|
167
|
+
return ((_ref = (_records_get = records.get(email)) == null ? void 0 : _records_get.basis) != null ? _ref : 'unrecorded') === 'unrecorded';
|
|
168
|
+
});
|
|
169
|
+
if (!unrecorded.length) return records;
|
|
170
|
+
const { stored } = await readContactConsent(contacts, group, unrecorded);
|
|
171
|
+
for (const email of unrecorded){
|
|
172
|
+
const fromContact = stored.get(email);
|
|
173
|
+
if (fromContact) records.set(email, fromContact);
|
|
174
|
+
}
|
|
175
|
+
return records;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
//# sourceMappingURL=consent-by-address.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/consent-by-address.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 * A person's consent as their CONTACT records it, read by address.\n *\n * Three surfaces ask this, and they must get one answer:\n *\n * - the list gate (`email/list-members-preview` and `-add`), deciding\n * whether an address can be enrolled and on what basis;\n * - `performCampaignSend`, for a list member a rule enrolled — the\n * materializer writes no basis onto those rows, because matching a rule is\n * not an opt-in, so the person's real basis is the one on their contact;\n * - the list's Consent column, which shows what the send will act on.\n *\n * A copy per surface agrees only until the shape moves, which is how the\n * Consent column once reported every member as having no basis while the\n * sender mailed them.\n */\n\nimport type { ConsentGroup } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport {\n grantEntriesAsRecorded,\n readMarketingBasis,\n type MarketingConsentRecord,\n} from '@aglyn/aglyn/app-utils/marketing-consent'\nimport {\n refusalsOf,\n withRetainedRefusals,\n} from '@aglyn/aglyn/app-utils/retained-refusals'\nimport { readRetainedRefusals } from './retained-refusals'\n\n/** Addresses per `in` query — Firestore's disjunction limit. */\nexport const CONTACT_LOOKUP_CHUNK = 30\n\n/**\n * The stored consent facts for these addresses, off the org's contacts.\n *\n * Read UNSCOPED, deliberately, exactly as the Inbox route reads it:\n * `scopedToHost` narrows an org collection to what one site may see, and a\n * refusal filtered out by that narrowing is a refusal the caller would then\n * step over — the failure mode is mailing or enrolling somebody who said no.\n * A grant cannot leak across sites through this read either: the record is\n * read for `group`, so another site's opt-in answers `otherGrant`, never\n * `granted`. Callers serving a browser must still prove the requester is an\n * org-wide member, which is the tier the rules grant the whole org's\n * contacts to.\n *\n * ## A refusal wins over an opt-in when the CRM holds both\n *\n * Nothing guarantees one contact per address — the collection is keyed by\n * resource id, not by email — so two records for one person can disagree.\n * Taking whichever the query happened to answer first would make the outcome\n * depend on document order. A recorded refusal is the answer whenever one\n * exists, which is the same precedence `assignmentBasis` applies within a\n * single record.\n *\n * ## A refusal outlives the contact it was written on (AGL-3338)\n *\n * Deleting a contact keeps every refusal it held in the org's retained store,\n * so the address is read with what was retained laid over whatever record is\n * left — `withRetainedRefusals` — and an address with no contact at all still\n * reads `declined` when its person said no. A grant given after the refusal,\n * on a contact the person signed up again through, is the person changing\n * their mind and reads `granted`. The grants carried onto a membership come\n * off the same merged record.\n *\n * A failed read falls to `declined` for the whole batch: a read that throws\n * can neither say the person consented nor that they refused, and the\n * direction that costs a retry is the one that does not reach somebody whose\n * stored refusal we simply failed to see. The retained store is read the\n * same way, and fails the same way.\n *\n * @param contacts the org's contacts collection\n * (`orgDataCollectionForHost(hostId, 'contacts')`), passed\n * as the pending lookup so a failure to resolve it reads as\n * the same `declined` as a failed query.\n * @param addresses normalized addresses (`normalizeContactEmail`).\n */\nexport async function readContactConsent(\n contacts:\n | FirebaseFirestore.CollectionReference\n | Promise<FirebaseFirestore.CollectionReference>,\n group: ConsentGroup,\n addresses: readonly string[],\n): Promise<{\n stored: Map<string, MarketingConsentRecord>\n grants: Map<string, Record<string, Record<string, unknown>>>\n}> {\n const found = new Map<string, MarketingConsentRecord>()\n const grants = new Map<string, Record<string, Record<string, unknown>>>()\n if (!addresses.length) {\n // Nothing to read, so the pending lookup is never awaited; a rejection\n // it carries is settled here rather than surfacing as unhandled.\n Promise.resolve(contacts).catch(() => undefined)\n return { stored: found, grants }\n }\n try {\n const collection = await contacts\n const chunks: string[][] = []\n for (let at = 0; at < addresses.length; at += CONTACT_LOOKUP_CHUNK) {\n chunks.push(addresses.slice(at, at + CONTACT_LOOKUP_CHUNK))\n }\n const [snapshots, retained] = await Promise.all([\n Promise.all(chunks.map((chunk) => collection.where('email', 'in', chunk).get())),\n readRetainedRefusals(collection, addresses),\n ])\n const consider = (email: string, data: Record<string, unknown> | null) => {\n const merged = withRetainedRefusals(data, refusalsOf(retained.get(email)))\n const record = readMarketingBasis(merged, group)\n const already = found.get(email)\n if (already?.basis === 'declined') return\n if (already && record.basis !== 'declined') return\n found.set(email, record)\n grants.set(email, grantEntriesAsRecorded(merged, group))\n }\n for (const snapshot of snapshots) {\n for (const doc of snapshot.docs) {\n const email = normalizeContactEmail(doc.get('email'))\n if (email) consider(email, doc.data() as Record<string, unknown>)\n }\n }\n // What was retained for an address no contact answers any more.\n for (const email of retained.keys()) {\n if (!found.has(email)) consider(email, null)\n }\n return { stored: found, grants }\n } catch (error) {\n console.error('[email] consent lookup failed', error)\n const refused: MarketingConsentRecord = {\n ...readMarketingBasis(null, group),\n basis: 'declined',\n // Attributed to nobody: this is what a failed read falls back to, not a\n // refusal anybody recorded.\n assertedBy: null,\n source: null,\n basisAtMs: null,\n capturedAtMs: null,\n }\n return {\n stored: new Map(addresses.map((email) => [email, refused])),\n // Nobody is reachable on a failed read, so nobody's grants travel.\n grants: new Map(),\n }\n }\n}\n\n/**\n * Lays each rule-enrolled member's contact basis over the basis its row\n * carries, where the row carries none.\n *\n * A row the dynamic-list materializer wrote (`via: 'rule'`) never holds a\n * basis of its own — see the ⛔ in `dynamic-list-materialize.ts` — so for\n * those rows the person's contact is the record. Only an `unrecorded` row\n * is filled: a basis stored on the membership (an attestation, an opt-in an\n * automation carried, a refusal) is a fact about that membership and stays\n * the answer. Rows enrolled any other way are untouched.\n *\n * @param contacts as for {@link readContactConsent}.\n * @param records the members' own records, keyed by normalized address;\n * updated in place.\n * @param ruleMembers the normalized addresses of the `via: 'rule'` rows.\n */\nexport async function withContactConsentForRuleMembers(\n contacts:\n | FirebaseFirestore.CollectionReference\n | Promise<FirebaseFirestore.CollectionReference>,\n group: ConsentGroup,\n records: Map<string, MarketingConsentRecord>,\n ruleMembers: ReadonlySet<string>,\n): Promise<Map<string, MarketingConsentRecord>> {\n const unrecorded = [...ruleMembers].filter(\n (email) => (records.get(email)?.basis ?? 'unrecorded') === 'unrecorded',\n )\n if (!unrecorded.length) return records\n const { stored } = await readContactConsent(contacts, group, unrecorded)\n for (const email of unrecorded) {\n const fromContact = stored.get(email)\n if (fromContact) records.set(email, fromContact)\n }\n return records\n}\n"],"names":["normalizeContactEmail","grantEntriesAsRecorded","readMarketingBasis","refusalsOf","withRetainedRefusals","readRetainedRefusals","CONTACT_LOOKUP_CHUNK","readContactConsent","contacts","group","addresses","found","Map","grants","length","Promise","resolve","catch","undefined","stored","collection","chunks","at","push","slice","snapshots","retained","all","map","chunk","where","get","consider","email","data","merged","record","already","basis","set","snapshot","doc","docs","keys","has","error","console","refused","assertedBy","source","basisAtMs","capturedAtMs","withContactConsentForRuleMembers","records","ruleMembers","unrecorded","filter","fromContact"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,qBAAqB,QAAQ,kCAAiC;AACvE,SACEC,sBAAsB,EACtBC,kBAAkB,QAEb,2CAA0C;AACjD,SACEC,UAAU,EACVC,oBAAoB,QACf,2CAA0C;AACjD,SAASC,oBAAoB,QAAQ,yBAAqB;AAE1D,8DAA8D,GAC9D,OAAO,MAAMC,uBAAuB,GAAE;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GACD,OAAO,eAAeC,mBACpBC,QAEkD,EAClDC,KAAmB,EACnBC,SAA4B;IAK5B,MAAMC,QAAQ,IAAIC;IAClB,MAAMC,SAAS,IAAID;IACnB,IAAI,CAACF,UAAUI,MAAM,EAAE;QACrB,uEAAuE;QACvE,iEAAiE;QACjEC,QAAQC,OAAO,CAACR,UAAUS,KAAK,CAAC,IAAMC;QACtC,OAAO;YAAEC,QAAQR;YAAOE;QAAO;IACjC;IACA,IAAI;QACF,MAAMO,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AMO;YAC5B6B,OAAO;YACP,wEAAwE;YACxE,4BAA4B;YAC5BU,YAAY;YACZC,QAAQ;YACRC,WAAW;YACXC,cAAc;;QAEhB,OAAO;YACLhC,QAAQ,IAAIP,IAAIF,UAAUkB,GAAG,CAAC,CAACK,QAAU;oBAACA;oBAAOc;iBAAQ;YACzD,mEAAmE;YACnElC,QAAQ,IAAID;QACd;IACF;AACF;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,eAAewC,iCACpB5C,QAEkD,EAClDC,KAAmB,EACnB4C,OAA4C,EAC5CC,WAAgC;IAEhC,MAAMC,aAAa;WAAID;KAAY,CAACE,MAAM,CACxC,CAACvB;;YAAWoB;eAAD,UAACA,eAAAA,QAAQtB,GAAG,CAACE,2BAAZoB,aAAoBf,KAAK,mBAAI,kBAAkB;;IAE7D,IAAI,CAACiB,WAAWzC,MAAM,EAAE,OAAOuC;IAC/B,MAAM,EAAElC,MAAM,EAAE,GAAG,MAAMZ,mBAAmBC,UAAUC,OAAO8C;IAC7D,KAAK,MAAMtB,SAASsB,WAAY;QAC9B,MAAME,cAActC,OAAOY,GAAG,CAACE;QAC/B,IAAIwB,aAAaJ,QAAQd,GAAG,CAACN,OAAOwB;IACtC;IACA,OAAOJ;AACT"}
|
|
@@ -49,7 +49,28 @@ export interface NotifyUsersOptions {
|
|
|
49
49
|
* the fan-out reaches is mailed as their preferences say.
|
|
50
50
|
*/
|
|
51
51
|
skipEmailFor?: readonly string[];
|
|
52
|
+
/**
|
|
53
|
+
* Particulars the email carries and the notification does not: a form
|
|
54
|
+
* submission's answers, so the person reading the email has the inquiry
|
|
55
|
+
* without opening the console.
|
|
56
|
+
*
|
|
57
|
+
* Email only, never written to the notification document or pushed. The
|
|
58
|
+
* document is copied once per recipient and outlives the record it points
|
|
59
|
+
* at, and a push lands on a lock screen; the record itself stays the one
|
|
60
|
+
* place the visitor's answers are kept.
|
|
61
|
+
*/
|
|
62
|
+
emailDetails?: readonly NotificationEmailDetail[];
|
|
52
63
|
}
|
|
64
|
+
/** One labeled line of a notification email's details. */
|
|
65
|
+
export interface NotificationEmailDetail {
|
|
66
|
+
label: string;
|
|
67
|
+
value: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The details as the email prints them: `Label: value`, one per line, a
|
|
71
|
+
* value's own line breaks kept and blank values left out.
|
|
72
|
+
*/
|
|
73
|
+
export declare function formatNotificationEmailDetails(details: readonly NotificationEmailDetail[] | undefined): string;
|
|
53
74
|
/**
|
|
54
75
|
* Notification fan-out (AGL-259): batch-writes one doc per recipient at
|
|
55
76
|
* `users/{uid}/notifications`, and — for recipients who asked for it
|
|
@@ -126,4 +147,6 @@ export declare function notifyHostManagers(hostId: string, payload: Notification
|
|
|
126
147
|
* the caller sends them their own email about the same event.
|
|
127
148
|
*/
|
|
128
149
|
skipOwnerEmail?: boolean;
|
|
150
|
+
/** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */
|
|
151
|
+
emailDetails?: readonly NotificationEmailDetail[];
|
|
129
152
|
}): Promise<void>;
|
|
@@ -18,6 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import { operatorAlertForNotificationType } from "@aglyn/aglyn/plugin-manager/operator-alerts";
|
|
19
19
|
import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
|
|
20
20
|
import { notificationPushEnabled } from "@aglyn/aglyn/app-utils/notification-push";
|
|
21
|
+
import { platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
|
|
21
22
|
import { FieldValue } from "firebase-admin/firestore";
|
|
22
23
|
import { withoutMailWithheldAccounts } from "./account-mail.js";
|
|
23
24
|
import { findUserByUidAcrossPools, listStaffUidsAcrossPools } from "./auth-pools.js";
|
|
@@ -28,9 +29,19 @@ import { mobilePushEnabled, mobilePushSenders } from "./mobile-push-switch.js";
|
|
|
28
29
|
import { listOrgMembers } from "./organizations.js";
|
|
29
30
|
import { loadSystemEmail, renderLoadedSystemEmail, systemEmailBrand, systemEmailContent } from "./render-system-email.js";
|
|
30
31
|
const firestore = ()=>firebaseAdmin.app().firestore();
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
/**
|
|
33
|
+
* At most this many characters of details per email. A submission is capped
|
|
34
|
+
* at 2,000 characters a field, so a long form would otherwise be a long email.
|
|
35
|
+
*/ const NOTIFY_EMAIL_MAX_DETAILS_CHARS = 10000;
|
|
36
|
+
/**
|
|
37
|
+
* The details as the email prints them: `Label: value`, one per line, a
|
|
38
|
+
* value's own line breaks kept and blank values left out.
|
|
39
|
+
*/ export function formatNotificationEmailDetails(details) {
|
|
40
|
+
const text = (details != null ? details : []).map(({ label, value })=>({
|
|
41
|
+
label: label.trim(),
|
|
42
|
+
value: value.trim()
|
|
43
|
+
})).filter(({ value })=>value).map(({ label, value })=>label ? `${label}: ${value}` : value).join('\n');
|
|
44
|
+
return text.length > NOTIFY_EMAIL_MAX_DETAILS_CHARS ? `${text.slice(0, NOTIFY_EMAIL_MAX_DETAILS_CHARS).trimEnd()}…` : text;
|
|
34
45
|
}
|
|
35
46
|
/**
|
|
36
47
|
* At most this many directory lookups per fan-out, and at most this many
|
|
@@ -65,18 +76,26 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
|
|
|
65
76
|
* template is read once per fan-out and rendered per recipient.
|
|
66
77
|
*
|
|
67
78
|
* Never throws, like everything else on this path.
|
|
68
|
-
*/ async function emailNotification(uids, payload, known, audience) {
|
|
79
|
+
*/ async function emailNotification(uids, payload, known, audience, emailDetails) {
|
|
69
80
|
var _payload_body;
|
|
70
|
-
|
|
81
|
+
/*
|
|
82
|
+
* `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this
|
|
83
|
+
* runs in the site app as well as the console, and the site app's
|
|
84
|
+
* deployment does not set that variable. Read bare, a notification a site
|
|
85
|
+
* sends (a form submission, an order) would carry a button that opens
|
|
86
|
+
* nothing and a settings line with no address.
|
|
87
|
+
*/ const origin = platformConsoleOrigin();
|
|
71
88
|
const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`;
|
|
72
89
|
const context = await notificationEmailContext(payload, audience);
|
|
73
90
|
const url = notificationEmailUrl(payload, context, origin);
|
|
91
|
+
const details = formatNotificationEmailDetails(emailDetails);
|
|
74
92
|
const loaded = await loadSystemEmail('notification').catch(()=>null);
|
|
75
93
|
const fallbackText = [
|
|
76
94
|
payload.title,
|
|
77
95
|
(_payload_body = payload.body) != null ? _payload_body : '',
|
|
96
|
+
details,
|
|
78
97
|
url,
|
|
79
|
-
|
|
98
|
+
`Change what you are emailed about: ${settingsUrl}`
|
|
80
99
|
].filter(Boolean).join('\n\n');
|
|
81
100
|
let lookups = 0;
|
|
82
101
|
let sent = 0;
|
|
@@ -100,8 +119,9 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
|
|
|
100
119
|
const rendered = loaded ? renderLoadedSystemEmail(loaded, _extends({}, context.brand.merge, {
|
|
101
120
|
'notification.title': payload.title,
|
|
102
121
|
'notification.body': (_payload_body1 = payload.body) != null ? _payload_body1 : '',
|
|
122
|
+
'notification.details': details,
|
|
103
123
|
'notification.url': url,
|
|
104
|
-
settingsUrl
|
|
124
|
+
settingsUrl
|
|
105
125
|
}), context.brand.options) : null;
|
|
106
126
|
const result = await sendEmail(_extends({
|
|
107
127
|
to: recipients
|
|
@@ -111,12 +131,11 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
|
|
|
111
131
|
}), context.brand.fromName ? {
|
|
112
132
|
fromName: context.brand.fromName
|
|
113
133
|
} : {}, {
|
|
114
|
-
context: 'notification'
|
|
115
|
-
}, origin ? {
|
|
134
|
+
context: 'notification',
|
|
116
135
|
headers: {
|
|
117
136
|
'List-Unsubscribe': `<${settingsUrl}>`
|
|
118
137
|
}
|
|
119
|
-
}
|
|
138
|
+
}));
|
|
120
139
|
if (!result.sent) continue;
|
|
121
140
|
sent += 1;
|
|
122
141
|
// Whose cost it is: a notification to a workspace's people is that
|
|
@@ -165,8 +184,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
|
|
|
165
184
|
* Where the email's button goes: the notification's own link, rewritten onto
|
|
166
185
|
* today's routes the way the console rewrites it when it is clicked, else
|
|
167
186
|
* the notifications page. A stored host link is `/{hostDocId}/…`, which only
|
|
168
|
-
* that rewrite turns into a page that exists.
|
|
169
|
-
* no console origin to make a link absolute with.
|
|
187
|
+
* that rewrite turns into a page that exists.
|
|
170
188
|
*/ function notificationEmailUrl(payload, context, origin) {
|
|
171
189
|
const link = normalizeNotificationLink(payload.link, {
|
|
172
190
|
orgSlug: context.orgSlug,
|
|
@@ -174,7 +192,6 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
|
|
|
174
192
|
hostSubdomain: context.hostSubdomain
|
|
175
193
|
});
|
|
176
194
|
if (link && /^https?:\/\//i.test(link)) return link;
|
|
177
|
-
if (!origin) return '';
|
|
178
195
|
return `${origin}${(link == null ? void 0 : link.startsWith('/')) ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`;
|
|
179
196
|
}
|
|
180
197
|
/**
|
|
@@ -258,7 +275,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
|
|
|
258
275
|
var _options_emails;
|
|
259
276
|
const reachable = await withoutMailWithheldAccounts(mailTo);
|
|
260
277
|
if (!reachable.length) return;
|
|
261
|
-
await emailNotification(reachable, payload, (_options_emails = options.emails) != null ? _options_emails : {}, options.audience);
|
|
278
|
+
await emailNotification(reachable, payload, (_options_emails = options.emails) != null ? _options_emails : {}, options.audience, options.emailDetails);
|
|
262
279
|
}
|
|
263
280
|
} catch (error) {
|
|
264
281
|
console.error('notification fan-out failed', error);
|
|
@@ -423,11 +440,13 @@ async function listStaffUids() {
|
|
|
423
440
|
hostId
|
|
424
441
|
}, orgId ? {
|
|
425
442
|
orgId
|
|
426
|
-
} : {}), ownerUid ? {
|
|
443
|
+
} : {}), _extends({}, ownerUid ? {
|
|
427
444
|
skipEmailFor: [
|
|
428
445
|
ownerUid
|
|
429
446
|
]
|
|
430
|
-
} : {}
|
|
447
|
+
} : {}, options.emailDetails ? {
|
|
448
|
+
emailDetails: options.emailDetails
|
|
449
|
+
} : {}));
|
|
431
450
|
} catch (error) {
|
|
432
451
|
console.error('host manager notification failed', error);
|
|
433
452
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/notifications.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 buildRoute,\n NOTIFICATION_SELF_SENT_EMAIL_TYPES,\n NOTIFICATION_SETTINGS_FIELD,\n normalizeNotificationLink,\n notificationChannelEnabled,\n type AglynNotification,\n Route,\n type NotificationSettings,\n} from '@aglyn/aglyn/server'\nimport { operatorAlertForNotificationType } from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { notificationPushEnabled } from '@aglyn/aglyn/app-utils/notification-push'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools, listStaffUidsAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { meterOrgEmail, meterPlatformEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { mobilePushEnabled, mobilePushSenders } from './mobile-push-switch'\nimport { listOrgMembers } from './organizations'\nimport {\n loadSystemEmail,\n renderLoadedSystemEmail,\n systemEmailBrand,\n systemEmailContent,\n type SystemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type NotificationPayload = Omit<\n AglynNotification,\n '$id' | 'createdAt' | 'readAt'\n>\n\nexport interface NotifyUsersOptions {\n /**\n * Addresses the caller already holds, by uid (AGL-3224).\n *\n * Purely an optimization, and one worth taking where it is free: a caller\n * that read the roster — `notifyOrgAdmins` does — has every address in hand\n * already, and without this the email half would look each one up again in\n * the directory. Absent uids fall back to that lookup, so passing a partial\n * map is fine and passing none is correct.\n */\n emails?: Readonly<Record<string, string | null | undefined>>\n /**\n * Who the fan-out is for (AGL-3367). `staff` is the platform talking to its\n * own people, so the email wears the platform's brand and is the platform's\n * cost even when the notification is ABOUT an org, which a canceled\n * subscription or a new ticket always is. Anything else speaks in the org's\n * brand when the notification names one.\n */\n audience?: 'staff'\n /**\n * Write the console notification only, and mail nobody through the\n * per-person email channel (AGL-3375): the caller has emailed the same\n * alert to the operator's inbox, and a staff member who also switched\n * email on would otherwise get it twice.\n */\n skipEmail?: boolean\n /**\n * People not to mail through the email channel for this one notification,\n * because the caller emails them the same event itself — the seller's\n * designed sale email beside a Buy Now order's notification. Everyone else\n * the fan-out reaches is mailed as their preferences say.\n */\n skipEmailFor?: readonly string[]\n}\n\n/** The console's absolute origin for an email link, or `''` when unset. */\nfunction consoleOrigin(): string {\n return (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, '')\n}\n\n/**\n * At most this many directory lookups per fan-out, and at most this many\n * notification emails.\n *\n * Both ceilings only ever bite on a fan-out where many recipients have\n * OPTED IN — the email channel defaults off outside a site's transactions\n * (`NOTIFICATION_TYPE_CHANNEL_DEFAULTS`), so the ordinary notification\n * costs exactly what it cost before this existed. They are here because a\n * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation\n * that emitted it: a notification must not be able to turn one write into\n * four hundred directory reads and four hundred sends.\n */\nconst NOTIFY_EMAIL_MAX_LOOKUPS = 25\nconst NOTIFY_EMAIL_MAX_SENDS = 50\n\n/**\n * The email beside the console notification (AGL-3224).\n *\n * One send per recipient, never a shared `to:` list — two people who manage\n * the same site have not agreed to be shown each other's addresses, and the\n * settings link in the footer belongs to one person.\n *\n * `List-Unsubscribe` points at the settings page rather than at a one-click\n * endpoint: this is not marketing mail and RFC 8058's POST form would be\n * claiming a capability that does not exist. What it does do is put the way\n * out in the headers as well as the body, so a client that surfaces it shows\n * the person the page where the switch they want actually is.\n *\n * Rendered through the `notification` system email (AGL-3367), which is what\n * gives it the header and footer every other system email wears, and makes\n * it designable on the staff System emails page. It used to hand `sendEmail`\n * bare text, which is the unbranded card the fallback HTML part draws. The\n * template is read once per fan-out and rendered per recipient.\n *\n * Never throws, like everything else on this path.\n */\nasync function emailNotification(\n uids: string[],\n payload: NotificationPayload,\n known: Readonly<Record<string, string | null | undefined>>,\n audience: NotifyUsersOptions['audience'],\n): Promise<void> {\n const origin = consoleOrigin()\n const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`\n const context = await notificationEmailContext(payload, audience)\n const url = notificationEmailUrl(payload, context, origin)\n const loaded = await loadSystemEmail('notification').catch(() => null)\n const fallbackText = [\n payload.title,\n payload.body ?? '',\n url,\n origin ? `Change what you are emailed about: ${settingsUrl}` : '',\n ]\n .filter(Boolean)\n .join('\\n\\n')\n let lookups = 0\n let sent = 0\n for (const uid of uids) {\n if (sent >= NOTIFY_EMAIL_MAX_SENDS) break\n let address = String(known[uid] ?? '').trim().toLowerCase()\n if (!address.includes('@')) {\n if (lookups >= NOTIFY_EMAIL_MAX_LOOKUPS) continue\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '').trim().toLowerCase()\n }\n if (!address.includes('@')) continue\n const recipients = await filterSuppressedEmails([address])\n if (!recipients.length) continue\n const rendered = loaded\n ? renderLoadedSystemEmail(\n loaded,\n {\n ...context.brand.merge,\n 'notification.title': payload.title,\n 'notification.body': payload.body ?? '',\n 'notification.url': url,\n settingsUrl: origin ? settingsUrl : '',\n },\n context.brand.options,\n )\n : null\n const result = await sendEmail({\n to: recipients,\n ...systemEmailContent(rendered, {\n subject: payload.title,\n text: fallbackText,\n }),\n ...(context.brand.fromName ? { fromName: context.brand.fromName } : {}),\n context: 'notification',\n ...(origin\n ? { headers: { 'List-Unsubscribe': `<${settingsUrl}>` } }\n : {}),\n })\n if (!result.sent) continue\n sent += 1\n // Whose cost it is: a notification to a workspace's people is that\n // workspace's mail, and a staff alert or an account-level notice is the\n // platform's, whichever org it is about.\n await (payload.orgId && audience !== 'staff'\n ? meterOrgEmail(payload.orgId)\n : meterPlatformEmail()\n ).catch(() => undefined)\n }\n}\n\n/** What a notification email needs from the org and site it is about. */\ninterface NotificationEmailContext {\n brand: SystemEmailBrand\n orgSlug?: string\n hostSubdomain?: string\n}\n\n/**\n * The org's brand, and the slug and subdomain its stored link is rewritten\n * with (AGL-3367): at most two reads per fan-out, made only when someone is\n * being emailed.\n *\n * A staff fan-out reads nothing. Its brand is the platform's, and its links\n * are staff routes that need no rewriting.\n */\nasync function notificationEmailContext(\n payload: NotificationPayload,\n audience: NotifyUsersOptions['audience'],\n): Promise<NotificationEmailContext> {\n if (audience === 'staff' || !payload.orgId) {\n return { brand: systemEmailBrand(null) }\n }\n try {\n const db = firestore()\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId\n ? db.collection('hosts').doc(payload.hostId).get()\n : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n return {\n brand: systemEmailBrand(org.exists ? (org.data() ?? null) : null),\n ...(typeof slug === 'string' && slug ? { orgSlug: slug } : {}),\n ...(typeof subdomain === 'string' && subdomain\n ? { hostSubdomain: subdomain }\n : {}),\n }\n } catch (error) {\n console.error('notification email context failed', error)\n return { brand: systemEmailBrand(null) }\n }\n}\n\n/**\n * Where the email's button goes: the notification's own link, rewritten onto\n * today's routes the way the console rewrites it when it is clicked, else\n * the notifications page. A stored host link is `/{hostDocId}/…`, which only\n * that rewrite turns into a page that exists. Empty when the deployment has\n * no console origin to make a link absolute with.\n */\nfunction notificationEmailUrl(\n payload: NotificationPayload,\n context: NotificationEmailContext,\n origin: string,\n): string {\n const link = normalizeNotificationLink(payload.link, {\n orgSlug: context.orgSlug,\n hostId: payload.hostId,\n hostSubdomain: context.hostSubdomain,\n })\n if (link && /^https?:\\/\\//i.test(link)) return link\n if (!origin) return ''\n return `${origin}${link?.startsWith('/') ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`\n}\n\n/**\n * Notification fan-out (AGL-259): batch-writes one doc per recipient at\n * `users/{uid}/notifications`, and — for recipients who asked for it\n * (AGL-3224) — sends one email beside it. Never throws: a notification miss,\n * or a send that failed, must not break the mutation that emitted it.\n */\nexport async function notifyUsers(\n uids: Iterable<string>,\n payload: NotificationPayload,\n options: NotifyUsersOptions = {},\n): Promise<void> {\n try {\n const db = firestore()\n const targets = [...new Set(uids)].filter(Boolean).slice(0, 400)\n if (!targets.length) return\n // Per-user preferences (AGL-267, AGL-3223): one getAll over the user\n // docs, which now answers for both channels and for all three scopes —\n // the settings live on this document precisely so that stays one read.\n const userDocs = await db.getAll(\n ...targets.map((uid) => db.collection('users').doc(uid)),\n )\n const scope = { orgId: payload.orgId, hostId: payload.hostId }\n const batch = db.batch()\n let count = 0\n const mailTo: string[] = []\n const pushTo: string[] = []\n for (const userDoc of userDocs) {\n const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD) as\n | NotificationSettings\n | undefined\n const legacy = userDoc.get('notificationPrefs') as\n | Record<string, boolean>\n | undefined\n if (\n notificationChannelEnabled(\n settings,\n 'console',\n payload.type,\n scope,\n legacy,\n )\n ) {\n batch.set(\n db\n .collection('users')\n .doc(userDoc.id)\n .collection('notifications')\n .doc(),\n // `read: false` on create, so the feed can ask for unread and read\n // alike by equality (AGL-3321; see `AglynNotification.read`).\n { ...payload, read: false, createdAt: FieldValue.serverTimestamp() },\n )\n count += 1\n }\n // The mobile push channel (AGL-3620); unanswered, it follows the feed.\n if (notificationPushEnabled(settings, payload.type, scope, legacy)) {\n pushTo.push(userDoc.id)\n }\n if (\n notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) &&\n !options.skipEmailFor?.includes(userDoc.id)\n ) {\n mailTo.push(userDoc.id)\n }\n }\n if (count > 0) await batch.commit()\n /*\n * The push after the commit for the same reason as the email below:\n * every registered transport is handed the recipients whose preferences\n * say push, unless the deployment has pulled the kill switch. A failing\n * transport is logged and never stops the email or another transport.\n */\n if (pushTo.length && mobilePushEnabled()) {\n for (const send of mobilePushSenders()) {\n try {\n await send(pushTo, payload, { db })\n } catch (error) {\n console.error('push delivery failed', error)\n }\n }\n }\n /*\n * THE EMAIL AFTER THE COMMIT, and not inside its `try`.\n *\n * The console notification is the durable record and the send is a\n * courtesy on top of it, so the order is the one where a failing network\n * call cannot lose the record. The two channels are independent by\n * design — a person may have muted the feed and asked for mail, or the\n * reverse — so neither is gated on the other having happened.\n *\n * Digests are excluded: they compose and send their own mail, under\n * their own switches, and the generic channel would send a second\n * message announcing that the first one had been sent.\n *\n * A locked or disabled account is not mailed (AGL-3418); its feed entry\n * above still records the event.\n */\n if (\n mailTo.length &&\n !options.skipEmail &&\n isEmailConfigured() &&\n !NOTIFICATION_SELF_SENT_EMAIL_TYPES.has(payload.type)\n ) {\n const reachable = await withoutMailWithheldAccounts(mailTo)\n if (!reachable.length) return\n await emailNotification(\n reachable,\n payload,\n options.emails ?? {},\n options.audience,\n )\n }\n } catch (error) {\n console.error('notification fan-out failed', error)\n }\n}\n\n// Staff are identified by a Firebase Auth custom claim (`staff`), which is not\n// a Firestore query — so the roster comes from paginating the auth users. A\n// burst of ticket activity shouldn't rescan every time, so the (small) result\n// is cached briefly. Fails soft to an empty list.\nlet staffUidCache: { uids: string[]; at: number } | null = null\nconst STAFF_CACHE_MS = 60_000\n\nasync function listStaffUids(): Promise<string[]> {\n const now = Date.now()\n if (staffUidCache && now - staffUidCache.at < STAFF_CACHE_MS) {\n return staffUidCache.uids\n }\n // Across ALL auth pools (AGL-1122). This scanned only the project pool, so\n // a staff member who signs in through enterprise SSO — whose account lives\n // in a GCIP tenant pool — was never in the fan-out. Nothing errored; the\n // notification simply never arrived, which is the worst shape a miss can\n // take on an alerting path.\n const uids = await listStaffUidsAcrossPools()\n staffUidCache = { uids, at: now }\n return uids\n}\n\n/**\n * Notifies every staff-claim holder (AGL-850) — the support-desk audience.\n * Staff are not org members, so `notifyOrgAdmins`/`notifyHostManagers` never\n * reach them; this enumerates the `staff` custom claim instead. The docs land\n * at `users/{uid}/notifications`, which the console notifications menu already\n * renders, so no separate staff inbox is needed. Never throws.\n *\n * A type the operator alert registry names (AGL-3377) — a fraud or risk\n * alert, a dispute nobody owns, a support ticket — is raised as that alert\n * instead: the same console notification, plus staff's switches, the\n * operator email or digest, and the webhook. See `raiseOperatorAlert`.\n */\nexport async function notifyStaff(payload: NotificationPayload): Promise<void> {\n try {\n const alert = operatorAlertForNotificationType(payload.type)\n if (alert) {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(alert, {\n subject: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n ...(payload.level ? { level: payload.level } : {}),\n ...(payload.link ? { url: payload.link } : {}),\n ...(payload.orgId ? { orgId: payload.orgId } : {}),\n ...(payload.hostId ? { hostId: payload.hostId } : {}),\n })\n return\n }\n await notifyStaffConsole(payload)\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * The staff console notification alone, with the per-person email channel\n * it carries: what `notifyStaff` did before the registry, and what\n * `raiseOperatorAlert` writes as its first step. Never throws.\n */\nexport async function notifyStaffConsole(\n payload: NotificationPayload,\n options: { skipEmail?: boolean } = {},\n): Promise<void> {\n try {\n await notifyUsers(await listStaffUids(), payload, {\n audience: 'staff',\n ...(options.skipEmail ? { skipEmail: true } : {}),\n })\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * Notifies the org's owner + admins (billing, membership, org events).\n *\n * `skipEmail` is for a caller that emails the same notice to the same people\n * itself — the usage alerts do (AGL-3431) — so an admin who switched the\n * email channel on is not sent it twice.\n */\nexport async function notifyOrgAdmins(\n orgId: string,\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail'> = {},\n): Promise<void> {\n try {\n const members = await listOrgMembers(orgId)\n const admins = members.filter(\n (member) => member.role === 'owner' || member.role === 'admin',\n )\n // The roster rows carry addresses, so the email channel (AGL-3224) needs\n // no directory lookup for anyone reached this way.\n const emails: Record<string, string | undefined> = {}\n for (const member of admins) {\n if (member.email) emails[member.$id] = member.email\n }\n await notifyUsers(\n admins.map((member) => member.$id),\n { ...payload, orgId },\n { emails, ...(options.skipEmail ? { skipEmail: true } : {}) },\n )\n } catch (error) {\n console.error('org admin notification failed', error)\n }\n}\n\n/**\n * The name a site's managers know it by: the name they gave it, then its\n * address, then — for a doc with neither — its id.\n */\nexport function hostDisplayName(\n host: Record<string, unknown> | undefined,\n hostId: string,\n): string {\n for (const value of [host?.['displayName'], host?.['subdomain']]) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return hostId\n}\n\n/**\n * Fills `{site}` in a host notification's title or body (AGL-3432).\n *\n * A manager of ten storefronts reads \"New order — $42.00\" and cannot tell\n * which store it came from, and the email shows only the body to someone who\n * skips the subject. `notifyHostManagers` already reads the host doc, so a\n * caller writes \"New order on {site}\" and pays no read of its own.\n */\nexport function withSiteName(text: string, site: string): string {\n return text.includes('{site}') ? text.split('{site}').join(site) : text\n}\n\n/**\n * Notifies everyone who manages a host (admin/editor in the host doc's\n * `memberRoles` projection) — the audience for form submissions and\n * bookings on that site.\n *\n * The OWNING ORG travels with the notification (AGL-1773). Host links are\n * stored in the legacy `/{hostDocId}/rest` shape and rewritten to\n * `/{orgSlug}/hosts/{subdomain}/rest` when they are FOLLOWED\n * (`normalizeNotificationLink`, AGL-644) — a rewrite that needs an org slug.\n * With no `orgId` on the doc the console had nothing to key on and fell back\n * to whichever org the reader happens to have OPEN, so a manager who belongs\n * to more than one workspace was routed to `/{other-org}/hosts/{subdomain}/…`\n * and got a designed 404: `HostGuard` only resolves subdomains belonging to\n * the current org. `notifyOrgAdmins` has always stamped it; the host fan-out\n * — every form submission, booking, order and stock alert — never did.\n *\n * The host doc already carries `orgId` (AGL-233), so this costs no extra\n * read. Spread conditionally: the field is optional on the host model and\n * Firestore rejects `undefined`.\n */\nexport async function notifyHostManagers(\n hostId: string,\n payload: NotificationPayload,\n options: {\n /**\n * Mail the workspace owner nothing through the email channel, because\n * the caller sends them their own email about the same event.\n */\n skipOwnerEmail?: boolean\n } = {},\n): Promise<void> {\n try {\n const host = await firestore().collection('hosts').doc(hostId).get()\n const memberRoles =\n (host.get('memberRoles') as Record<string, string> | undefined) ?? {}\n const managers = Object.entries(memberRoles)\n .filter(([, role]) => role === 'admin' || role === 'editor')\n .map(([uid]) => uid)\n const orgId = payload.orgId ?? (host.get('orgId') as string | undefined)\n const site = hostDisplayName(host.data(), hostId)\n const ownerUid =\n options.skipOwnerEmail && orgId\n ? ((await firestore().collection('orgs').doc(orgId).get()).get('ownerUid') as\n | string\n | undefined)\n : undefined\n await notifyUsers(\n managers,\n {\n ...payload,\n title: withSiteName(payload.title, site),\n ...(payload.body !== undefined\n ? { body: withSiteName(payload.body, site) }\n : {}),\n hostId,\n ...(orgId ? { orgId } : {}),\n },\n ownerUid ? { skipEmailFor: [ownerUid] } : {},\n )\n } catch (error) {\n console.error('host manager notification failed', error)\n }\n}\n"],"names":["buildRoute","NOTIFICATION_SELF_SENT_EMAIL_TYPES","NOTIFICATION_SETTINGS_FIELD","normalizeNotificationLink","notificationChannelEnabled","Route","operatorAlertForNotificationType","isEmailConfigured","sendEmail","notificationPushEnabled","FieldValue","withoutMailWithheldAccounts","findUserByUidAcrossPools","listStaffUidsAcrossPools","filterSuppressedEmails","meterOrgEmail","meterPlatformEmail","firebaseAdmin","mobilePushEnabled","mobilePushSenders","listOrgMembers","loadSystemEmail","renderLoadedSystemEmail","systemEmailBrand","systemEmailContent","firestore","app","consoleOrigin","process","env","NEXT_PUBLIC_CONSOLE_URL","trim","replace","NOTIFY_EMAIL_MAX_LOOKUPS","NOTIFY_EMAIL_MAX_SENDS","emailNotification","uids","payload","known","audience","origin","settingsUrl","MANAGE_NOTIFICATION_SETTINGS","context","notificationEmailContext","url","notificationEmailUrl","loaded","catch","fallbackText","title","body","filter","Boolean","join","lookups","sent","uid","address","String","toLowerCase","includes","pooled","record","email","recipients","length","rendered","brand","merge","options","result","to","subject","text","fromName","headers","orgId","undefined","org","db","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","exists","data","orgSlug","hostSubdomain","error","console","link","test","startsWith","MANAGE_NOTIFICATIONS","notifyUsers","targets","Set","slice","userDocs","getAll","map","scope","batch","count","mailTo","pushTo","userDoc","settings","legacy","type","set","id","read","createdAt","serverTimestamp","push","skipEmailFor","commit","send","skipEmail","has","reachable","emails","staffUidCache","STAFF_CACHE_MS","listStaffUids","now","Date","at","notifyStaff","alert","raiseOperatorAlert","level","notifyStaffConsole","notifyOrgAdmins","members","admins","member","role","$id","hostDisplayName","value","withSiteName","site","split","notifyHostManagers","memberRoles","managers","Object","entries","ownerUid","skipOwnerEmail"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,kCAAkC,EAClCC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,EAE1BC,KAAK,QAEA,sBAAqB;AAC5B,SAASC,gCAAgC,QAAQ,8CAA6C;AAC9F,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,2BAA2B,QAAQ,oBAAgB;AAC5D,SAASC,wBAAwB,EAAEC,wBAAwB,QAAQ,kBAAc;AACjF,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,aAAa,EAAEC,kBAAkB,QAAQ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AM4C,OAAO,MAAMxD,YAAY2D,UAAU,CAAC,SAASC,GAAG,CAACE,QAAQD,GAAG;QAClE,MAAMmE,eACHxE,YAAAA,KAAKK,GAAG,CAAC,0BAATL,YAAkE,CAAC;QACtE,MAAMyE,WAAWC,OAAOC,OAAO,CAACH,aAC7BrG,MAAM,CAAC,CAAC,GAAG6F,KAAK,GAAKA,SAAS,WAAWA,SAAS,UAClDtC,GAAG,CAAC,CAAC,CAAClD,IAAI,GAAKA;QAClB,MAAMoB,SAAQxC,iBAAAA,QAAQwC,KAAK,YAAbxC,iBAAkB4C,KAAKK,GAAG,CAAC;QACzC,MAAMgE,OAAOH,gBAAgBlE,KAAKW,IAAI,IAAIL;QAC1C,MAAMsE,WACJvF,QAAQwF,cAAc,IAAIjF,QACrB,AAAC,CAAA,MAAMpD,YAAY2D,UAAU,CAAC,QAAQC,GAAG,CAACR,OAAOS,GAAG,EAAC,EAAGA,GAAG,CAAC,cAG7DR;QACN,MAAMuB,YACJqD,UACA,aACKrH;YACHa,OAAOmG,aAAahH,QAAQa,KAAK,EAAEoG;WAC/BjH,QAAQc,IAAI,KAAK2B,YACjB;YAAE3B,MAAMkG,aAAahH,QAAQc,IAAI,EAAEmG;QAAM,IACzC,CAAC;YACL/D;WACIV,QAAQ;YAAEA;QAAM,IAAI,CAAC,IAE3BgF,WAAW;YAAElC,cAAc;gBAACkC;aAAS;QAAC,IAAI,CAAC;IAE/C,EAAE,OAAO9D,OAAO;QACdC,QAAQD,KAAK,CAAC,oCAAoCA;IACpD;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/notifications.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 buildRoute,\n NOTIFICATION_SELF_SENT_EMAIL_TYPES,\n NOTIFICATION_SETTINGS_FIELD,\n normalizeNotificationLink,\n notificationChannelEnabled,\n type AglynNotification,\n Route,\n type NotificationSettings,\n} from '@aglyn/aglyn/server'\nimport { operatorAlertForNotificationType } from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { notificationPushEnabled } from '@aglyn/aglyn/app-utils/notification-push'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools, listStaffUidsAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { meterOrgEmail, meterPlatformEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { mobilePushEnabled, mobilePushSenders } from './mobile-push-switch'\nimport { listOrgMembers } from './organizations'\nimport {\n loadSystemEmail,\n renderLoadedSystemEmail,\n systemEmailBrand,\n systemEmailContent,\n type SystemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type NotificationPayload = Omit<\n AglynNotification,\n '$id' | 'createdAt' | 'readAt'\n>\n\nexport interface NotifyUsersOptions {\n /**\n * Addresses the caller already holds, by uid (AGL-3224).\n *\n * Purely an optimization, and one worth taking where it is free: a caller\n * that read the roster — `notifyOrgAdmins` does — has every address in hand\n * already, and without this the email half would look each one up again in\n * the directory. Absent uids fall back to that lookup, so passing a partial\n * map is fine and passing none is correct.\n */\n emails?: Readonly<Record<string, string | null | undefined>>\n /**\n * Who the fan-out is for (AGL-3367). `staff` is the platform talking to its\n * own people, so the email wears the platform's brand and is the platform's\n * cost even when the notification is ABOUT an org, which a canceled\n * subscription or a new ticket always is. Anything else speaks in the org's\n * brand when the notification names one.\n */\n audience?: 'staff'\n /**\n * Write the console notification only, and mail nobody through the\n * per-person email channel (AGL-3375): the caller has emailed the same\n * alert to the operator's inbox, and a staff member who also switched\n * email on would otherwise get it twice.\n */\n skipEmail?: boolean\n /**\n * People not to mail through the email channel for this one notification,\n * because the caller emails them the same event itself — the seller's\n * designed sale email beside a Buy Now order's notification. Everyone else\n * the fan-out reaches is mailed as their preferences say.\n */\n skipEmailFor?: readonly string[]\n /**\n * Particulars the email carries and the notification does not: a form\n * submission's answers, so the person reading the email has the inquiry\n * without opening the console.\n *\n * Email only, never written to the notification document or pushed. The\n * document is copied once per recipient and outlives the record it points\n * at, and a push lands on a lock screen; the record itself stays the one\n * place the visitor's answers are kept.\n */\n emailDetails?: readonly NotificationEmailDetail[]\n}\n\n/** One labeled line of a notification email's details. */\nexport interface NotificationEmailDetail {\n label: string\n value: string\n}\n\n/**\n * At most this many characters of details per email. A submission is capped\n * at 2,000 characters a field, so a long form would otherwise be a long email.\n */\nconst NOTIFY_EMAIL_MAX_DETAILS_CHARS = 10_000\n\n/**\n * The details as the email prints them: `Label: value`, one per line, a\n * value's own line breaks kept and blank values left out.\n */\nexport function formatNotificationEmailDetails(\n details: readonly NotificationEmailDetail[] | undefined,\n): string {\n const text = (details ?? [])\n .map(({ label, value }) => ({ label: label.trim(), value: value.trim() }))\n .filter(({ value }) => value)\n .map(({ label, value }) => (label ? `${label}: ${value}` : value))\n .join('\\n')\n return text.length > NOTIFY_EMAIL_MAX_DETAILS_CHARS\n ? `${text.slice(0, NOTIFY_EMAIL_MAX_DETAILS_CHARS).trimEnd()}…`\n : text\n}\n\n/**\n * At most this many directory lookups per fan-out, and at most this many\n * notification emails.\n *\n * Both ceilings only ever bite on a fan-out where many recipients have\n * OPTED IN — the email channel defaults off outside a site's transactions\n * (`NOTIFICATION_TYPE_CHANNEL_DEFAULTS`), so the ordinary notification\n * costs exactly what it cost before this existed. They are here because a\n * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation\n * that emitted it: a notification must not be able to turn one write into\n * four hundred directory reads and four hundred sends.\n */\nconst NOTIFY_EMAIL_MAX_LOOKUPS = 25\nconst NOTIFY_EMAIL_MAX_SENDS = 50\n\n/**\n * The email beside the console notification (AGL-3224).\n *\n * One send per recipient, never a shared `to:` list — two people who manage\n * the same site have not agreed to be shown each other's addresses, and the\n * settings link in the footer belongs to one person.\n *\n * `List-Unsubscribe` points at the settings page rather than at a one-click\n * endpoint: this is not marketing mail and RFC 8058's POST form would be\n * claiming a capability that does not exist. What it does do is put the way\n * out in the headers as well as the body, so a client that surfaces it shows\n * the person the page where the switch they want actually is.\n *\n * Rendered through the `notification` system email (AGL-3367), which is what\n * gives it the header and footer every other system email wears, and makes\n * it designable on the staff System emails page. It used to hand `sendEmail`\n * bare text, which is the unbranded card the fallback HTML part draws. The\n * template is read once per fan-out and rendered per recipient.\n *\n * Never throws, like everything else on this path.\n */\nasync function emailNotification(\n uids: string[],\n payload: NotificationPayload,\n known: Readonly<Record<string, string | null | undefined>>,\n audience: NotifyUsersOptions['audience'],\n emailDetails: NotifyUsersOptions['emailDetails'],\n): Promise<void> {\n /*\n * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this\n * runs in the site app as well as the console, and the site app's\n * deployment does not set that variable. Read bare, a notification a site\n * sends (a form submission, an order) would carry a button that opens\n * nothing and a settings line with no address.\n */\n const origin = platformConsoleOrigin()\n const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`\n const context = await notificationEmailContext(payload, audience)\n const url = notificationEmailUrl(payload, context, origin)\n const details = formatNotificationEmailDetails(emailDetails)\n const loaded = await loadSystemEmail('notification').catch(() => null)\n const fallbackText = [\n payload.title,\n payload.body ?? '',\n details,\n url,\n `Change what you are emailed about: ${settingsUrl}`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n let lookups = 0\n let sent = 0\n for (const uid of uids) {\n if (sent >= NOTIFY_EMAIL_MAX_SENDS) break\n let address = String(known[uid] ?? '').trim().toLowerCase()\n if (!address.includes('@')) {\n if (lookups >= NOTIFY_EMAIL_MAX_LOOKUPS) continue\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '').trim().toLowerCase()\n }\n if (!address.includes('@')) continue\n const recipients = await filterSuppressedEmails([address])\n if (!recipients.length) continue\n const rendered = loaded\n ? renderLoadedSystemEmail(\n loaded,\n {\n ...context.brand.merge,\n 'notification.title': payload.title,\n 'notification.body': payload.body ?? '',\n 'notification.details': details,\n 'notification.url': url,\n settingsUrl,\n },\n context.brand.options,\n )\n : null\n const result = await sendEmail({\n to: recipients,\n ...systemEmailContent(rendered, {\n subject: payload.title,\n text: fallbackText,\n }),\n ...(context.brand.fromName ? { fromName: context.brand.fromName } : {}),\n context: 'notification',\n headers: { 'List-Unsubscribe': `<${settingsUrl}>` },\n })\n if (!result.sent) continue\n sent += 1\n // Whose cost it is: a notification to a workspace's people is that\n // workspace's mail, and a staff alert or an account-level notice is the\n // platform's, whichever org it is about.\n await (payload.orgId && audience !== 'staff'\n ? meterOrgEmail(payload.orgId)\n : meterPlatformEmail()\n ).catch(() => undefined)\n }\n}\n\n/** What a notification email needs from the org and site it is about. */\ninterface NotificationEmailContext {\n brand: SystemEmailBrand\n orgSlug?: string\n hostSubdomain?: string\n}\n\n/**\n * The org's brand, and the slug and subdomain its stored link is rewritten\n * with (AGL-3367): at most two reads per fan-out, made only when someone is\n * being emailed.\n *\n * A staff fan-out reads nothing. Its brand is the platform's, and its links\n * are staff routes that need no rewriting.\n */\nasync function notificationEmailContext(\n payload: NotificationPayload,\n audience: NotifyUsersOptions['audience'],\n): Promise<NotificationEmailContext> {\n if (audience === 'staff' || !payload.orgId) {\n return { brand: systemEmailBrand(null) }\n }\n try {\n const db = firestore()\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId\n ? db.collection('hosts').doc(payload.hostId).get()\n : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n return {\n brand: systemEmailBrand(org.exists ? (org.data() ?? null) : null),\n ...(typeof slug === 'string' && slug ? { orgSlug: slug } : {}),\n ...(typeof subdomain === 'string' && subdomain\n ? { hostSubdomain: subdomain }\n : {}),\n }\n } catch (error) {\n console.error('notification email context failed', error)\n return { brand: systemEmailBrand(null) }\n }\n}\n\n/**\n * Where the email's button goes: the notification's own link, rewritten onto\n * today's routes the way the console rewrites it when it is clicked, else\n * the notifications page. A stored host link is `/{hostDocId}/…`, which only\n * that rewrite turns into a page that exists.\n */\nfunction notificationEmailUrl(\n payload: NotificationPayload,\n context: NotificationEmailContext,\n origin: string,\n): string {\n const link = normalizeNotificationLink(payload.link, {\n orgSlug: context.orgSlug,\n hostId: payload.hostId,\n hostSubdomain: context.hostSubdomain,\n })\n if (link && /^https?:\\/\\//i.test(link)) return link\n return `${origin}${link?.startsWith('/') ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`\n}\n\n/**\n * Notification fan-out (AGL-259): batch-writes one doc per recipient at\n * `users/{uid}/notifications`, and — for recipients who asked for it\n * (AGL-3224) — sends one email beside it. Never throws: a notification miss,\n * or a send that failed, must not break the mutation that emitted it.\n */\nexport async function notifyUsers(\n uids: Iterable<string>,\n payload: NotificationPayload,\n options: NotifyUsersOptions = {},\n): Promise<void> {\n try {\n const db = firestore()\n const targets = [...new Set(uids)].filter(Boolean).slice(0, 400)\n if (!targets.length) return\n // Per-user preferences (AGL-267, AGL-3223): one getAll over the user\n // docs, which now answers for both channels and for all three scopes —\n // the settings live on this document precisely so that stays one read.\n const userDocs = await db.getAll(\n ...targets.map((uid) => db.collection('users').doc(uid)),\n )\n const scope = { orgId: payload.orgId, hostId: payload.hostId }\n const batch = db.batch()\n let count = 0\n const mailTo: string[] = []\n const pushTo: string[] = []\n for (const userDoc of userDocs) {\n const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD) as\n | NotificationSettings\n | undefined\n const legacy = userDoc.get('notificationPrefs') as\n | Record<string, boolean>\n | undefined\n if (\n notificationChannelEnabled(\n settings,\n 'console',\n payload.type,\n scope,\n legacy,\n )\n ) {\n batch.set(\n db\n .collection('users')\n .doc(userDoc.id)\n .collection('notifications')\n .doc(),\n // `read: false` on create, so the feed can ask for unread and read\n // alike by equality (AGL-3321; see `AglynNotification.read`).\n { ...payload, read: false, createdAt: FieldValue.serverTimestamp() },\n )\n count += 1\n }\n // The mobile push channel (AGL-3620); unanswered, it follows the feed.\n if (notificationPushEnabled(settings, payload.type, scope, legacy)) {\n pushTo.push(userDoc.id)\n }\n if (\n notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) &&\n !options.skipEmailFor?.includes(userDoc.id)\n ) {\n mailTo.push(userDoc.id)\n }\n }\n if (count > 0) await batch.commit()\n /*\n * The push after the commit for the same reason as the email below:\n * every registered transport is handed the recipients whose preferences\n * say push, unless the deployment has pulled the kill switch. A failing\n * transport is logged and never stops the email or another transport.\n */\n if (pushTo.length && mobilePushEnabled()) {\n for (const send of mobilePushSenders()) {\n try {\n await send(pushTo, payload, { db })\n } catch (error) {\n console.error('push delivery failed', error)\n }\n }\n }\n /*\n * THE EMAIL AFTER THE COMMIT, and not inside its `try`.\n *\n * The console notification is the durable record and the send is a\n * courtesy on top of it, so the order is the one where a failing network\n * call cannot lose the record. The two channels are independent by\n * design — a person may have muted the feed and asked for mail, or the\n * reverse — so neither is gated on the other having happened.\n *\n * Digests are excluded: they compose and send their own mail, under\n * their own switches, and the generic channel would send a second\n * message announcing that the first one had been sent.\n *\n * A locked or disabled account is not mailed (AGL-3418); its feed entry\n * above still records the event.\n */\n if (\n mailTo.length &&\n !options.skipEmail &&\n isEmailConfigured() &&\n !NOTIFICATION_SELF_SENT_EMAIL_TYPES.has(payload.type)\n ) {\n const reachable = await withoutMailWithheldAccounts(mailTo)\n if (!reachable.length) return\n await emailNotification(\n reachable,\n payload,\n options.emails ?? {},\n options.audience,\n options.emailDetails,\n )\n }\n } catch (error) {\n console.error('notification fan-out failed', error)\n }\n}\n\n// Staff are identified by a Firebase Auth custom claim (`staff`), which is not\n// a Firestore query — so the roster comes from paginating the auth users. A\n// burst of ticket activity shouldn't rescan every time, so the (small) result\n// is cached briefly. Fails soft to an empty list.\nlet staffUidCache: { uids: string[]; at: number } | null = null\nconst STAFF_CACHE_MS = 60_000\n\nasync function listStaffUids(): Promise<string[]> {\n const now = Date.now()\n if (staffUidCache && now - staffUidCache.at < STAFF_CACHE_MS) {\n return staffUidCache.uids\n }\n // Across ALL auth pools (AGL-1122). This scanned only the project pool, so\n // a staff member who signs in through enterprise SSO — whose account lives\n // in a GCIP tenant pool — was never in the fan-out. Nothing errored; the\n // notification simply never arrived, which is the worst shape a miss can\n // take on an alerting path.\n const uids = await listStaffUidsAcrossPools()\n staffUidCache = { uids, at: now }\n return uids\n}\n\n/**\n * Notifies every staff-claim holder (AGL-850) — the support-desk audience.\n * Staff are not org members, so `notifyOrgAdmins`/`notifyHostManagers` never\n * reach them; this enumerates the `staff` custom claim instead. The docs land\n * at `users/{uid}/notifications`, which the console notifications menu already\n * renders, so no separate staff inbox is needed. Never throws.\n *\n * A type the operator alert registry names (AGL-3377) — a fraud or risk\n * alert, a dispute nobody owns, a support ticket — is raised as that alert\n * instead: the same console notification, plus staff's switches, the\n * operator email or digest, and the webhook. See `raiseOperatorAlert`.\n */\nexport async function notifyStaff(payload: NotificationPayload): Promise<void> {\n try {\n const alert = operatorAlertForNotificationType(payload.type)\n if (alert) {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(alert, {\n subject: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n ...(payload.level ? { level: payload.level } : {}),\n ...(payload.link ? { url: payload.link } : {}),\n ...(payload.orgId ? { orgId: payload.orgId } : {}),\n ...(payload.hostId ? { hostId: payload.hostId } : {}),\n })\n return\n }\n await notifyStaffConsole(payload)\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * The staff console notification alone, with the per-person email channel\n * it carries: what `notifyStaff` did before the registry, and what\n * `raiseOperatorAlert` writes as its first step. Never throws.\n */\nexport async function notifyStaffConsole(\n payload: NotificationPayload,\n options: { skipEmail?: boolean } = {},\n): Promise<void> {\n try {\n await notifyUsers(await listStaffUids(), payload, {\n audience: 'staff',\n ...(options.skipEmail ? { skipEmail: true } : {}),\n })\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * Notifies the org's owner + admins (billing, membership, org events).\n *\n * `skipEmail` is for a caller that emails the same notice to the same people\n * itself — the usage alerts do (AGL-3431) — so an admin who switched the\n * email channel on is not sent it twice.\n */\nexport async function notifyOrgAdmins(\n orgId: string,\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail'> = {},\n): Promise<void> {\n try {\n const members = await listOrgMembers(orgId)\n const admins = members.filter(\n (member) => member.role === 'owner' || member.role === 'admin',\n )\n // The roster rows carry addresses, so the email channel (AGL-3224) needs\n // no directory lookup for anyone reached this way.\n const emails: Record<string, string | undefined> = {}\n for (const member of admins) {\n if (member.email) emails[member.$id] = member.email\n }\n await notifyUsers(\n admins.map((member) => member.$id),\n { ...payload, orgId },\n { emails, ...(options.skipEmail ? { skipEmail: true } : {}) },\n )\n } catch (error) {\n console.error('org admin notification failed', error)\n }\n}\n\n/**\n * The name a site's managers know it by: the name they gave it, then its\n * address, then — for a doc with neither — its id.\n */\nexport function hostDisplayName(\n host: Record<string, unknown> | undefined,\n hostId: string,\n): string {\n for (const value of [host?.['displayName'], host?.['subdomain']]) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return hostId\n}\n\n/**\n * Fills `{site}` in a host notification's title or body (AGL-3432).\n *\n * A manager of ten storefronts reads \"New order — $42.00\" and cannot tell\n * which store it came from, and the email shows only the body to someone who\n * skips the subject. `notifyHostManagers` already reads the host doc, so a\n * caller writes \"New order on {site}\" and pays no read of its own.\n */\nexport function withSiteName(text: string, site: string): string {\n return text.includes('{site}') ? text.split('{site}').join(site) : text\n}\n\n/**\n * Notifies everyone who manages a host (admin/editor in the host doc's\n * `memberRoles` projection) — the audience for form submissions and\n * bookings on that site.\n *\n * The OWNING ORG travels with the notification (AGL-1773). Host links are\n * stored in the legacy `/{hostDocId}/rest` shape and rewritten to\n * `/{orgSlug}/hosts/{subdomain}/rest` when they are FOLLOWED\n * (`normalizeNotificationLink`, AGL-644) — a rewrite that needs an org slug.\n * With no `orgId` on the doc the console had nothing to key on and fell back\n * to whichever org the reader happens to have OPEN, so a manager who belongs\n * to more than one workspace was routed to `/{other-org}/hosts/{subdomain}/…`\n * and got a designed 404: `HostGuard` only resolves subdomains belonging to\n * the current org. `notifyOrgAdmins` has always stamped it; the host fan-out\n * — every form submission, booking, order and stock alert — never did.\n *\n * The host doc already carries `orgId` (AGL-233), so this costs no extra\n * read. Spread conditionally: the field is optional on the host model and\n * Firestore rejects `undefined`.\n */\nexport async function notifyHostManagers(\n hostId: string,\n payload: NotificationPayload,\n options: {\n /**\n * Mail the workspace owner nothing through the email channel, because\n * the caller sends them their own email about the same event.\n */\n skipOwnerEmail?: boolean\n /** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */\n emailDetails?: readonly NotificationEmailDetail[]\n } = {},\n): Promise<void> {\n try {\n const host = await firestore().collection('hosts').doc(hostId).get()\n const memberRoles =\n (host.get('memberRoles') as Record<string, string> | undefined) ?? {}\n const managers = Object.entries(memberRoles)\n .filter(([, role]) => role === 'admin' || role === 'editor')\n .map(([uid]) => uid)\n const orgId = payload.orgId ?? (host.get('orgId') as string | undefined)\n const site = hostDisplayName(host.data(), hostId)\n const ownerUid =\n options.skipOwnerEmail && orgId\n ? ((await firestore().collection('orgs').doc(orgId).get()).get('ownerUid') as\n | string\n | undefined)\n : undefined\n await notifyUsers(\n managers,\n {\n ...payload,\n title: withSiteName(payload.title, site),\n ...(payload.body !== undefined\n ? { body: withSiteName(payload.body, site) }\n : {}),\n hostId,\n ...(orgId ? { orgId } : {}),\n },\n {\n ...(ownerUid ? { skipEmailFor: [ownerUid] } : {}),\n ...(options.emailDetails ? { emailDetails: options.emailDetails } : {}),\n },\n )\n } catch (error) {\n console.error('host manager notification failed', error)\n }\n}\n"],"names":["buildRoute","NOTIFICATION_SELF_SENT_EMAIL_TYPES","NOTIFICATION_SETTINGS_FIELD","normalizeNotificationLink","notificationChannelEnabled","Route","operatorAlertForNotificationType","isEmailConfigured","sendEmail","notificationPushEnabled","platformConsoleOrigin","FieldValue","withoutMailWithheldAccounts","findUserByUidAcrossPools","listStaffUidsAcrossPools","filterSuppressedEmails","meterOrgEmail","meterPlatformEmail","firebaseAdmin","mobilePushEnabled","mobilePushSenders","listOrgMembers","loadSystemEmail","renderLoadedSystemEmail","systemEmailBrand","systemEmailContent","firestore","app","NOTIFY_EMAIL_MAX_DETAILS_CHARS","formatNotificationEmailDetails","details","text","map","label","value","trim","filter","join","length","slice","trimEnd","NOTIFY_EMAIL_MAX_LOOKUPS","NOTIFY_EMAIL_MAX_SENDS","emailNotification","uids","payload","known","audience","emailDetails","origin","settingsUrl","MANAGE_NOTIFICATION_SETTINGS","context","notificationEmailContext","url","notificationEmailUrl","loaded","catch","fallbackText","title","body","Boolean","lookups","sent","uid","address","String","toLowerCase","includes","pooled","record","email","recipients","rendered","brand","merge","options","result","to","subject","fromName","headers","orgId","undefined","org","db","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","exists","data","orgSlug","hostSubdomain","error","console","link","test","startsWith","MANAGE_NOTIFICATIONS","notifyUsers","targets","Set","userDocs","getAll","scope","batch","count","mailTo","pushTo","userDoc","settings","legacy","type","set","id","read","createdAt","serverTimestamp","push","skipEmailFor","commit","send","skipEmail","has","reachable","emails","staffUidCache","STAFF_CACHE_MS","listStaffUids","now","Date","at","notifyStaff","alert","raiseOperatorAlert","level","notifyStaffConsole","notifyOrgAdmins","members","admins","member","role","$id","hostDisplayName","withSiteName","site","split","notifyHostManagers","memberRoles","managers","Object","entries","ownerUid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