@aglyn/aglyn 1.0.0-beta.206 → 1.0.0-beta.209
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 +11 -11
- package/src/lib/app-utils/announce-site-wide-change.d.ts +45 -0
- package/src/lib/app-utils/announce-site-wide-change.js +58 -0
- package/src/lib/app-utils/announce-site-wide-change.js.map +1 -0
- package/src/lib/app-utils/console-routes.d.ts +2 -0
- package/src/lib/app-utils/console-routes.js +3 -0
- package/src/lib/app-utils/console-routes.js.map +1 -1
- package/src/lib/app-utils/content-authors.d.ts +12 -64
- package/src/lib/app-utils/content-authors.js +0 -133
- package/src/lib/app-utils/content-authors.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +6 -0
- package/src/lib/app-utils/docs-help.generated.js +61 -0
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +4 -4
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/health-report.js +13 -0
- package/src/lib/app-utils/health-report.js.map +1 -1
- package/src/lib/app-utils/host-transfer.d.ts +55 -0
- package/src/lib/app-utils/host-transfer.js +23 -0
- package/src/lib/app-utils/host-transfer.js.map +1 -0
- package/src/lib/app-utils/local-business.d.ts +161 -0
- package/src/lib/app-utils/local-business.js +253 -0
- package/src/lib/app-utils/local-business.js.map +1 -0
- package/src/lib/app-utils/notifications.d.ts +1 -13
- package/src/lib/app-utils/notifications.js +1 -16
- package/src/lib/app-utils/notifications.js.map +1 -1
- package/src/lib/app-utils/operator-alerts.d.ts +132 -0
- package/src/lib/app-utils/operator-alerts.js +513 -0
- package/src/lib/app-utils/operator-alerts.js.map +1 -0
- package/src/lib/app-utils/screen-link-value.d.ts +4 -0
- package/src/lib/app-utils/screen-link-value.js +6 -2
- package/src/lib/app-utils/screen-link-value.js.map +1 -1
- package/src/lib/app-utils/server.d.ts +1 -0
- package/src/lib/app-utils/server.js +9 -0
- package/src/lib/app-utils/server.js.map +1 -1
- package/src/lib/app-utils/site-entity-json-ld.d.ts +96 -0
- package/src/lib/app-utils/site-entity-json-ld.js +220 -0
- package/src/lib/app-utils/site-entity-json-ld.js.map +1 -0
- package/src/lib/foundation/definitions/platform.types.d.ts +24 -0
- package/src/lib/foundation/definitions/platform.types.js.map +1 -1
- package/src/lib/plugin-manager/feature-plugins.d.ts +9 -0
- package/src/lib/plugin-manager/feature-plugins.js +9 -0
- package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.js +8 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/operator-alerts.d.ts +37 -0
- package/src/lib/plugin-manager/operator-alerts.js +80 -0
- package/src/lib/plugin-manager/operator-alerts.js.map +1 -0
- package/src/lib/plugin-manager/plugin-host-collections.d.ts +11 -0
- package/src/lib/plugin-manager/plugin-host-collections.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/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 type { ITimestamp } from '@aglyn/shared-util-timestamp'\nimport { buildRoute, Route } from './console-routes'\n\n/**\n * In-app notifications (AGL-259): per-user docs at\n * `users/{uid}/notifications/{id}`, written by the Admin SDK (emitters in\n * the API routes + the `notifyAdmins` automation step) and read/marked by\n * their owner. Types follow the common SaaS taxonomy so the console can\n * icon/group them without a registry.\n */\nexport type AglynNotificationType =\n | 'billing.invoice'\n | 'billing.paymentFailed'\n // Stripe gave up on a failed renewal and CANCELLED the subscription\n // (AGL-1877). Distinct from `paymentFailed`, which announces one failed\n // attempt inside a retry window the customer can still recover from; this\n // one is the window having closed. Measured on the test account with a\n // test clock: five attempts over 21.08 days, then\n // `cancellation_details.reason: 'payment_failed'` — and until this existed\n // the org went silently to Free at that moment, with the `past_due` banner\n // disappearing at exactly the instant the consequence arrived.\n | 'billing.subscriptionCanceled'\n | 'billing.usage'\n | 'team.invite'\n | 'team.roleChanged'\n | 'team.hostAccessGranted'\n | 'content.formSubmission'\n | 'content.booking'\n | 'content.order'\n | 'content.lowStock'\n // A CRM task was assigned to the recipient by somebody else (AGL-2599).\n // `content.` because it is the same kind of message as a form submission\n // or a booking: a thing on the site that now needs this person's hands,\n // not a change to their standing (`team.`) and not a platform notice\n // (`system.`). Someone who has muted the operational stream has said they\n // do not want to be told about work as it arrives, and a task is work.\n | 'content.taskAssigned'\n // A CRM task's reminder came due (AGL-2659): the hourly runner telling\n // the assignee, at the task's own time, that the task is due. `content.`\n // beside `taskAssigned` for the same reason it gives — work on the site,\n // not standing — and so the one mute that stops \"work arriving\" stops\n // \"work falling due\" with it. The mute governs the whole reminder, mail\n // included, unlike the digest's: a reminder is one message about one\n // task, and there is no schedule to keep separately from it.\n | 'content.taskReminder'\n // A contact, or a lead, became the recipient's to work (AGL-2618): a\n // capture the assignment rules or the site's default owner routed to\n // them, a lead somebody converted and handed to them, or an automation's\n // \"assign an owner\" step — every server path that writes `ownerUid`\n // except the recipient assigning themselves. Two types rather than one\n // because the record the person opens differs: a lead is the site's own\n // working record and a contact is the org's, and the link goes to the\n // one they will actually work. `content.`, beside `taskAssigned`, for the\n // same reason: work arriving, not standing changing.\n | 'content.contactAssigned'\n | 'content.leadAssigned'\n // The morning's CRM digest (AGL-2619): what the recipient owes today —\n // overdue and due-today tasks, and the leads nobody has worked. `content.`\n // for the reason `taskAssigned` is: it is about work on the site, and the\n // person who muted the operational stream has asked not to be told about\n // work. The digest EMAIL is governed separately, by\n // `crmDailyDigestEnabled`: the mute is a fact about the console feed and\n // the digest switch is a fact about the digest.\n | 'content.crmDailyDigest'\n // The weekly insights (AGL-2915): what a site's figures showed that week,\n // for a person who asked for them. `content.` beside the CRM digest, for the\n // reason that one gives: it is about the site's work, and the operational\n // mute governs the console notification while the person's own switch for\n // the digest governs the digest.\n | 'content.insightsDigest'\n // Marketplace review verdicts (AGL-432/653).\n | 'marketplace.review'\n // Support desk, staff audience (AGL-850): a subscriber opened or replied to\n // a ticket. Fanned out to staff-claim holders, not org members.\n | 'support.ticketOpened'\n | 'support.ticketReply'\n | 'system.announcement'\n // A live plugin version stopped passing the static verifier (AGL-1086).\n // Staff audience: bytes we told workspaces were checked now fail checks\n // that did not exist when they were approved.\n //\n // Deliberately NOT under `marketplace.` (AGL-1088). Category is the prefix,\n // categories are mutable per user, and Marketplace is the category a staff\n // member mutes to stop routine listing-review chatter — which would drop\n // this alert as collateral. `system` is the bucket nobody mutes to reduce\n // noise. The adminAudit record survives a mute either way; the timeliness\n // does not, and timeliness is the whole point of the alert.\n | 'system.pluginVerifierRegression'\n // A sign-in method was removed from the user's own account because their\n // organization turned on SSO enforcement (AGL-1129). `system.`, not\n // `team.`, for the AGL-1088 reason above: `team` is the category someone\n // mutes to stop routine roster chatter, and \"the way you sign in just\n // changed\" is not chatter — the next sign-in fails without it.\n | 'system.signInMethodRemoved'\n // Documents in a scoped collection carrying no `visibleTo` (AGL-1478).\n // Staff audience: the weekly dry run found resources that are invisible\n // to every site-scoped read, which always means a creation path forgot\n // the field. `system.` for the AGL-1088 reason above, and because the\n // collection it names may be `marketplace`-adjacent or not.\n | 'system.scopeDrift'\n // An SSO domain that WAS DNS-proven has stopped answering with our\n // challenge record, for three consecutive weekly sweeps (AGL-1210).\n // Nothing has been turned off — sign-in for that domain still routes\n // exactly as it did — and that is precisely why this has to be said out\n // loud rather than left in a log.\n //\n // `system.`, not `team.`, for the AGL-1088 reason above and one of its\n // own: the audience is the org's own admins, the subject is whether their\n // people can still sign in, and it must reach them BEFORE anybody decides\n // to revoke the routing. A category somebody mutes to quieten roster\n // chatter is the wrong place for the one warning that precedes a lockout.\n | 'system.ssoDomainUnverified'\n // A site hit the per-month form-submission abuse ceiling and further\n // submissions are being refused (AGL-1655). `system.`, not `content.`, for\n // the AGL-1088 reason above and more sharply than any of them: `content` is\n // literally the category a site owner mutes to stop routine form-submission\n // chatter, and this is the one form notification that says the form has\n // STOPPED accepting. Filing it under the muted bucket would guarantee it\n // reaches nobody on exactly the sites busy enough to trip it.\n | 'system.formSubmissionsPaused'\n // A site reached the flat platform ceiling on member accounts or on lead\n // records, so further ones are being refused (AGL-1529). `system.` for the\n // same reason as `formSubmissionsPaused` directly above, and with the same\n // sharpness: `content.` is the bucket an owner mutes to stop routine\n // sign-up and lead chatter, and this is the one notification saying the\n // sign-ups have STOPPED — muted exactly on the sites busy enough to trip it.\n | 'system.visitorRecordsPaused'\n // An outsider reported one of our sites for phishing, malware or CSAM\n // (AGL-1964). `system` for the AGL-1088 reason and, again, more sharply\n // than most: this notification goes to STAFF, not to a customer, and its\n // subject is somebody else's site. There is no bucket a recipient could\n // mute it into that would be honest — nobody has opted into being told a\n // stranger is being phished through our platform, and nobody should be able\n // to opt out of it either.\n //\n // Only the urgent categories raise one, and only on a first report. See the\n // fan-out in apps/tenant/app/api/report-abuse/route.ts for why: a flood of\n // alerts IS the flood, and the alert it would cost us is the phishing one.\n | 'system.abuseReportUrgent'\n // Something on the recipient's OWN workspace was held, flagged, locked or\n // paused (AGL-3368): an email or page held for review, a flagged domain,\n // a fraud signal on a payment, a lock and its lift. Written by\n // `notifyRiskEvent` from the risk notice catalog, which says what happened,\n // what it means and how to request a review. `system.` for the AGL-1088\n // reason: it is the one message saying the owner's work has STOPPED, and a\n // category muted to quieten routine chatter must not swallow it. It sends\n // its own email, transactional and preference-free, so it is also in\n // NOTIFICATION_SELF_SENT_EMAIL_TYPES.\n | 'system.riskNotice'\n // The §512(g) counter-notice (AGL-1983), and the one place the \"only urgent\n // categories raise a notification\" restraint above is deliberately not\n // applied. Every counter-notice carries a statutory deadline that is\n // ALREADY RUNNING when it arrives — the clock counts from the subscriber's\n // submission, not from our attention — so there is no low-value tail of\n // these to drown out the important ones, and the one that goes unread is a\n // customer locked out of their own work plus an unmet obligation under\n // §512(g)(2)(A). Raised on first submission only, like the one above, so a\n // resubmitting customer cannot re-alert.\n | 'system.dmcaCounterNotice'\n // A site crossed the per-month bandwidth abuse ceiling (AGL-2155). Two\n // audiences share one type: staff, because an uncompensated free site\n // serving six figures of page views is an incident; and the site's own\n // managers, because on free the site is now serving a capped notice and\n // nobody should learn that from a visitor.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this meter: on the free plan there is no bill, so `billing` would be the\n // one category where the message is literally never about money — and it is\n // exactly the free-tier trip that changes what visitors see.\n | 'system.bandwidthCeilingTripped'\n // A free site crossed its PLAN's included bandwidth and is now serving the\n // capped notice (AGL-2413). Distinct from the ceiling above on purpose: that\n // one is an incident at 10x the band and goes to staff first; this one is an\n // ordinary quota at 1x, concerns only the site's own managers, and its\n // remedy is an upgrade rather than an investigation. Sending both under one\n // type would tell an owner their traffic was being treated as suspected\n // abuse when it is simply a successful free site.\n | 'system.bandwidthCapEngaged'\n // A Stripe billing webhook threw AFTER its handlers had begun (AGL-2157),\n // so its side effects may be half applied and its idempotency claim is\n // being HELD — Stripe will not retry it. Staff audience: this is the one\n // failure on that route no automatic retry can make safe, because the\n // handlers behind it are not all idempotent, and a human has to reconcile.\n | 'system.billingWebhookHalfApplied'\n // A card dispute arrived that NOTHING in the platform claimed (AGL-2429):\n // no `platformRevenue` row, no storefront order, no marketplace purchase.\n // Staff audience, and the reason it needs a type of its own is that its\n // absence was the bug — the routine case (a storefront or marketplace\n // chargeback, which the plugins own) and the fault case were the same\n // silence from the route's side, so a dispute nobody handled looked\n // exactly like one somebody did.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this alert: `billing` is the category a recipient is most likely to have\n // muted as routine invoice traffic, and this is the one message on that\n // route where muting it means money moves with nobody looking.\n | 'system.disputeUnattributed'\n // Somebody created an account, and somebody created a workspace\n // (AGL-3225). Staff audience, and the only two types in the taxonomy whose\n // subject is the platform's own growth rather than anybody's work.\n //\n // `staff.`, and NOT `system.`, and the AGL-1088 note above is the reason\n // rather than an exception to it: `system` is the bucket nobody mutes to\n // reduce noise, which is exactly what makes it the wrong home for the two\n // routine, high-volume events in the product. A staff member must be able\n // to stop hearing about every sign-up without also dropping the verifier\n // regression and the unattributed dispute that share that bucket — and\n // before this category existed, there was nowhere to put them where that\n // was true.\n //\n // The category also tells the settings page who a row is for: `staff` is\n // rendered only to claim holders, so no customer is shown a switch for\n // notifications they could never receive.\n | 'staff.userSignedUp'\n | 'staff.orgCreated'\n // And when money moves (AGL-3267). The category was two signup types, so\n // the one thing a platform feed exists to report — revenue starting,\n // changing and stopping — was the one thing it did not.\n //\n // `staff.paymentFailed` is deliberately NOT the customer's\n // `billing.paymentFailed`: different audience, different action. The\n // customer is told to fix their card; staff are told a paying workspace is\n // about to stop paying.\n | 'staff.subscriptionStarted'\n | 'staff.subscriptionCanceled'\n | 'staff.planChanged'\n | 'staff.paymentFailed'\n\nexport interface AglynNotification {\n $id?: string\n type: AglynNotificationType\n title: string\n body?: string\n /** Console path the notification opens (e.g. a host inbox). */\n link?: string\n orgId?: string\n hostId?: string\n createdAt?: ITimestamp\n /** When the owner read it; absent or null while unread. */\n readAt?: ITimestamp | null\n /**\n * Whether the owner has read it — `false` on create, `true` beside\n * `readAt` when read (AGL-3321).\n *\n * A boolean rather than `readAt: null`, because the feed filters by it\n * under its newest-first cursor. Equality on a boolean answers BOTH\n * states (`read == false`, `read == true`) beneath `orderBy('createdAt')`\n * with one composite index. A nullable timestamp answers \"unread\" by\n * equality but \"read\" only as `readAt != null`, and Firestore requires an\n * inequality's field to be the FIRST sort, which would order the feed by\n * when things were read instead of when they arrived. Absent only on\n * notifications written before the field existed, which\n * `tools/scripts/backfill-notification-read.mjs` stamps.\n */\n read?: boolean\n}\n\nexport const NOTIFICATION_TYPE_LABELS: Record<AglynNotificationType, string> = {\n 'billing.invoice': 'Invoice available',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Usage threshold',\n 'team.invite': 'Team invite',\n 'team.roleChanged': 'Role changed',\n 'team.hostAccessGranted': 'Site access granted',\n 'content.formSubmission': 'Form submission',\n 'content.booking': 'New booking',\n 'content.order': 'New order',\n 'content.lowStock': 'Low stock',\n 'content.taskAssigned': 'Task assigned to you',\n 'content.taskReminder': 'Task reminder',\n 'content.contactAssigned': 'Contact assigned to you',\n 'content.leadAssigned': 'Lead assigned to you',\n 'content.crmDailyDigest': 'Daily CRM digest',\n 'content.insightsDigest': 'Weekly insights',\n 'marketplace.review': 'Listing review',\n\n 'support.ticketOpened': 'New support ticket',\n 'support.ticketReply': 'Support ticket reply',\n 'system.announcement': 'Announcement',\n 'system.pluginVerifierRegression': 'Plugin verifier regression',\n 'system.signInMethodRemoved': 'Sign-in method removed',\n 'system.scopeDrift': 'Resources missing a sharing scope',\n 'system.ssoDomainUnverified': 'SSO domain no longer proves ownership',\n 'system.formSubmissionsPaused': 'Form submissions paused',\n 'system.visitorRecordsPaused': 'Sign-ups or leads paused',\n 'system.abuseReportUrgent': 'Urgent abuse report',\n 'system.riskNotice': 'Held, flagged or locked on your workspace',\n 'system.dmcaCounterNotice': 'DMCA counter-notice',\n 'system.bandwidthCeilingTripped': 'Bandwidth ceiling reached',\n 'system.bandwidthCapEngaged': 'Monthly traffic limit reached',\n 'system.billingWebhookHalfApplied': 'Billing webhook half applied',\n 'system.disputeUnattributed': 'Card dispute with no owner',\n 'staff.userSignedUp': 'New account',\n 'staff.orgCreated': 'New workspace',\n 'staff.subscriptionStarted': 'New subscription',\n 'staff.subscriptionCanceled': 'Subscription canceled',\n 'staff.planChanged': 'Plan changed',\n 'staff.paymentFailed': 'Payment failed (workspace)',\n}\n\n/** Preference buckets (AGL-267): the prefix before the dot. */\nexport type NotificationCategory =\n | 'billing'\n | 'team'\n | 'content'\n | 'marketplace'\n | 'support'\n | 'system'\n // Staff-only, and shown only to staff (AGL-3225) — see\n // {@link STAFF_NOTIFICATION_CATEGORIES}.\n | 'staff'\n\nexport const NOTIFICATION_CATEGORY_LABELS: Record<\n NotificationCategory,\n string\n> = {\n billing: 'Billing',\n team: 'Team & access',\n content: 'Forms & bookings',\n marketplace: 'Marketplace',\n support: 'Support',\n system: 'Product & system',\n staff: 'Platform growth',\n}\n\n/**\n * The categories only staff can receive (AGL-3225).\n *\n * The settings page hides these rows from everybody else, because a switch\n * for mail that can never arrive is a promise the product does not keep. It\n * is presentation only: `notifyStaff` is what decides the audience, and it\n * enumerates the `staff` claim rather than reading this.\n */\nexport const STAFF_NOTIFICATION_CATEGORIES: ReadonlySet<NotificationCategory> =\n new Set<NotificationCategory>(['staff'])\n\n/**\n * What each category actually covers, in the reader's words (AGL-3251).\n *\n * The settings page listed seven bare labels and two switches, so deciding\n * whether to silence `Product & system` meant guessing what was in it. The\n * type labels beneath each row now name the contents exactly; this is the\n * one-line answer for somebody who does not want to expand anything.\n *\n * Written as what ARRIVES rather than as what the bucket is called: \"someone\n * joins, a role changes\" is checkable against your own feed in a way that\n * \"team and access events\" is not. Exhaustive `Record`, like the channel\n * defaults below — a new category cannot ship without somebody saying in\n * plain words what lands in it.\n */\nexport const NOTIFICATION_CATEGORY_DESCRIPTIONS: Record<\n NotificationCategory,\n string\n> = {\n billing:\n 'Invoices, failed payments, cancellations, and usage that crosses a plan limit.',\n team: 'Somebody joins or leaves, a role changes, or a site is shared with you.',\n content:\n 'Work arriving on your sites: form submissions, bookings, orders, low stock, and the tasks and leads assigned to you.',\n marketplace: 'Decisions on plugin listings you submitted for review.',\n support: 'New support tickets and replies on tickets you are following.',\n system:\n 'Announcements, and the faults the platform finds in your account: sign-in methods removed, traffic limits reached, billing or sharing left in a broken state.',\n staff:\n 'New accounts, new workspaces, and money moving — subscriptions starting, changing, failing and ending — across the whole platform. Only staff receive these.',\n}\n\nexport function notificationCategory(\n type: AglynNotificationType | string,\n): NotificationCategory {\n const prefix = String(type).split('.')[0]\n return (\n [\n 'billing',\n 'team',\n 'content',\n 'marketplace',\n 'support',\n 'system',\n 'staff',\n ].includes(prefix)\n ? prefix\n : 'system'\n ) as NotificationCategory\n}\n\n/**\n * Per-user mute map stored at `users/{uid}.notificationPrefs`\n * (`{ [category]: false }` mutes); absent categories stay on.\n */\nexport function notificationMuted(\n prefs: Record<string, boolean> | null | undefined,\n type: AglynNotificationType | string,\n): boolean {\n return prefs?.[notificationCategory(type)] === false\n}\n\n/**\n * The field on `users/{uid}` that holds a person's digest switches\n * (AGL-2619): `{ crmDaily: false }` turns the daily CRM digest off, and an\n * absent key leaves it on. Its own map rather than a key in\n * `notificationPrefs`, because that map is keyed by CATEGORY and read by\n * {@link notificationMuted} — a digest is a schedule a person keeps or\n * drops, not a bucket of types, and one switch governs both the console\n * notification and the email it travels with.\n */\nexport const DIGEST_PREFS_FIELD = 'digestPrefs'\n\n/**\n * The key the daily CRM digest keeps inside {@link DIGEST_PREFS_FIELD}.\n *\n * Exported so the console writes the switch through a name rather than a\n * second copy of the string (AGL-3230). The reader below and the page that\n * flips it were spelling the same literal in two files, which is how a\n * preference comes to be written under one key and read under another — and\n * it kept the plugin's vocabulary in a console page, where\n * `check:plugin-domain-in-core` rightly refuses it.\n */\nexport const CRM_DAILY_DIGEST_KEY = 'crmDaily'\n\nexport function crmDailyDigestEnabled(\n prefs: Record<string, boolean> | null | undefined,\n): boolean {\n return prefs?.[CRM_DAILY_DIGEST_KEY] !== false\n}\n\n/**\n * The field on `users/{uid}` naming the workspaces whose weekly insights a\n * person asked for (AGL-2915): `{ [orgId]: true }`. OPT-IN, unlike the CRM\n * digest — an absent key is off — because a weekly insight is generated, and a\n * generation spends the workspace's credits. The person turns it on beside the\n * answers themselves, where the plan, the release and their permission have\n * already been checked, and off again there or in Notifications; the weekly\n * sweep checks all three again before it spends anything.\n */\nexport const INSIGHT_DIGESTS_FIELD = 'insightDigests'\n\n/** Whether a person asked for a workspace's weekly insights. */\nexport function insightDigestSubscribed(\n value: Record<string, boolean> | null | undefined,\n orgId: string,\n): boolean {\n return Boolean(orgId) && value?.[orgId] === true\n}\n\n/**\n * The channels a notification can travel on (AGL-3223).\n *\n * `console` is the feed at `/manage/notifications` and the app-bar dropdown\n * that reads it — the only channel that existed. `email` is the message the\n * fan-out sends beside that doc when the recipient asked for one.\n */\nexport type NotificationChannel = 'console' | 'email'\n\n/**\n * One scope's answer for one category. **Tri-state on purpose**: `true` and\n * `false` decide, and an ABSENT key inherits from the scope above.\n *\n * Inheritance is the whole reason this is a partial rather than a pair of\n * booleans. A person who wants form submissions from one busy site and not\n * from the other five has to be able to say that about the one site without\n * restating their answer for every other category at every other scope — and\n * a two-valued leaf cannot express \"I have not said\", so every override would\n * have to be written out in full and would then stop tracking the account\n * default it was never meant to detach from.\n */\nexport interface NotificationChannelPrefs {\n console?: boolean\n email?: boolean\n}\n\nexport type NotificationCategoryPrefs = Partial<\n Record<NotificationCategory, NotificationChannelPrefs>\n>\n\n/**\n * One scope's answer for a single notification TYPE (AGL-3251), tri-state on\n * the same terms as {@link NotificationChannelPrefs}: an absent key falls\n * through to the category.\n *\n * Its own map rather than extra keys in {@link NotificationCategoryPrefs},\n * because that one is an exhaustive record keyed by category and a type key\n * inside it would type-check only by widening the thing that makes a missing\n * category a compile error.\n */\nexport type NotificationTypePrefs = Partial<\n Record<AglynNotificationType, NotificationChannelPrefs>\n>\n\n/**\n * Per-scope, per-channel notification preferences (AGL-3223), stored at\n * `users/{uid}.notificationSettings`.\n *\n * Three layers, narrowest first when resolving: the SITE a notification\n * concerns, then the WORKSPACE, then the account. Anything none of them\n * answers falls to {@link NOTIFICATION_CHANNEL_DEFAULTS}.\n *\n * ON THE USER DOCUMENT, not on `orgs/{orgId}/members/{uid}`, and that is a\n * cost decision rather than a modelling preference. `notifyUsers` already\n * does exactly one `getAll` over the recipients' user docs to read their\n * category mutes, so every layer living here means per-site preferences are\n * read for free on the fan-out's hot path. The member row would add a read\n * per recipient per notification to answer a question the document already in\n * hand could have answered.\n */\nexport interface NotificationSettings {\n account?: NotificationCategoryPrefs\n /**\n * Per-TYPE answers at the account scope (AGL-3251), consulted before\n * {@link NotificationSettings.account}'s category answer and never above a\n * narrower scope — see {@link notificationChannelEnabled}.\n *\n * ACCOUNT ONLY, deliberately. The per-workspace and per-site card is\n * already seven categories by three states by two channels, and a type row\n * for each of the ~thirty types, per workspace AND per site, is a page\n * nobody can read — which is the complaint this whole issue started as.\n * The account scope is where \"stop telling me about THIS\" belongs anyway:\n * it is a statement about the kind of thing, and kinds do not vary by site.\n */\n accountTypes?: NotificationTypePrefs\n /** Keyed by org id. */\n orgs?: Record<string, NotificationCategoryPrefs>\n /** Keyed by host id — a site's own answer, narrower than its workspace's. */\n hosts?: Record<string, NotificationCategoryPrefs>\n /**\n * Per-TYPE answers at the workspace and site scopes (AGL-3267), beside the\n * category maps above rather than nested inside them.\n *\n * Parallel maps because the category maps are already stored under `orgs`\n * and `hosts` on live user documents: folding both into one\n * `{ categories, types }` object per scope would be a migration of every\n * preference anybody has set, to express something two more keys express\n * without touching a byte of what exists.\n *\n * This supersedes the account-only limit AGL-3251 shipped under. That was\n * the right call for a card nobody had used yet and the wrong one once it\n * existed: \"quiet this one type down on this one busy site\" is the question\n * the scope card is FOR, and answering it only for whole categories made\n * the fine grain stop exactly where the noise is worst.\n */\n orgTypes?: Record<string, NotificationTypePrefs>\n hostTypes?: Record<string, NotificationTypePrefs>\n}\n\nexport const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings'\n\n/**\n * What a category does when nobody has said otherwise.\n *\n * Console on, email OFF, everywhere. Email defaults off because the inbox is\n * not ours to fill: the product already sends transactional mail nobody opted\n * into — welcome, verification, invites, dunning, usage alerts — and every one\n * of those leaves on the same domain a customer's password reset depends on.\n * Turning a busy site's form submissions into mail by default would put that\n * domain's reputation behind traffic the recipient never asked for.\n *\n * Exhaustive `Record` deliberately: a new {@link NotificationCategory} is a\n * compile error here until somebody decides what it does by default, which is\n * the one question a new category must not be able to ship without answering.\n */\nexport const NOTIFICATION_CHANNEL_DEFAULTS: Record<\n NotificationCategory,\n Record<NotificationChannel, boolean>\n> = {\n billing: { console: true, email: false },\n team: { console: true, email: false },\n content: { console: true, email: false },\n marketplace: { console: true, email: false },\n support: { console: true, email: false },\n system: { console: true, email: false },\n // Console ON, because the complaint this answers is that staff never heard\n // about a sign-up at all; email off, like everything else, because that is\n // what the channel defaults to and a sign-up is not urgent enough to be the\n // exception that starts filling inboxes by default.\n staff: { console: true, email: false },\n}\n\n/**\n * The types that send their OWN email and must never be mailed again by the\n * generic channel (AGL-3224).\n *\n * Both digests compose a message the fan-out could not reproduce — a day's\n * owed tasks, a week's figures — and send it from their own route under their\n * own switch (`digestPrefs.crmDaily`, `insightDigests.{orgId}`). A recipient\n * who switches the `content` email channel on would otherwise receive the\n * digest twice: once as the digest, once as a one-line \"Daily CRM digest\"\n * notification saying that the digest happened.\n */\nexport const NOTIFICATION_SELF_SENT_EMAIL_TYPES: ReadonlySet<string> =\n new Set<AglynNotificationType>([\n 'content.crmDailyDigest',\n 'content.insightsDigest',\n // Emailed by `notifyRiskEvent` itself, as account mail (AGL-3368).\n 'system.riskNotice',\n ])\n\n/**\n * Staff notifications the OPERATOR must hear about by email, whoever runs the\n * install and whatever anyone switched on (AGL-3375): fraud and risk alerts,\n * a card dispute nobody owns, a DMCA counter-notice whose statutory clock is\n * running, and a billing webhook that applied only half of what it meant to.\n *\n * The console notification is still written for every staff member. What\n * this adds is one email to the operator's alert inbox, because the email\n * channel defaults OFF and a self-hosted or OSS install that nobody tuned\n * would otherwise learn about card testing on its checkout from its bank.\n */\nexport const OPERATOR_ALERT_NOTIFICATION_TYPES: ReadonlySet<string> =\n new Set<AglynNotificationType>([\n 'system.abuseReportUrgent',\n 'system.disputeUnattributed',\n 'system.dmcaCounterNotice',\n 'system.billingWebhookHalfApplied',\n ])\n\n/**\n * Whether a channel is on for one notification, at its own scope.\n *\n * Resolution order, first answer wins: the notification's SITE, its\n * WORKSPACE, the account, then {@link NOTIFICATION_CHANNEL_DEFAULTS}. A scope\n * that holds no entry for the category, or an entry with the channel key\n * absent, does not answer — see {@link NotificationChannelPrefs}.\n *\n * `legacyPrefs` is the flat `notificationPrefs` mute map this replaces\n * (AGL-267), and it sits BELOW the account layer rather than beside it.\n * Nothing migrates it: a person who never opens the new settings page keeps\n * being governed by the mutes they set years ago, and the first thing they do\n * set on the account layer overrides the old map for that category without\n * disturbing the rest of it. It answers for `console` only, because the map\n * predates there being a second channel and reading a console mute as an\n * email preference would be inventing an answer its author never gave.\n */\nexport function notificationChannelEnabled(\n settings: NotificationSettings | null | undefined,\n channel: NotificationChannel,\n type: AglynNotificationType | string,\n scope?: { orgId?: string | null; hostId?: string | null },\n legacyPrefs?: Record<string, boolean> | null,\n): boolean {\n const category = notificationCategory(type)\n /*\n * ⛔ A STAFF NOTIFICATION HAS NO SCOPE TO BE NARROWED BY (AGL-3267).\n *\n * It is about the platform, and the workspace one MENTIONS is its subject,\n * not its audience: the staff member reading \"Acme Co subscribed\" is\n * almost never a member of Acme Co, and if they happen to be, their\n * preferences for their own membership have nothing to do with it.\n *\n * This was already true by accident — no staff emitter passes `orgId` or\n * `hostId`, so the scope layers never matched — which made every\n * \"Platform growth\" row in the per-workspace card a control that could be\n * set and could never do anything. Stating it here rather than only hiding\n * those rows is the difference between the model being right and the UI\n * covering for a model that is wrong: a `staff.*` type that ever does\n * start carrying an `orgId`, for its link or its subject line, must not\n * silently become mutable per workspace.\n */\n const staffWide = STAFF_NOTIFICATION_CATEGORIES.has(category)\n /*\n * Narrowest scope first, and within each scope the TYPE before its\n * CATEGORY (AGL-3251, widened to every scope by AGL-3267).\n *\n * Both halves matter and they answer different questions. Scope order is\n * \"where is this from\" — a site's answer beats its workspace's, which beats\n * the account's, because quietening one busy site is the thing the scope\n * card exists for. Type-before-category is \"what kind of thing is this\" —\n * somebody who switched `Payment failed` off said something about that\n * type, and it must beat their own broader `Billing` answer at the SAME\n * scope without leaking upward past a narrower one.\n */\n const layers: Array<NotificationChannelPrefs | undefined> = staffWide\n ? [\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n : [\n scope?.hostId\n ? settings?.hostTypes?.[scope.hostId]?.[type as AglynNotificationType]\n : undefined,\n scope?.hostId ? settings?.hosts?.[scope.hostId]?.[category] : undefined,\n scope?.orgId\n ? settings?.orgTypes?.[scope.orgId]?.[type as AglynNotificationType]\n : undefined,\n scope?.orgId ? settings?.orgs?.[scope.orgId]?.[category] : undefined,\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n for (const layer of layers) {\n const answer = layer?.[channel]\n if (typeof answer === 'boolean') return answer\n }\n if (channel === 'console' && notificationMuted(legacyPrefs, type))\n return false\n return NOTIFICATION_CHANNEL_DEFAULTS[category][channel]\n}\n\n/**\n * What one scope says, with no inheritance applied — what the settings page\n * renders as Inherit / On / Off, and `undefined` is Inherit.\n *\n * `scope` names the layer directly rather than being derived from a\n * notification, because the page edits a layer whether or not anything has\n * ever arrived from it.\n */\n/**\n * What the account scope says about one TYPE, with no inheritance applied\n * (AGL-3251) — `undefined` means the row follows its category.\n *\n * The page needs the unresolved answer to draw the difference between \"on\n * because Billing is on\" and \"on because you said so\": only the second can be\n * reset, and a switch that cannot show which one it is leaves a person unable\n * to get back to following the category.\n */\nexport function notificationAccountTypePref(\n settings: NotificationSettings | null | undefined,\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n return settings?.accountTypes?.[type as AglynNotificationType]?.[channel]\n}\n\n/**\n * Every type in a category, in the order the labels declare them\n * (AGL-3251) — what the settings page expands a category row into.\n *\n * Derived from {@link NOTIFICATION_TYPE_LABELS} rather than held as a second\n * map, so a type added there appears under its category without anybody\n * remembering to list it twice.\n */\nexport function notificationTypesInCategory(\n category: NotificationCategory,\n): AglynNotificationType[] {\n return (\n Object.keys(NOTIFICATION_TYPE_LABELS) as AglynNotificationType[]\n ).filter((type) => notificationCategory(type) === category)\n}\n\n/**\n * What ONE scope says about ONE type, with no inheritance applied\n * (AGL-3267) — `undefined` means the row follows its category at that scope.\n *\n * The scope-aware sibling of {@link notificationAccountTypePref}, which stays\n * as the account-only shorthand its callers already use.\n */\nexport function notificationScopeTypePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.accountTypes\n : scope.kind === 'org'\n ? settings?.orgTypes?.[scope.id]\n : settings?.hostTypes?.[scope.id]\n return layer?.[type as AglynNotificationType]?.[channel]\n}\n\nexport function notificationScopePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n category: NotificationCategory,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.account\n : scope.kind === 'org'\n ? settings?.orgs?.[scope.id]\n : settings?.hosts?.[scope.id]\n return layer?.[category]?.[channel]\n}\n\n/**\n * The scopes this person has said something different about — what the\n * settings page lists so an override is never somewhere you have to go\n * looking for.\n *\n * Returns ids, not names: the page holds the org and host rosters and this\n * module holds no lookups. An id with no name is still worth listing, because\n * a preference about a workspace somebody left is exactly the kind of\n * leftover that is invisible until it is listed.\n */\nexport function notificationOverriddenScopes(\n settings: NotificationSettings | null | undefined,\n): { orgIds: string[]; hostIds: string[] } {\n /*\n * BOTH maps for a scope, categories and types (AGL-3267).\n *\n * Reading only the category map would make a scope whose ONLY answer is a\n * per-type one invisible here — and this list is the single place a person\n * can find an override they set months ago. Silencing one type on one busy\n * site and then being unable to find where you did it is precisely the\n * failure this function exists to prevent.\n */\n const answered = (prefs: Record<string, NotificationChannelPrefs> | undefined) =>\n Object.values(prefs ?? {}).some((channels) =>\n Object.values(channels ?? {}).some((value) => typeof value === 'boolean'),\n )\n const named = (\n categories: Record<string, NotificationCategoryPrefs> | undefined,\n types: Record<string, NotificationTypePrefs> | undefined,\n ) =>\n [\n ...new Set([\n ...Object.keys(categories ?? {}),\n ...Object.keys(types ?? {}),\n ]),\n ]\n .filter(\n (id) =>\n answered(categories?.[id] as Record<string, NotificationChannelPrefs>) ||\n answered(types?.[id] as Record<string, NotificationChannelPrefs>),\n )\n .sort()\n return {\n orgIds: named(settings?.orgs, settings?.orgTypes),\n hostIds: named(settings?.hosts, settings?.hostTypes),\n }\n}\n\n/**\n * Rewrites a stored notification link onto the current URL scheme (AGL-644).\n *\n * A notification's `link` is frozen at write time — `notifyUsers` persists\n * whatever string the emitter passed and never normalizes it. So every\n * notification written before the org-slug migration (AGL-621) and the\n * subdomain migration (AGL-622) still points at a route that no longer\n * exists, and fixing the emitters alone would leave that whole backlog dead.\n * Normalizing when the link is FOLLOWED repairs old and new alike, and keeps\n * working for emitters that haven't been migrated yet.\n *\n * Rewrites, in order:\n * - `/{hostDocId}` or `/{hostDocId}/rest` → `/{orgSlug}/hosts/{subdomain}/rest`\n * - `/org` or `/org/rest` → `/{orgSlug}/rest`\n * - `/hosts` (exactly) → `/{orgSlug}/hosts`\n *\n * Anything already canonical, user-scoped (`/manage/...`), staff (`/admin/...`)\n * or absolute is returned untouched. Every rewrite is gated on having the\n * context it needs, so an unresolvable link degrades to its stored value\n * rather than to a wrong destination.\n *\n * The host rewrite is keyed on the notification's own `hostId` rather than\n * guessing from the path shape, so it can never mistake a real first segment\n * for a doc id.\n *\n * The email copy of a notification goes through it too (AGL-3367): a button\n * in an inbox is a followed link with no console around it to repair it.\n */\nexport function normalizeNotificationLink(\n link: string | undefined | null,\n context: {\n orgSlug?: string | null\n /** The notification's `hostId` (a Firestore doc id). */\n hostId?: string | null\n /** That host's subdomain, which the current routes are keyed by. */\n hostSubdomain?: string | null\n },\n): string | undefined {\n if (!link) return undefined\n // Absolute URLs (staff broadcasts can carry them) are not ours to rewrite.\n if (!link.startsWith('/')) return link\n\n const { orgSlug, hostId, hostSubdomain } = context\n\n if (orgSlug && hostId && hostSubdomain) {\n const prefix = `/${hostId}`\n if (link === prefix || link.startsWith(`${prefix}/`)) {\n return `${buildRoute(Route.HOST_DASHBOARD, {\n orgSlug,\n host: hostSubdomain,\n })}${link.slice(prefix.length)}`\n }\n }\n\n if (orgSlug) {\n if (link === '/org' || link.startsWith('/org/')) {\n return `${buildRoute(Route.ORG_HOME, { orgSlug })}${link.slice(\n '/org'.length,\n )}`\n }\n // Only the bare list — `/hosts/{docId}` would still need a subdomain, and\n // guessing one is worse than leaving the link alone.\n if (link === '/hosts') return buildRoute(Route.HOST_LIST, { orgSlug })\n }\n\n return link\n}\n"],"names":["buildRoute","Route","NOTIFICATION_TYPE_LABELS","NOTIFICATION_CATEGORY_LABELS","billing","team","content","marketplace","support","system","staff","STAFF_NOTIFICATION_CATEGORIES","Set","NOTIFICATION_CATEGORY_DESCRIPTIONS","notificationCategory","type","prefix","String","split","includes","notificationMuted","prefs","DIGEST_PREFS_FIELD","CRM_DAILY_DIGEST_KEY","crmDailyDigestEnabled","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","value","orgId","Boolean","NOTIFICATION_SETTINGS_FIELD","NOTIFICATION_CHANNEL_DEFAULTS","console","email","NOTIFICATION_SELF_SENT_EMAIL_TYPES","OPERATOR_ALERT_NOTIFICATION_TYPES","notificationChannelEnabled","settings","channel","scope","legacyPrefs","category","staffWide","has","layers","accountTypes","account","hostId","hostTypes","undefined","hosts","orgTypes","orgs","layer","answer","notificationAccountTypePref","notificationTypesInCategory","Object","keys","filter","notificationScopeTypePref","kind","id","notificationScopePref","notificationOverriddenScopes","answered","values","some","channels","named","categories","types","sort","orgIds","hostIds","normalizeNotificationLink","link","context","startsWith","orgSlug","hostSubdomain","HOST_DASHBOARD","host","slice","length","ORG_HOME","HOST_LIST"],"mappings":"AAAA;;;;;;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C;IAED,IAAI,CAACD,MAAM,OAAO3B;IAClB,2EAA2E;IAC3E,IAAI,CAAC2B,KAAKE,UAAU,CAAC,MAAM,OAAOF;IAElC,MAAM,EAAEG,OAAO,EAAEhC,MAAM,EAAEiC,aAAa,EAAE,GAAGH;IAE3C,IAAIE,WAAWhC,UAAUiC,eAAe;QACtC,MAAMhE,SAAS,CAAC,CAAC,EAAE+B,QAAQ;QAC3B,IAAI6B,SAAS5D,UAAU4D,KAAKE,UAAU,CAAC,GAAG9D,OAAO,CAAC,CAAC,GAAG;YACpD,OAAO,GAAGhB,WAAWC,MAAMgF,cAAc,EAAE;gBACzCF;gBACAG,MAAMF;YACR,KAAKJ,KAAKO,KAAK,CAACnE,OAAOoE,MAAM,GAAG;QAClC;IACF;IAEA,IAAIL,SAAS;QACX,IAAIH,SAAS,UAAUA,KAAKE,UAAU,CAAC,UAAU;YAC/C,OAAO,GAAG9E,WAAWC,MAAMoF,QAAQ,EAAE;gBAAEN;YAAQ,KAAKH,KAAKO,KAAK,CAC5D,OAAOC,MAAM,GACZ;QACL;QACA,0EAA0E;QAC1E,qDAAqD;QACrD,IAAIR,SAAS,UAAU,OAAO5E,WAAWC,MAAMqF,SAAS,EAAE;YAAEP;QAAQ;IACtE;IAEA,OAAOH;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/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 type { ITimestamp } from '@aglyn/shared-util-timestamp'\nimport { buildRoute, Route } from './console-routes'\n\n/**\n * In-app notifications (AGL-259): per-user docs at\n * `users/{uid}/notifications/{id}`, written by the Admin SDK (emitters in\n * the API routes + the `notifyAdmins` automation step) and read/marked by\n * their owner. Types follow the common SaaS taxonomy so the console can\n * icon/group them without a registry.\n */\nexport type AglynNotificationType =\n | 'billing.invoice'\n | 'billing.paymentFailed'\n // Stripe gave up on a failed renewal and CANCELLED the subscription\n // (AGL-1877). Distinct from `paymentFailed`, which announces one failed\n // attempt inside a retry window the customer can still recover from; this\n // one is the window having closed. Measured on the test account with a\n // test clock: five attempts over 21.08 days, then\n // `cancellation_details.reason: 'payment_failed'` — and until this existed\n // the org went silently to Free at that moment, with the `past_due` banner\n // disappearing at exactly the instant the consequence arrived.\n | 'billing.subscriptionCanceled'\n | 'billing.usage'\n | 'team.invite'\n | 'team.roleChanged'\n | 'team.hostAccessGranted'\n | 'content.formSubmission'\n | 'content.booking'\n | 'content.order'\n | 'content.lowStock'\n // A CRM task was assigned to the recipient by somebody else (AGL-2599).\n // `content.` because it is the same kind of message as a form submission\n // or a booking: a thing on the site that now needs this person's hands,\n // not a change to their standing (`team.`) and not a platform notice\n // (`system.`). Someone who has muted the operational stream has said they\n // do not want to be told about work as it arrives, and a task is work.\n | 'content.taskAssigned'\n // A CRM task's reminder came due (AGL-2659): the hourly runner telling\n // the assignee, at the task's own time, that the task is due. `content.`\n // beside `taskAssigned` for the same reason it gives — work on the site,\n // not standing — and so the one mute that stops \"work arriving\" stops\n // \"work falling due\" with it. The mute governs the whole reminder, mail\n // included, unlike the digest's: a reminder is one message about one\n // task, and there is no schedule to keep separately from it.\n | 'content.taskReminder'\n // A contact, or a lead, became the recipient's to work (AGL-2618): a\n // capture the assignment rules or the site's default owner routed to\n // them, a lead somebody converted and handed to them, or an automation's\n // \"assign an owner\" step — every server path that writes `ownerUid`\n // except the recipient assigning themselves. Two types rather than one\n // because the record the person opens differs: a lead is the site's own\n // working record and a contact is the org's, and the link goes to the\n // one they will actually work. `content.`, beside `taskAssigned`, for the\n // same reason: work arriving, not standing changing.\n | 'content.contactAssigned'\n | 'content.leadAssigned'\n // The morning's CRM digest (AGL-2619): what the recipient owes today —\n // overdue and due-today tasks, and the leads nobody has worked. `content.`\n // for the reason `taskAssigned` is: it is about work on the site, and the\n // person who muted the operational stream has asked not to be told about\n // work. The digest EMAIL is governed separately, by\n // `crmDailyDigestEnabled`: the mute is a fact about the console feed and\n // the digest switch is a fact about the digest.\n | 'content.crmDailyDigest'\n // The weekly insights (AGL-2915): what a site's figures showed that week,\n // for a person who asked for them. `content.` beside the CRM digest, for the\n // reason that one gives: it is about the site's work, and the operational\n // mute governs the console notification while the person's own switch for\n // the digest governs the digest.\n | 'content.insightsDigest'\n // Marketplace review verdicts (AGL-432/653).\n | 'marketplace.review'\n // Support desk, staff audience (AGL-850): a subscriber opened or replied to\n // a ticket. Fanned out to staff-claim holders, not org members.\n | 'support.ticketOpened'\n | 'support.ticketReply'\n | 'system.announcement'\n // A live plugin version stopped passing the static verifier (AGL-1086).\n // Staff audience: bytes we told workspaces were checked now fail checks\n // that did not exist when they were approved.\n //\n // Deliberately NOT under `marketplace.` (AGL-1088). Category is the prefix,\n // categories are mutable per user, and Marketplace is the category a staff\n // member mutes to stop routine listing-review chatter — which would drop\n // this alert as collateral. `system` is the bucket nobody mutes to reduce\n // noise. The adminAudit record survives a mute either way; the timeliness\n // does not, and timeliness is the whole point of the alert.\n | 'system.pluginVerifierRegression'\n // A sign-in method was removed from the user's own account because their\n // organization turned on SSO enforcement (AGL-1129). `system.`, not\n // `team.`, for the AGL-1088 reason above: `team` is the category someone\n // mutes to stop routine roster chatter, and \"the way you sign in just\n // changed\" is not chatter — the next sign-in fails without it.\n | 'system.signInMethodRemoved'\n // Documents in a scoped collection carrying no `visibleTo` (AGL-1478).\n // Staff audience: the weekly dry run found resources that are invisible\n // to every site-scoped read, which always means a creation path forgot\n // the field. `system.` for the AGL-1088 reason above, and because the\n // collection it names may be `marketplace`-adjacent or not.\n | 'system.scopeDrift'\n // An SSO domain that WAS DNS-proven has stopped answering with our\n // challenge record, for three consecutive weekly sweeps (AGL-1210).\n // Nothing has been turned off — sign-in for that domain still routes\n // exactly as it did — and that is precisely why this has to be said out\n // loud rather than left in a log.\n //\n // `system.`, not `team.`, for the AGL-1088 reason above and one of its\n // own: the audience is the org's own admins, the subject is whether their\n // people can still sign in, and it must reach them BEFORE anybody decides\n // to revoke the routing. A category somebody mutes to quieten roster\n // chatter is the wrong place for the one warning that precedes a lockout.\n | 'system.ssoDomainUnverified'\n // A site hit the per-month form-submission abuse ceiling and further\n // submissions are being refused (AGL-1655). `system.`, not `content.`, for\n // the AGL-1088 reason above and more sharply than any of them: `content` is\n // literally the category a site owner mutes to stop routine form-submission\n // chatter, and this is the one form notification that says the form has\n // STOPPED accepting. Filing it under the muted bucket would guarantee it\n // reaches nobody on exactly the sites busy enough to trip it.\n | 'system.formSubmissionsPaused'\n // A site reached the flat platform ceiling on member accounts or on lead\n // records, so further ones are being refused (AGL-1529). `system.` for the\n // same reason as `formSubmissionsPaused` directly above, and with the same\n // sharpness: `content.` is the bucket an owner mutes to stop routine\n // sign-up and lead chatter, and this is the one notification saying the\n // sign-ups have STOPPED — muted exactly on the sites busy enough to trip it.\n | 'system.visitorRecordsPaused'\n // An outsider reported one of our sites for phishing, malware or CSAM\n // (AGL-1964). `system` for the AGL-1088 reason and, again, more sharply\n // than most: this notification goes to STAFF, not to a customer, and its\n // subject is somebody else's site. There is no bucket a recipient could\n // mute it into that would be honest — nobody has opted into being told a\n // stranger is being phished through our platform, and nobody should be able\n // to opt out of it either.\n //\n // Only the urgent categories raise one, and only on a first report. See the\n // fan-out in apps/tenant/app/api/report-abuse/route.ts for why: a flood of\n // alerts IS the flood, and the alert it would cost us is the phishing one.\n | 'system.abuseReportUrgent'\n // Something on the recipient's OWN workspace was held, flagged, locked or\n // paused (AGL-3368): an email or page held for review, a flagged domain,\n // a fraud signal on a payment, a lock and its lift. Written by\n // `notifyRiskEvent` from the risk notice catalog, which says what happened,\n // what it means and how to request a review. `system.` for the AGL-1088\n // reason: it is the one message saying the owner's work has STOPPED, and a\n // category muted to quieten routine chatter must not swallow it. It sends\n // its own email, transactional and preference-free, so it is also in\n // NOTIFICATION_SELF_SENT_EMAIL_TYPES.\n | 'system.riskNotice'\n // The §512(g) counter-notice (AGL-1983), and the one place the \"only urgent\n // categories raise a notification\" restraint above is deliberately not\n // applied. Every counter-notice carries a statutory deadline that is\n // ALREADY RUNNING when it arrives — the clock counts from the subscriber's\n // submission, not from our attention — so there is no low-value tail of\n // these to drown out the important ones, and the one that goes unread is a\n // customer locked out of their own work plus an unmet obligation under\n // §512(g)(2)(A). Raised on first submission only, like the one above, so a\n // resubmitting customer cannot re-alert.\n | 'system.dmcaCounterNotice'\n // A site crossed the per-month bandwidth abuse ceiling (AGL-2155). Two\n // audiences share one type: staff, because an uncompensated free site\n // serving six figures of page views is an incident; and the site's own\n // managers, because on free the site is now serving a capped notice and\n // nobody should learn that from a visitor.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this meter: on the free plan there is no bill, so `billing` would be the\n // one category where the message is literally never about money — and it is\n // exactly the free-tier trip that changes what visitors see.\n | 'system.bandwidthCeilingTripped'\n // A free site crossed its PLAN's included bandwidth and is now serving the\n // capped notice (AGL-2413). Distinct from the ceiling above on purpose: that\n // one is an incident at 10x the band and goes to staff first; this one is an\n // ordinary quota at 1x, concerns only the site's own managers, and its\n // remedy is an upgrade rather than an investigation. Sending both under one\n // type would tell an owner their traffic was being treated as suspected\n // abuse when it is simply a successful free site.\n | 'system.bandwidthCapEngaged'\n // A Stripe billing webhook threw AFTER its handlers had begun (AGL-2157),\n // so its side effects may be half applied and its idempotency claim is\n // being HELD — Stripe will not retry it. Staff audience: this is the one\n // failure on that route no automatic retry can make safe, because the\n // handlers behind it are not all idempotent, and a human has to reconcile.\n | 'system.billingWebhookHalfApplied'\n // A card dispute arrived that NOTHING in the platform claimed (AGL-2429):\n // no `platformRevenue` row, no storefront order, no marketplace purchase.\n // Staff audience, and the reason it needs a type of its own is that its\n // absence was the bug — the routine case (a storefront or marketplace\n // chargeback, which the plugins own) and the fault case were the same\n // silence from the route's side, so a dispute nobody handled looked\n // exactly like one somebody did.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this alert: `billing` is the category a recipient is most likely to have\n // muted as routine invoice traffic, and this is the one message on that\n // route where muting it means money moves with nobody looking.\n | 'system.disputeUnattributed'\n // An operator alert from the registry in `./operator-alerts` (AGL-3377)\n // that has no notification type of its own: a lost dispute, a failed\n // erasure, a degraded health check. One type for all of them because the\n // registry, not the taxonomy, is what names the alert; the title and body\n // say which one it is. `system.` for the AGL-1088 reason above: these are\n // the faults nobody may mute away as routine chatter.\n | 'system.operatorAlert'\n // Somebody created an account, and somebody created a workspace\n // (AGL-3225). Staff audience, and the only two types in the taxonomy whose\n // subject is the platform's own growth rather than anybody's work.\n //\n // `staff.`, and NOT `system.`, and the AGL-1088 note above is the reason\n // rather than an exception to it: `system` is the bucket nobody mutes to\n // reduce noise, which is exactly what makes it the wrong home for the two\n // routine, high-volume events in the product. A staff member must be able\n // to stop hearing about every sign-up without also dropping the verifier\n // regression and the unattributed dispute that share that bucket — and\n // before this category existed, there was nowhere to put them where that\n // was true.\n //\n // The category also tells the settings page who a row is for: `staff` is\n // rendered only to claim holders, so no customer is shown a switch for\n // notifications they could never receive.\n | 'staff.userSignedUp'\n | 'staff.orgCreated'\n // And when money moves (AGL-3267). The category was two signup types, so\n // the one thing a platform feed exists to report — revenue starting,\n // changing and stopping — was the one thing it did not.\n //\n // `staff.paymentFailed` is deliberately NOT the customer's\n // `billing.paymentFailed`: different audience, different action. The\n // customer is told to fix their card; staff are told a paying workspace is\n // about to stop paying.\n | 'staff.subscriptionStarted'\n | 'staff.subscriptionCanceled'\n | 'staff.planChanged'\n | 'staff.paymentFailed'\n\nexport interface AglynNotification {\n $id?: string\n type: AglynNotificationType\n title: string\n body?: string\n /** Console path the notification opens (e.g. a host inbox). */\n link?: string\n orgId?: string\n hostId?: string\n createdAt?: ITimestamp\n /** When the owner read it; absent or null while unread. */\n readAt?: ITimestamp | null\n /**\n * Whether the owner has read it — `false` on create, `true` beside\n * `readAt` when read (AGL-3321).\n *\n * A boolean rather than `readAt: null`, because the feed filters by it\n * under its newest-first cursor. Equality on a boolean answers BOTH\n * states (`read == false`, `read == true`) beneath `orderBy('createdAt')`\n * with one composite index. A nullable timestamp answers \"unread\" by\n * equality but \"read\" only as `readAt != null`, and Firestore requires an\n * inequality's field to be the FIRST sort, which would order the feed by\n * when things were read instead of when they arrived. Absent only on\n * notifications written before the field existed, which\n * `tools/scripts/backfill-notification-read.mjs` stamps.\n */\n read?: boolean\n}\n\nexport const NOTIFICATION_TYPE_LABELS: Record<AglynNotificationType, string> = {\n 'billing.invoice': 'Invoice available',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Usage threshold',\n 'team.invite': 'Team invite',\n 'team.roleChanged': 'Role changed',\n 'team.hostAccessGranted': 'Site access granted',\n 'content.formSubmission': 'Form submission',\n 'content.booking': 'New booking',\n 'content.order': 'New order',\n 'content.lowStock': 'Low stock',\n 'content.taskAssigned': 'Task assigned to you',\n 'content.taskReminder': 'Task reminder',\n 'content.contactAssigned': 'Contact assigned to you',\n 'content.leadAssigned': 'Lead assigned to you',\n 'content.crmDailyDigest': 'Daily CRM digest',\n 'content.insightsDigest': 'Weekly insights',\n 'marketplace.review': 'Listing review',\n\n 'support.ticketOpened': 'New support ticket',\n 'support.ticketReply': 'Support ticket reply',\n 'system.announcement': 'Announcement',\n 'system.pluginVerifierRegression': 'Plugin verifier regression',\n 'system.signInMethodRemoved': 'Sign-in method removed',\n 'system.scopeDrift': 'Resources missing a sharing scope',\n 'system.ssoDomainUnverified': 'SSO domain no longer proves ownership',\n 'system.formSubmissionsPaused': 'Form submissions paused',\n 'system.visitorRecordsPaused': 'Sign-ups or leads paused',\n 'system.abuseReportUrgent': 'Urgent abuse report',\n 'system.riskNotice': 'Held, flagged or locked on your workspace',\n 'system.dmcaCounterNotice': 'DMCA counter-notice',\n 'system.bandwidthCeilingTripped': 'Bandwidth ceiling reached',\n 'system.bandwidthCapEngaged': 'Monthly traffic limit reached',\n 'system.billingWebhookHalfApplied': 'Billing webhook half applied',\n 'system.disputeUnattributed': 'Card dispute with no owner',\n 'system.operatorAlert': 'Operator alert',\n 'staff.userSignedUp': 'New account',\n 'staff.orgCreated': 'New workspace',\n 'staff.subscriptionStarted': 'New subscription',\n 'staff.subscriptionCanceled': 'Subscription canceled',\n 'staff.planChanged': 'Plan changed',\n 'staff.paymentFailed': 'Payment failed (workspace)',\n}\n\n/** Preference buckets (AGL-267): the prefix before the dot. */\nexport type NotificationCategory =\n | 'billing'\n | 'team'\n | 'content'\n | 'marketplace'\n | 'support'\n | 'system'\n // Staff-only, and shown only to staff (AGL-3225) — see\n // {@link STAFF_NOTIFICATION_CATEGORIES}.\n | 'staff'\n\nexport const NOTIFICATION_CATEGORY_LABELS: Record<\n NotificationCategory,\n string\n> = {\n billing: 'Billing',\n team: 'Team & access',\n content: 'Forms & bookings',\n marketplace: 'Marketplace',\n support: 'Support',\n system: 'Product & system',\n staff: 'Platform growth',\n}\n\n/**\n * The categories only staff can receive (AGL-3225).\n *\n * The settings page hides these rows from everybody else, because a switch\n * for mail that can never arrive is a promise the product does not keep. It\n * is presentation only: `notifyStaff` is what decides the audience, and it\n * enumerates the `staff` claim rather than reading this.\n */\nexport const STAFF_NOTIFICATION_CATEGORIES: ReadonlySet<NotificationCategory> =\n new Set<NotificationCategory>(['staff'])\n\n/**\n * What each category actually covers, in the reader's words (AGL-3251).\n *\n * The settings page listed seven bare labels and two switches, so deciding\n * whether to silence `Product & system` meant guessing what was in it. The\n * type labels beneath each row now name the contents exactly; this is the\n * one-line answer for somebody who does not want to expand anything.\n *\n * Written as what ARRIVES rather than as what the bucket is called: \"someone\n * joins, a role changes\" is checkable against your own feed in a way that\n * \"team and access events\" is not. Exhaustive `Record`, like the channel\n * defaults below — a new category cannot ship without somebody saying in\n * plain words what lands in it.\n */\nexport const NOTIFICATION_CATEGORY_DESCRIPTIONS: Record<\n NotificationCategory,\n string\n> = {\n billing:\n 'Invoices, failed payments, cancellations, and usage that crosses a plan limit.',\n team: 'Somebody joins or leaves, a role changes, or a site is shared with you.',\n content:\n 'Work arriving on your sites: form submissions, bookings, orders, low stock, and the tasks and leads assigned to you.',\n marketplace: 'Decisions on plugin listings you submitted for review.',\n support: 'New support tickets and replies on tickets you are following.',\n system:\n 'Announcements, and the faults the platform finds in your account: sign-in methods removed, traffic limits reached, billing or sharing left in a broken state.',\n staff:\n 'New accounts, new workspaces, and money moving — subscriptions starting, changing, failing and ending — across the whole platform. Only staff receive these.',\n}\n\nexport function notificationCategory(\n type: AglynNotificationType | string,\n): NotificationCategory {\n const prefix = String(type).split('.')[0]\n return (\n [\n 'billing',\n 'team',\n 'content',\n 'marketplace',\n 'support',\n 'system',\n 'staff',\n ].includes(prefix)\n ? prefix\n : 'system'\n ) as NotificationCategory\n}\n\n/**\n * Per-user mute map stored at `users/{uid}.notificationPrefs`\n * (`{ [category]: false }` mutes); absent categories stay on.\n */\nexport function notificationMuted(\n prefs: Record<string, boolean> | null | undefined,\n type: AglynNotificationType | string,\n): boolean {\n return prefs?.[notificationCategory(type)] === false\n}\n\n/**\n * The field on `users/{uid}` that holds a person's digest switches\n * (AGL-2619): `{ crmDaily: false }` turns the daily CRM digest off, and an\n * absent key leaves it on. Its own map rather than a key in\n * `notificationPrefs`, because that map is keyed by CATEGORY and read by\n * {@link notificationMuted} — a digest is a schedule a person keeps or\n * drops, not a bucket of types, and one switch governs both the console\n * notification and the email it travels with.\n */\nexport const DIGEST_PREFS_FIELD = 'digestPrefs'\n\n/**\n * The key the daily CRM digest keeps inside {@link DIGEST_PREFS_FIELD}.\n *\n * Exported so the console writes the switch through a name rather than a\n * second copy of the string (AGL-3230). The reader below and the page that\n * flips it were spelling the same literal in two files, which is how a\n * preference comes to be written under one key and read under another — and\n * it kept the plugin's vocabulary in a console page, where\n * `check:plugin-domain-in-core` rightly refuses it.\n */\nexport const CRM_DAILY_DIGEST_KEY = 'crmDaily'\n\nexport function crmDailyDigestEnabled(\n prefs: Record<string, boolean> | null | undefined,\n): boolean {\n return prefs?.[CRM_DAILY_DIGEST_KEY] !== false\n}\n\n/**\n * The field on `users/{uid}` naming the workspaces whose weekly insights a\n * person asked for (AGL-2915): `{ [orgId]: true }`. OPT-IN, unlike the CRM\n * digest — an absent key is off — because a weekly insight is generated, and a\n * generation spends the workspace's credits. The person turns it on beside the\n * answers themselves, where the plan, the release and their permission have\n * already been checked, and off again there or in Notifications; the weekly\n * sweep checks all three again before it spends anything.\n */\nexport const INSIGHT_DIGESTS_FIELD = 'insightDigests'\n\n/** Whether a person asked for a workspace's weekly insights. */\nexport function insightDigestSubscribed(\n value: Record<string, boolean> | null | undefined,\n orgId: string,\n): boolean {\n return Boolean(orgId) && value?.[orgId] === true\n}\n\n/**\n * The channels a notification can travel on (AGL-3223).\n *\n * `console` is the feed at `/manage/notifications` and the app-bar dropdown\n * that reads it — the only channel that existed. `email` is the message the\n * fan-out sends beside that doc when the recipient asked for one.\n */\nexport type NotificationChannel = 'console' | 'email'\n\n/**\n * One scope's answer for one category. **Tri-state on purpose**: `true` and\n * `false` decide, and an ABSENT key inherits from the scope above.\n *\n * Inheritance is the whole reason this is a partial rather than a pair of\n * booleans. A person who wants form submissions from one busy site and not\n * from the other five has to be able to say that about the one site without\n * restating their answer for every other category at every other scope — and\n * a two-valued leaf cannot express \"I have not said\", so every override would\n * have to be written out in full and would then stop tracking the account\n * default it was never meant to detach from.\n */\nexport interface NotificationChannelPrefs {\n console?: boolean\n email?: boolean\n}\n\nexport type NotificationCategoryPrefs = Partial<\n Record<NotificationCategory, NotificationChannelPrefs>\n>\n\n/**\n * One scope's answer for a single notification TYPE (AGL-3251), tri-state on\n * the same terms as {@link NotificationChannelPrefs}: an absent key falls\n * through to the category.\n *\n * Its own map rather than extra keys in {@link NotificationCategoryPrefs},\n * because that one is an exhaustive record keyed by category and a type key\n * inside it would type-check only by widening the thing that makes a missing\n * category a compile error.\n */\nexport type NotificationTypePrefs = Partial<\n Record<AglynNotificationType, NotificationChannelPrefs>\n>\n\n/**\n * Per-scope, per-channel notification preferences (AGL-3223), stored at\n * `users/{uid}.notificationSettings`.\n *\n * Three layers, narrowest first when resolving: the SITE a notification\n * concerns, then the WORKSPACE, then the account. Anything none of them\n * answers falls to {@link NOTIFICATION_CHANNEL_DEFAULTS}.\n *\n * ON THE USER DOCUMENT, not on `orgs/{orgId}/members/{uid}`, and that is a\n * cost decision rather than a modelling preference. `notifyUsers` already\n * does exactly one `getAll` over the recipients' user docs to read their\n * category mutes, so every layer living here means per-site preferences are\n * read for free on the fan-out's hot path. The member row would add a read\n * per recipient per notification to answer a question the document already in\n * hand could have answered.\n */\nexport interface NotificationSettings {\n account?: NotificationCategoryPrefs\n /**\n * Per-TYPE answers at the account scope (AGL-3251), consulted before\n * {@link NotificationSettings.account}'s category answer and never above a\n * narrower scope — see {@link notificationChannelEnabled}.\n *\n * ACCOUNT ONLY, deliberately. The per-workspace and per-site card is\n * already seven categories by three states by two channels, and a type row\n * for each of the ~thirty types, per workspace AND per site, is a page\n * nobody can read — which is the complaint this whole issue started as.\n * The account scope is where \"stop telling me about THIS\" belongs anyway:\n * it is a statement about the kind of thing, and kinds do not vary by site.\n */\n accountTypes?: NotificationTypePrefs\n /** Keyed by org id. */\n orgs?: Record<string, NotificationCategoryPrefs>\n /** Keyed by host id — a site's own answer, narrower than its workspace's. */\n hosts?: Record<string, NotificationCategoryPrefs>\n /**\n * Per-TYPE answers at the workspace and site scopes (AGL-3267), beside the\n * category maps above rather than nested inside them.\n *\n * Parallel maps because the category maps are already stored under `orgs`\n * and `hosts` on live user documents: folding both into one\n * `{ categories, types }` object per scope would be a migration of every\n * preference anybody has set, to express something two more keys express\n * without touching a byte of what exists.\n *\n * This supersedes the account-only limit AGL-3251 shipped under. That was\n * the right call for a card nobody had used yet and the wrong one once it\n * existed: \"quiet this one type down on this one busy site\" is the question\n * the scope card is FOR, and answering it only for whole categories made\n * the fine grain stop exactly where the noise is worst.\n */\n orgTypes?: Record<string, NotificationTypePrefs>\n hostTypes?: Record<string, NotificationTypePrefs>\n}\n\nexport const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings'\n\n/**\n * What a category does when nobody has said otherwise.\n *\n * Console on, email OFF, everywhere. Email defaults off because the inbox is\n * not ours to fill: the product already sends transactional mail nobody opted\n * into — welcome, verification, invites, dunning, usage alerts — and every one\n * of those leaves on the same domain a customer's password reset depends on.\n * Turning a busy site's form submissions into mail by default would put that\n * domain's reputation behind traffic the recipient never asked for.\n *\n * Exhaustive `Record` deliberately: a new {@link NotificationCategory} is a\n * compile error here until somebody decides what it does by default, which is\n * the one question a new category must not be able to ship without answering.\n */\nexport const NOTIFICATION_CHANNEL_DEFAULTS: Record<\n NotificationCategory,\n Record<NotificationChannel, boolean>\n> = {\n billing: { console: true, email: false },\n team: { console: true, email: false },\n content: { console: true, email: false },\n marketplace: { console: true, email: false },\n support: { console: true, email: false },\n system: { console: true, email: false },\n // Console ON, because the complaint this answers is that staff never heard\n // about a sign-up at all; email off, like everything else, because that is\n // what the channel defaults to and a sign-up is not urgent enough to be the\n // exception that starts filling inboxes by default.\n staff: { console: true, email: false },\n}\n\n/**\n * The types that send their OWN email and must never be mailed again by the\n * generic channel (AGL-3224).\n *\n * Both digests compose a message the fan-out could not reproduce — a day's\n * owed tasks, a week's figures — and send it from their own route under their\n * own switch (`digestPrefs.crmDaily`, `insightDigests.{orgId}`). A recipient\n * who switches the `content` email channel on would otherwise receive the\n * digest twice: once as the digest, once as a one-line \"Daily CRM digest\"\n * notification saying that the digest happened.\n */\nexport const NOTIFICATION_SELF_SENT_EMAIL_TYPES: ReadonlySet<string> =\n new Set<AglynNotificationType>([\n 'content.crmDailyDigest',\n 'content.insightsDigest',\n // Emailed by `notifyRiskEvent` itself, as account mail (AGL-3368).\n 'system.riskNotice',\n ])\n\n/**\n * Whether a channel is on for one notification, at its own scope.\n *\n * Resolution order, first answer wins: the notification's SITE, its\n * WORKSPACE, the account, then {@link NOTIFICATION_CHANNEL_DEFAULTS}. A scope\n * that holds no entry for the category, or an entry with the channel key\n * absent, does not answer — see {@link NotificationChannelPrefs}.\n *\n * `legacyPrefs` is the flat `notificationPrefs` mute map this replaces\n * (AGL-267), and it sits BELOW the account layer rather than beside it.\n * Nothing migrates it: a person who never opens the new settings page keeps\n * being governed by the mutes they set years ago, and the first thing they do\n * set on the account layer overrides the old map for that category without\n * disturbing the rest of it. It answers for `console` only, because the map\n * predates there being a second channel and reading a console mute as an\n * email preference would be inventing an answer its author never gave.\n */\nexport function notificationChannelEnabled(\n settings: NotificationSettings | null | undefined,\n channel: NotificationChannel,\n type: AglynNotificationType | string,\n scope?: { orgId?: string | null; hostId?: string | null },\n legacyPrefs?: Record<string, boolean> | null,\n): boolean {\n const category = notificationCategory(type)\n /*\n * ⛔ A STAFF NOTIFICATION HAS NO SCOPE TO BE NARROWED BY (AGL-3267).\n *\n * It is about the platform, and the workspace one MENTIONS is its subject,\n * not its audience: the staff member reading \"Acme Co subscribed\" is\n * almost never a member of Acme Co, and if they happen to be, their\n * preferences for their own membership have nothing to do with it.\n *\n * This was already true by accident — no staff emitter passes `orgId` or\n * `hostId`, so the scope layers never matched — which made every\n * \"Platform growth\" row in the per-workspace card a control that could be\n * set and could never do anything. Stating it here rather than only hiding\n * those rows is the difference between the model being right and the UI\n * covering for a model that is wrong: a `staff.*` type that ever does\n * start carrying an `orgId`, for its link or its subject line, must not\n * silently become mutable per workspace.\n */\n const staffWide = STAFF_NOTIFICATION_CATEGORIES.has(category)\n /*\n * Narrowest scope first, and within each scope the TYPE before its\n * CATEGORY (AGL-3251, widened to every scope by AGL-3267).\n *\n * Both halves matter and they answer different questions. Scope order is\n * \"where is this from\" — a site's answer beats its workspace's, which beats\n * the account's, because quietening one busy site is the thing the scope\n * card exists for. Type-before-category is \"what kind of thing is this\" —\n * somebody who switched `Payment failed` off said something about that\n * type, and it must beat their own broader `Billing` answer at the SAME\n * scope without leaking upward past a narrower one.\n */\n const layers: Array<NotificationChannelPrefs | undefined> = staffWide\n ? [\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n : [\n scope?.hostId\n ? settings?.hostTypes?.[scope.hostId]?.[type as AglynNotificationType]\n : undefined,\n scope?.hostId ? settings?.hosts?.[scope.hostId]?.[category] : undefined,\n scope?.orgId\n ? settings?.orgTypes?.[scope.orgId]?.[type as AglynNotificationType]\n : undefined,\n scope?.orgId ? settings?.orgs?.[scope.orgId]?.[category] : undefined,\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n for (const layer of layers) {\n const answer = layer?.[channel]\n if (typeof answer === 'boolean') return answer\n }\n if (channel === 'console' && notificationMuted(legacyPrefs, type))\n return false\n return NOTIFICATION_CHANNEL_DEFAULTS[category][channel]\n}\n\n/**\n * What one scope says, with no inheritance applied — what the settings page\n * renders as Inherit / On / Off, and `undefined` is Inherit.\n *\n * `scope` names the layer directly rather than being derived from a\n * notification, because the page edits a layer whether or not anything has\n * ever arrived from it.\n */\n/**\n * What the account scope says about one TYPE, with no inheritance applied\n * (AGL-3251) — `undefined` means the row follows its category.\n *\n * The page needs the unresolved answer to draw the difference between \"on\n * because Billing is on\" and \"on because you said so\": only the second can be\n * reset, and a switch that cannot show which one it is leaves a person unable\n * to get back to following the category.\n */\nexport function notificationAccountTypePref(\n settings: NotificationSettings | null | undefined,\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n return settings?.accountTypes?.[type as AglynNotificationType]?.[channel]\n}\n\n/**\n * Every type in a category, in the order the labels declare them\n * (AGL-3251) — what the settings page expands a category row into.\n *\n * Derived from {@link NOTIFICATION_TYPE_LABELS} rather than held as a second\n * map, so a type added there appears under its category without anybody\n * remembering to list it twice.\n */\nexport function notificationTypesInCategory(\n category: NotificationCategory,\n): AglynNotificationType[] {\n return (\n Object.keys(NOTIFICATION_TYPE_LABELS) as AglynNotificationType[]\n ).filter((type) => notificationCategory(type) === category)\n}\n\n/**\n * What ONE scope says about ONE type, with no inheritance applied\n * (AGL-3267) — `undefined` means the row follows its category at that scope.\n *\n * The scope-aware sibling of {@link notificationAccountTypePref}, which stays\n * as the account-only shorthand its callers already use.\n */\nexport function notificationScopeTypePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.accountTypes\n : scope.kind === 'org'\n ? settings?.orgTypes?.[scope.id]\n : settings?.hostTypes?.[scope.id]\n return layer?.[type as AglynNotificationType]?.[channel]\n}\n\nexport function notificationScopePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n category: NotificationCategory,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.account\n : scope.kind === 'org'\n ? settings?.orgs?.[scope.id]\n : settings?.hosts?.[scope.id]\n return layer?.[category]?.[channel]\n}\n\n/**\n * The scopes this person has said something different about — what the\n * settings page lists so an override is never somewhere you have to go\n * looking for.\n *\n * Returns ids, not names: the page holds the org and host rosters and this\n * module holds no lookups. An id with no name is still worth listing, because\n * a preference about a workspace somebody left is exactly the kind of\n * leftover that is invisible until it is listed.\n */\nexport function notificationOverriddenScopes(\n settings: NotificationSettings | null | undefined,\n): { orgIds: string[]; hostIds: string[] } {\n /*\n * BOTH maps for a scope, categories and types (AGL-3267).\n *\n * Reading only the category map would make a scope whose ONLY answer is a\n * per-type one invisible here — and this list is the single place a person\n * can find an override they set months ago. Silencing one type on one busy\n * site and then being unable to find where you did it is precisely the\n * failure this function exists to prevent.\n */\n const answered = (prefs: Record<string, NotificationChannelPrefs> | undefined) =>\n Object.values(prefs ?? {}).some((channels) =>\n Object.values(channels ?? {}).some((value) => typeof value === 'boolean'),\n )\n const named = (\n categories: Record<string, NotificationCategoryPrefs> | undefined,\n types: Record<string, NotificationTypePrefs> | undefined,\n ) =>\n [\n ...new Set([\n ...Object.keys(categories ?? {}),\n ...Object.keys(types ?? {}),\n ]),\n ]\n .filter(\n (id) =>\n answered(categories?.[id] as Record<string, NotificationChannelPrefs>) ||\n answered(types?.[id] as Record<string, NotificationChannelPrefs>),\n )\n .sort()\n return {\n orgIds: named(settings?.orgs, settings?.orgTypes),\n hostIds: named(settings?.hosts, settings?.hostTypes),\n }\n}\n\n/**\n * Rewrites a stored notification link onto the current URL scheme (AGL-644).\n *\n * A notification's `link` is frozen at write time — `notifyUsers` persists\n * whatever string the emitter passed and never normalizes it. So every\n * notification written before the org-slug migration (AGL-621) and the\n * subdomain migration (AGL-622) still points at a route that no longer\n * exists, and fixing the emitters alone would leave that whole backlog dead.\n * Normalizing when the link is FOLLOWED repairs old and new alike, and keeps\n * working for emitters that haven't been migrated yet.\n *\n * Rewrites, in order:\n * - `/{hostDocId}` or `/{hostDocId}/rest` → `/{orgSlug}/hosts/{subdomain}/rest`\n * - `/org` or `/org/rest` → `/{orgSlug}/rest`\n * - `/hosts` (exactly) → `/{orgSlug}/hosts`\n *\n * Anything already canonical, user-scoped (`/manage/...`), staff (`/admin/...`)\n * or absolute is returned untouched. Every rewrite is gated on having the\n * context it needs, so an unresolvable link degrades to its stored value\n * rather than to a wrong destination.\n *\n * The host rewrite is keyed on the notification's own `hostId` rather than\n * guessing from the path shape, so it can never mistake a real first segment\n * for a doc id.\n *\n * The email copy of a notification goes through it too (AGL-3367): a button\n * in an inbox is a followed link with no console around it to repair it.\n */\nexport function normalizeNotificationLink(\n link: string | undefined | null,\n context: {\n orgSlug?: string | null\n /** The notification's `hostId` (a Firestore doc id). */\n hostId?: string | null\n /** That host's subdomain, which the current routes are keyed by. */\n hostSubdomain?: string | null\n },\n): string | undefined {\n if (!link) return undefined\n // Absolute URLs (staff broadcasts can carry them) are not ours to rewrite.\n if (!link.startsWith('/')) return link\n\n const { orgSlug, hostId, hostSubdomain } = context\n\n if (orgSlug && hostId && hostSubdomain) {\n const prefix = `/${hostId}`\n if (link === prefix || link.startsWith(`${prefix}/`)) {\n return `${buildRoute(Route.HOST_DASHBOARD, {\n orgSlug,\n host: hostSubdomain,\n })}${link.slice(prefix.length)}`\n }\n }\n\n if (orgSlug) {\n if (link === '/org' || link.startsWith('/org/')) {\n return `${buildRoute(Route.ORG_HOME, { orgSlug })}${link.slice(\n '/org'.length,\n )}`\n }\n // Only the bare list — `/hosts/{docId}` would still need a subdomain, and\n // guessing one is worse than leaving the link alone.\n if (link === '/hosts') return buildRoute(Route.HOST_LIST, { orgSlug })\n }\n\n return link\n}\n"],"names":["buildRoute","Route","NOTIFICATION_TYPE_LABELS","NOTIFICATION_CATEGORY_LABELS","billing","team","content","marketplace","support","system","staff","STAFF_NOTIFICATION_CATEGORIES","Set","NOTIFICATION_CATEGORY_DESCRIPTIONS","notificationCategory","type","prefix","String","split","includes","notificationMuted","prefs","DIGEST_PREFS_FIELD","CRM_DAILY_DIGEST_KEY","crmDailyDigestEnabled","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","value","orgId","Boolean","NOTIFICATION_SETTINGS_FIELD","NOTIFICATION_CHANNEL_DEFAULTS","console","email","NOTIFICATION_SELF_SENT_EMAIL_TYPES","notificationChannelEnabled","settings","channel","scope","legacyPrefs","category","staffWide","has","layers","accountTypes","account","hostId","hostTypes","undefined","hosts","orgTypes","orgs","layer","answer","notificationAccountTypePref","notificationTypesInCategory","Object","keys","filter","notificationScopeTypePref","kind","id","notificationScopePref","notificationOverriddenScopes","answered","values","some","channels","named","categories","types","sort","orgIds","hostIds","normalizeNotificationLink","link","context","startsWith","orgSlug","hostSubdomain","HOST_DASHBOARD","host","slice","length","ORG_HOME","HOST_LIST"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,UAAU,EAAEC,KAAK,QAAQ,sBAA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MAAM,EAAEiC,aAAa,EAAE,GAAGH;IAE3C,IAAIE,WAAWhC,UAAUiC,eAAe;QACtC,MAAM/D,SAAS,CAAC,CAAC,EAAE8B,QAAQ;QAC3B,IAAI6B,SAAS3D,UAAU2D,KAAKE,UAAU,CAAC,GAAG7D,OAAO,CAAC,CAAC,GAAG;YACpD,OAAO,GAAGhB,WAAWC,MAAM+E,cAAc,EAAE;gBACzCF;gBACAG,MAAMF;YACR,KAAKJ,KAAKO,KAAK,CAAClE,OAAOmE,MAAM,GAAG;QAClC;IACF;IAEA,IAAIL,SAAS;QACX,IAAIH,SAAS,UAAUA,KAAKE,UAAU,CAAC,UAAU;YAC/C,OAAO,GAAG7E,WAAWC,MAAMmF,QAAQ,EAAE;gBAAEN;YAAQ,KAAKH,KAAKO,KAAK,CAC5D,OAAOC,MAAM,GACZ;QACL;QACA,0EAA0E;QAC1E,qDAAqD;QACrD,IAAIR,SAAS,UAAU,OAAO3E,WAAWC,MAAMoF,SAAS,EAAE;YAAEP;QAAQ;IACtE;IAEA,OAAOH;AACT"}
|
|
@@ -0,0 +1,132 @@
|
|
|
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
|
+
import type { AglynNotificationType } from './notifications';
|
|
18
|
+
/**
|
|
19
|
+
* OPERATOR ALERTS (AGL-3377): the events whoever runs an install must hear
|
|
20
|
+
* about, as one typed catalog.
|
|
21
|
+
*
|
|
22
|
+
* Every alert is an entry here (or a plugin's entry in the same shape,
|
|
23
|
+
* registered through `@aglyn/aglyn/plugin-manager/operator-alerts`) and is
|
|
24
|
+
* raised through ONE server entry point, `raiseOperatorAlert` in
|
|
25
|
+
* `@aglyn/tenant-data-admin/server/operator-alerts`. That entry point writes
|
|
26
|
+
* the staff console notification, dedupes a flapping condition, honours the
|
|
27
|
+
* per-type switches staff set on Staff → Operator alerts, and delivers by
|
|
28
|
+
* email (the `operator-alert` system email) and the optional out-of-band
|
|
29
|
+
* webhook. No call site composes or sends its own mail.
|
|
30
|
+
*
|
|
31
|
+
* The catalog holds nothing install-specific: no address, no domain, no
|
|
32
|
+
* host. Recipients come from `resolveStaffAlertRecipients()` and the webhook
|
|
33
|
+
* from `OPERATOR_ALERT_WEBHOOK_URL`, so an entry reads the same on aglyn.com,
|
|
34
|
+
* on a self-hosted install and in an OSS consumer's deployment.
|
|
35
|
+
*
|
|
36
|
+
* Copy is written against merge tokens (`{{orgId}}`), filled from the
|
|
37
|
+
* `context` the call site passes. A token the call site did not supply is
|
|
38
|
+
* blanked, so every sentence must still read when its optional tokens are
|
|
39
|
+
* empty. Never put a data subject's address or other personal data into a
|
|
40
|
+
* context: the alert travels to an inbox and a webhook, not only the console.
|
|
41
|
+
*/
|
|
42
|
+
/**
|
|
43
|
+
* How much an alert matters.
|
|
44
|
+
*
|
|
45
|
+
* - `must` — money moving with nobody looking, a legal duty unmet, data not
|
|
46
|
+
* protected or not erased. On and immediate unless staff change it.
|
|
47
|
+
* - `should` — a fault an operator wants to know about today.
|
|
48
|
+
* - `low` — routine review work; on, and batched into the daily digest.
|
|
49
|
+
*/
|
|
50
|
+
export type OperatorAlertTier = 'must' | 'should' | 'low';
|
|
51
|
+
export type OperatorAlertCategory = 'billing' | 'payments' | 'legal' | 'data' | 'ops' | 'deliverability' | 'security' | 'support';
|
|
52
|
+
/** `digest` batches the alert into the once-a-day operator digest. */
|
|
53
|
+
export type OperatorAlertDelivery = 'immediate' | 'digest';
|
|
54
|
+
export interface OperatorAlertDefinition {
|
|
55
|
+
/**
|
|
56
|
+
* Stable id, also the key of its settings row. Never rename: staff
|
|
57
|
+
* switches are stored under it. A plugin's types start with its plugin id
|
|
58
|
+
* and a dot (`commerce.taxNotReversed`).
|
|
59
|
+
*/
|
|
60
|
+
type: string;
|
|
61
|
+
/** The settings row's name. */
|
|
62
|
+
label: string;
|
|
63
|
+
/** What it means and the first thing to do, for the settings page. */
|
|
64
|
+
description: string;
|
|
65
|
+
tier: OperatorAlertTier;
|
|
66
|
+
category: OperatorAlertCategory;
|
|
67
|
+
/** The notification title and email subject, with `{{tokens}}`. */
|
|
68
|
+
title: string;
|
|
69
|
+
/** What happened and what to do, with `{{tokens}}`. */
|
|
70
|
+
body: string;
|
|
71
|
+
/** Console path the alert opens, with `{{tokens}}`; the call may override. */
|
|
72
|
+
link?: string;
|
|
73
|
+
/** The coded default; staff may change it. */
|
|
74
|
+
delivery: OperatorAlertDelivery;
|
|
75
|
+
/**
|
|
76
|
+
* How long one `dedupeKey` stays quiet after it fired, in minutes. A
|
|
77
|
+
* condition that flaps inside the window is told once. `0` never dedupes.
|
|
78
|
+
* A call without a `dedupeKey` is never deduped.
|
|
79
|
+
*/
|
|
80
|
+
dedupeWindowMinutes: number;
|
|
81
|
+
/**
|
|
82
|
+
* Fire only once the same `dedupeKey` has been raised this many times
|
|
83
|
+
* inside the window — for an endpoint any stranger can hit, where one
|
|
84
|
+
* refused request is noise and several are a broken secret. Default 1.
|
|
85
|
+
*/
|
|
86
|
+
minOccurrences?: number;
|
|
87
|
+
/** The coded default; staff may change it. */
|
|
88
|
+
defaultEnabled: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* The console notification's type. Absent is the generic
|
|
91
|
+
* `system.operatorAlert`; a type that already had its own notification
|
|
92
|
+
* keeps it, so its icon, label and everyone's mutes are unchanged.
|
|
93
|
+
*/
|
|
94
|
+
notificationType?: AglynNotificationType;
|
|
95
|
+
/** The plugin that contributed it; absent for core's own. */
|
|
96
|
+
pluginId?: string;
|
|
97
|
+
}
|
|
98
|
+
/** Values a call site passes for an alert's `{{tokens}}`. */
|
|
99
|
+
export type OperatorAlertContext = Readonly<Record<string, string | number | boolean | null | undefined>>;
|
|
100
|
+
/** The notification type an alert without its own writes under. */
|
|
101
|
+
export declare const OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE: AglynNotificationType;
|
|
102
|
+
export declare const OPERATOR_ALERT_TIER_LABELS: Record<OperatorAlertTier, string>;
|
|
103
|
+
export declare const OPERATOR_ALERT_CATEGORY_LABELS: Record<OperatorAlertCategory, string>;
|
|
104
|
+
/**
|
|
105
|
+
* Core's alerts. Plugins contribute theirs through the plugin-manager
|
|
106
|
+
* registry; nothing plugin-specific belongs in this list.
|
|
107
|
+
*/
|
|
108
|
+
export declare const CORE_OPERATOR_ALERTS: readonly OperatorAlertDefinition[];
|
|
109
|
+
/** An amount in minor units, as an alert prints it: `$12.40`. */
|
|
110
|
+
export declare function formatOperatorAlertAmount(cents: number, currency?: string): string;
|
|
111
|
+
/** Replaces each `{{token}}` with its context value, or nothing. */
|
|
112
|
+
export declare function renderOperatorAlertTemplate(template: string, context: OperatorAlertContext | undefined): string;
|
|
113
|
+
/** A staff member's answer for one type; an absent key keeps the default. */
|
|
114
|
+
export interface OperatorAlertTypeSetting {
|
|
115
|
+
enabled?: boolean;
|
|
116
|
+
delivery?: OperatorAlertDelivery;
|
|
117
|
+
}
|
|
118
|
+
/** `platformSettings/operatorAlerts`, keyed by alert type. */
|
|
119
|
+
export interface OperatorAlertSettings {
|
|
120
|
+
types?: Record<string, OperatorAlertTypeSetting>;
|
|
121
|
+
}
|
|
122
|
+
/** Whether a type is on, and how it is delivered, after staff's answers. */
|
|
123
|
+
export declare function effectiveOperatorAlertSetting(definition: Pick<OperatorAlertDefinition, 'type' | 'delivery' | 'defaultEnabled'>, settings: OperatorAlertSettings | null | undefined): {
|
|
124
|
+
enabled: boolean;
|
|
125
|
+
delivery: OperatorAlertDelivery;
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Staff notification types whose alert emails the operator on a coded
|
|
129
|
+
* default of immediate (AGL-3375), derived from the catalog so there is one
|
|
130
|
+
* list.
|
|
131
|
+
*/
|
|
132
|
+
export declare const OPERATOR_ALERT_NOTIFICATION_TYPES: ReadonlySet<string>;
|