@aglyn/tenant-data-admin 1.0.0-beta.269 → 1.0.0-beta.271

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.
Files changed (77) hide show
  1. package/package.json +7 -7
  2. package/src/lib/render-cache.d.ts +10 -3
  3. package/src/lib/render-cache.js +10 -3
  4. package/src/lib/render-cache.js.map +1 -1
  5. package/src/lib/server/append-only-history-write.d.ts +38 -0
  6. package/src/lib/server/append-only-history-write.js +60 -0
  7. package/src/lib/server/append-only-history-write.js.map +1 -0
  8. package/src/lib/server/billing-addons.d.ts +58 -30
  9. package/src/lib/server/billing-addons.js +102 -77
  10. package/src/lib/server/billing-addons.js.map +1 -1
  11. package/src/lib/server/bundle-links.d.ts +166 -0
  12. package/src/lib/server/bundle-links.js +286 -0
  13. package/src/lib/server/bundle-links.js.map +1 -0
  14. package/src/lib/server/client-build.d.ts +74 -0
  15. package/src/lib/server/client-build.js +264 -0
  16. package/src/lib/server/client-build.js.map +1 -0
  17. package/src/lib/server/configured-url-fetch.d.ts +26 -0
  18. package/src/lib/server/configured-url-fetch.js +68 -0
  19. package/src/lib/server/configured-url-fetch.js.map +1 -1
  20. package/src/lib/server/custom-domain-redirects.d.ts +50 -0
  21. package/src/lib/server/custom-domain-redirects.js +61 -0
  22. package/src/lib/server/custom-domain-redirects.js.map +1 -0
  23. package/src/lib/server/host-custom-domain.d.ts +125 -0
  24. package/src/lib/server/host-custom-domain.js +395 -0
  25. package/src/lib/server/host-custom-domain.js.map +1 -0
  26. package/src/lib/server/host-memberships.d.ts +35 -2
  27. package/src/lib/server/host-memberships.js +63 -2
  28. package/src/lib/server/host-memberships.js.map +1 -1
  29. package/src/lib/server/host-released-names.d.ts +1 -2
  30. package/src/lib/server/host-released-names.js +4 -2
  31. package/src/lib/server/host-released-names.js.map +1 -1
  32. package/src/lib/server/media-photo-links.d.ts +196 -0
  33. package/src/lib/server/media-photo-links.js +290 -0
  34. package/src/lib/server/media-photo-links.js.map +1 -0
  35. package/src/lib/server/org-billing.d.ts +4 -2
  36. package/src/lib/server/org-billing.js +5 -0
  37. package/src/lib/server/org-billing.js.map +1 -1
  38. package/src/lib/server/organizations.d.ts +25 -1
  39. package/src/lib/server/organizations.js +62 -2
  40. package/src/lib/server/organizations.js.map +1 -1
  41. package/src/lib/server/personal-data-export.js +21 -1
  42. package/src/lib/server/personal-data-export.js.map +1 -1
  43. package/src/lib/server/push-delivery.js +32 -14
  44. package/src/lib/server/push-delivery.js.map +1 -1
  45. package/src/lib/server/site-care-emails.d.ts +52 -0
  46. package/src/lib/server/site-care-emails.js +97 -0
  47. package/src/lib/server/site-care-emails.js.map +1 -0
  48. package/src/lib/server/site-care-inbound.d.ts +80 -0
  49. package/src/lib/server/site-care-inbound.js +171 -0
  50. package/src/lib/server/site-care-inbound.js.map +1 -0
  51. package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
  52. package/src/lib/server/site-care-project-reconcile.js +211 -0
  53. package/src/lib/server/site-care-project-reconcile.js.map +1 -0
  54. package/src/lib/server/site-care-project-stripe.d.ts +114 -0
  55. package/src/lib/server/site-care-project-stripe.js +305 -0
  56. package/src/lib/server/site-care-project-stripe.js.map +1 -0
  57. package/src/lib/server/site-care-projects.d.ts +169 -0
  58. package/src/lib/server/site-care-projects.js +882 -0
  59. package/src/lib/server/site-care-projects.js.map +1 -0
  60. package/src/lib/server/site-care-reconcile.d.ts +81 -0
  61. package/src/lib/server/site-care-reconcile.js +349 -0
  62. package/src/lib/server/site-care-reconcile.js.map +1 -0
  63. package/src/lib/server/site-care-requests.d.ts +243 -0
  64. package/src/lib/server/site-care-requests.js +1414 -0
  65. package/src/lib/server/site-care-requests.js.map +1 -0
  66. package/src/lib/server/site-care-stripe.d.ts +175 -0
  67. package/src/lib/server/site-care-stripe.js +375 -0
  68. package/src/lib/server/site-care-stripe.js.map +1 -0
  69. package/src/lib/server/tenant-dns-check.d.ts +58 -0
  70. package/src/lib/server/tenant-dns-check.js +197 -0
  71. package/src/lib/server/tenant-dns-check.js.map +1 -0
  72. package/src/lib/server/upgrade-proposal.d.ts +40 -1
  73. package/src/lib/server/upgrade-proposal.js +92 -50
  74. package/src/lib/server/upgrade-proposal.js.map +1 -1
  75. package/src/tenancy.d.ts +5 -0
  76. package/src/tenancy.js +10 -0
  77. package/src/tenancy.js.map +1 -1
@@ -0,0 +1,52 @@
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
+ /**
18
+ * SENDING THE SITE CARE EMAILS (AGL-3959).
19
+ *
20
+ * Every Site Care email is a catalog key (`site-care-emails.ts` in
21
+ * `shared-util-email`), rendered in the WORKSPACE's brand — a white-label
22
+ * agency's client hears from the agency — and sent from the platform's
23
+ * address with a Reply-To that threads the answer onto the same request:
24
+ * `care+<requestId>@<inbound mail domain>`. Metered as platform mail, like
25
+ * the success manager's copy: this is the service the owner pays for, not
26
+ * mail the workspace sent.
27
+ *
28
+ * Never throws. The caller records what it returns as the request's
29
+ * `email.sent` history row, so whether an email went is a fact on the
30
+ * request rather than an assumption.
31
+ */
32
+ /** The address a request's emails reply to, so the answer joins it. */
33
+ export declare function siteCareReplyTo(requestId: string | null): string;
34
+ export interface SiteCareEmailInput {
35
+ key: string;
36
+ to: string | null;
37
+ /** The workspace whose brand the email is sent in; null is the platform's. */
38
+ org: Readonly<Record<string, unknown>> | null;
39
+ requestId: string | null;
40
+ merge: Record<string, string>;
41
+ fallback: {
42
+ subject: string;
43
+ text: string;
44
+ };
45
+ }
46
+ export interface SiteCareEmailResult {
47
+ sent: boolean;
48
+ to: string | null;
49
+ subject: string;
50
+ reason?: string;
51
+ }
52
+ export declare function sendSiteCareEmail(input: SiteCareEmailInput): Promise<SiteCareEmailResult>;
@@ -0,0 +1,97 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { inboundMailDomain } from "@aglyn/aglyn/app-utils/inbound-mail-domain";
18
+ import { SITE_CARE_INBOUND_LOCAL_PART } from "@aglyn/aglyn/app-utils/site-care";
19
+ import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
20
+ import { meterPlatformEmail } from "./email-metering.js";
21
+ import { renderSystemEmailContent, systemEmailBrand } from "./render-system-email.js";
22
+ /**
23
+ * SENDING THE SITE CARE EMAILS (AGL-3959).
24
+ *
25
+ * Every Site Care email is a catalog key (`site-care-emails.ts` in
26
+ * `shared-util-email`), rendered in the WORKSPACE's brand — a white-label
27
+ * agency's client hears from the agency — and sent from the platform's
28
+ * address with a Reply-To that threads the answer onto the same request:
29
+ * `care+<requestId>@<inbound mail domain>`. Metered as platform mail, like
30
+ * the success manager's copy: this is the service the owner pays for, not
31
+ * mail the workspace sent.
32
+ *
33
+ * Never throws. The caller records what it returns as the request's
34
+ * `email.sent` history row, so whether an email went is a fact on the
35
+ * request rather than an assumption.
36
+ */ /** The address a request's emails reply to, so the answer joins it. */ export function siteCareReplyTo(requestId) {
37
+ const local = requestId ? `${SITE_CARE_INBOUND_LOCAL_PART}+${requestId}` : SITE_CARE_INBOUND_LOCAL_PART;
38
+ return `${local}@${inboundMailDomain()}`;
39
+ }
40
+ export async function sendSiteCareEmail(input) {
41
+ var _input_to;
42
+ const to = String((_input_to = input.to) != null ? _input_to : '').trim();
43
+ if (!to) return {
44
+ sent: false,
45
+ to: null,
46
+ subject: input.fallback.subject,
47
+ reason: 'no-recipient'
48
+ };
49
+ if (!isEmailConfigured()) {
50
+ return {
51
+ sent: false,
52
+ to,
53
+ subject: input.fallback.subject,
54
+ reason: 'unconfigured'
55
+ };
56
+ }
57
+ try {
58
+ var _result_reason;
59
+ const brand = systemEmailBrand(input.org);
60
+ const content = await renderSystemEmailContent(input.key, _extends({}, brand.orgName ? {
61
+ 'org.name': brand.orgName
62
+ } : {}, input.merge), brand, input.fallback);
63
+ const result = await sendEmail(_extends({
64
+ to,
65
+ subject: content.subject,
66
+ text: content.text
67
+ }, content.html ? {
68
+ html: content.html
69
+ } : {}, brand.fromName ? {
70
+ fromName: brand.fromName
71
+ } : {}, {
72
+ replyTo: siteCareReplyTo(input.requestId),
73
+ context: input.key
74
+ }));
75
+ if (result.sent) await meterPlatformEmail();
76
+ return result.sent ? {
77
+ sent: true,
78
+ to,
79
+ subject: content.subject
80
+ } : {
81
+ sent: false,
82
+ to,
83
+ subject: content.subject,
84
+ reason: String((_result_reason = result.reason) != null ? _result_reason : 'not-sent')
85
+ };
86
+ } catch (error) {
87
+ console.error(`[site-care] ${input.key} email failed`, error);
88
+ return {
89
+ sent: false,
90
+ to,
91
+ subject: input.fallback.subject,
92
+ reason: 'error'
93
+ };
94
+ }
95
+ }
96
+
97
+ //# sourceMappingURL=site-care-emails.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-emails.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 { inboundMailDomain } from '@aglyn/aglyn/app-utils/inbound-mail-domain'\nimport { SITE_CARE_INBOUND_LOCAL_PART } from '@aglyn/aglyn/app-utils/site-care'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { meterPlatformEmail } from './email-metering'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\n/**\n * SENDING THE SITE CARE EMAILS (AGL-3959).\n *\n * Every Site Care email is a catalog key (`site-care-emails.ts` in\n * `shared-util-email`), rendered in the WORKSPACE's brand — a white-label\n * agency's client hears from the agency — and sent from the platform's\n * address with a Reply-To that threads the answer onto the same request:\n * `care+<requestId>@<inbound mail domain>`. Metered as platform mail, like\n * the success manager's copy: this is the service the owner pays for, not\n * mail the workspace sent.\n *\n * Never throws. The caller records what it returns as the request's\n * `email.sent` history row, so whether an email went is a fact on the\n * request rather than an assumption.\n */\n\n/** The address a request's emails reply to, so the answer joins it. */\nexport function siteCareReplyTo(requestId: string | null): string {\n const local = requestId ? `${SITE_CARE_INBOUND_LOCAL_PART}+${requestId}` : SITE_CARE_INBOUND_LOCAL_PART\n return `${local}@${inboundMailDomain()}`\n}\n\nexport interface SiteCareEmailInput {\n key: string\n to: string | null\n /** The workspace whose brand the email is sent in; null is the platform's. */\n org: Readonly<Record<string, unknown>> | null\n requestId: string | null\n merge: Record<string, string>\n fallback: { subject: string; text: string }\n}\n\nexport interface SiteCareEmailResult {\n sent: boolean\n to: string | null\n subject: string\n reason?: string\n}\n\nexport async function sendSiteCareEmail(input: SiteCareEmailInput): Promise<SiteCareEmailResult> {\n const to = String(input.to ?? '').trim()\n if (!to) return { sent: false, to: null, subject: input.fallback.subject, reason: 'no-recipient' }\n if (!isEmailConfigured()) {\n return { sent: false, to, subject: input.fallback.subject, reason: 'unconfigured' }\n }\n try {\n const brand = systemEmailBrand(input.org)\n const content = await renderSystemEmailContent(\n input.key,\n { ...(brand.orgName ? { 'org.name': brand.orgName } : {}), ...input.merge },\n brand,\n input.fallback,\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n replyTo: siteCareReplyTo(input.requestId),\n context: input.key,\n })\n if (result.sent) await meterPlatformEmail()\n return result.sent\n ? { sent: true, to, subject: content.subject }\n : {\n sent: false,\n to,\n subject: content.subject,\n reason: String((result as { reason?: unknown }).reason ?? 'not-sent'),\n }\n } catch (error) {\n console.error(`[site-care] ${input.key} email failed`, error)\n return { sent: false, to, subject: input.fallback.subject, reason: 'error' }\n }\n}\n"],"names":["inboundMailDomain","SITE_CARE_INBOUND_LOCAL_PART","isEmailConfigured","sendEmail","meterPlatformEmail","renderSystemEmailContent","systemEmailBrand","siteCareReplyTo","requestId","local","sendSiteCareEmail","input","to","String","trim","sent","subject","fallback","reason","brand","org","content","key","orgName","merge","result","text","html","fromName","replyTo","context","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,4BAA4B,QAAQ,mCAAkC;AAC/E,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,kBAAkB,QAAQ,sBAAkB;AACrD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B;;;;;;;;;;;;;;CAcC,GAED,qEAAqE,GACrE,OAAO,SAASC,gBAAgBC,SAAwB;IACtD,MAAMC,QAAQD,YAAY,GAAGP,6BAA6B,CAAC,EAAEO,WAAW,GAAGP;IAC3E,OAAO,GAAGQ,MAAM,CAAC,EAAET,qBAAqB;AAC1C;AAmBA,OAAO,eAAeU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,CAAC,EAAES;QACvD,OAAO;YAAEhB,MAAM;YAAOH;YAAII,SAASL,MAAMM,QAAQ,CAACD,OAAO;YAAEE,QAAQ;QAAQ;IAC7E;AACF"}
@@ -0,0 +1,80 @@
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 ReceivedEmail } from '@aglyn/shared-util-email';
18
+ import { type SiteCareDeps } from './site-care-requests';
19
+ /**
20
+ * THE SITE CARE ADDRESS (AGL-3959): `care@<inbound mail domain>`.
21
+ *
22
+ * An owner emails or forwards a change to the address and it becomes a Site
23
+ * Care request on their workspace, matched by the sender's address against
24
+ * the members of workspaces that have Site Care. A reply to any Site Care
25
+ * email goes to `care+<requestId>@…` and joins that request's thread, when
26
+ * the sender is a member of its workspace. A sender who matches nobody gets
27
+ * a reply asking them to write from the address on the account; the message
28
+ * itself is not kept.
29
+ */
30
+ /** What a received message was addressed to, of the Site Care address. */
31
+ export type SiteCareInboundTarget = {
32
+ kind: 'new';
33
+ } | {
34
+ kind: 'reply';
35
+ requestId: string;
36
+ };
37
+ /** The Site Care target among a message's recipients, or null. */
38
+ export declare function siteCareInboundTarget(recipients: readonly string[], domain: string): SiteCareInboundTarget | null;
39
+ export interface SiteCareSenderMatch {
40
+ orgId: string;
41
+ org: Record<string, unknown>;
42
+ uid: string;
43
+ email: string;
44
+ }
45
+ /** The account an address signs in with: its uid, or null when it has none. */
46
+ export type SiteCareAccountLookup = (email: string) => Promise<{
47
+ uid: string;
48
+ } | null>;
49
+ /**
50
+ * Every pool, not only the project's: an owner who signs in through SSO is a
51
+ * GCIP tenant user the project pool never returns (AGL-1122), and their mail
52
+ * would be answered as a stranger's.
53
+ */
54
+ export declare const findSiteCareAccount: SiteCareAccountLookup;
55
+ /**
56
+ * The Site Care workspace a sender belongs to: the account their address
57
+ * signs in with (in any pool), then the workspaces it is a member of, the
58
+ * first with Site Care in force (by id, so the choice is stable).
59
+ */
60
+ export declare function findSiteCareWorkspaceForSender(firestore: FirebaseFirestore.Firestore, findAccount: SiteCareAccountLookup, sender: string): Promise<SiteCareSenderMatch | null>;
61
+ /** The words of a message, above any quoted history. */
62
+ export declare function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string;
63
+ export type SiteCareInboundOutcome = {
64
+ outcome: 'opened';
65
+ requestId: string;
66
+ } | {
67
+ outcome: 'replied';
68
+ requestId: string;
69
+ } | {
70
+ outcome: 'unknown-sender';
71
+ } | {
72
+ outcome: 'empty';
73
+ };
74
+ /** Files one received message addressed to the Site Care address. */
75
+ export declare function fileSiteCareInboundEmail(firestore: FirebaseFirestore.Firestore, input: {
76
+ target: SiteCareInboundTarget;
77
+ message: ReceivedEmail;
78
+ /** The seam a spec replaces; every auth pool by default. */
79
+ findAccount?: SiteCareAccountLookup;
80
+ }, deps?: SiteCareDeps): Promise<SiteCareInboundOutcome>;
@@ -0,0 +1,171 @@
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
+ */ import { emailAddressOf, htmlToPlainText, stripQuotedHistory, threadSubject } from "@aglyn/aglyn/app-utils/email-text";
17
+ import { SITE_CARE_INBOUND_LOCAL_PART } from "@aglyn/aglyn/app-utils/site-care";
18
+ import { SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY } from "@aglyn/shared-util-email";
19
+ import { appendSiteCareReply, openSiteCareRequest, orgHasSiteCare, readSiteCareOrg } from "./site-care-requests.js";
20
+ import { findUserByEmailAcrossPools } from "./auth-pools.js";
21
+ import { sendSiteCareEmail } from "./site-care-emails.js";
22
+ /** The Site Care target among a message's recipients, or null. */ export function siteCareInboundTarget(recipients, domain) {
23
+ let found = null;
24
+ for (const value of recipients){
25
+ var _ref;
26
+ var _exec;
27
+ // Validated (and lowercased) for the domain, but the local part is read
28
+ // as written: a request id is a case-sensitive Firestore id, and
29
+ // lowercasing `care+AbC…` would look up a ticket that does not exist.
30
+ const address = emailAddressOf(value);
31
+ if (!address) continue;
32
+ const raw = String(value != null ? value : '').trim();
33
+ const written = ((_ref = (_exec = /<([^<>]+)>\s*$/.exec(raw)) == null ? void 0 : _exec[1]) != null ? _ref : raw).trim();
34
+ const at = written.lastIndexOf('@');
35
+ if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain.toLowerCase()) continue;
36
+ const local = written.slice(0, at);
37
+ if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {
38
+ found = found != null ? found : {
39
+ kind: 'new'
40
+ };
41
+ continue;
42
+ }
43
+ const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`;
44
+ if (local.toLowerCase().startsWith(prefix)) {
45
+ const requestId = local.slice(prefix.length);
46
+ // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape
47
+ // is refused rather than looked up.
48
+ if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return {
49
+ kind: 'reply',
50
+ requestId
51
+ };
52
+ }
53
+ }
54
+ return found;
55
+ }
56
+ /**
57
+ * Every pool, not only the project's: an owner who signs in through SSO is a
58
+ * GCIP tenant user the project pool never returns (AGL-1122), and their mail
59
+ * would be answered as a stranger's.
60
+ */ export const findSiteCareAccount = async (email)=>{
61
+ const found = await findUserByEmailAcrossPools(email).catch(()=>null);
62
+ return found ? {
63
+ uid: found.record.uid
64
+ } : null;
65
+ };
66
+ /**
67
+ * The Site Care workspace a sender belongs to: the account their address
68
+ * signs in with (in any pool), then the workspaces it is a member of, the
69
+ * first with Site Care in force (by id, so the choice is stable).
70
+ */ export async function findSiteCareWorkspaceForSender(firestore, findAccount, sender) {
71
+ const email = emailAddressOf(sender);
72
+ if (!email) return null;
73
+ const user = await findAccount(email).catch(()=>null);
74
+ if (!user) return null;
75
+ const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get();
76
+ const orgIds = memberships.docs.map((doc)=>doc.id).sort();
77
+ for (const orgId of orgIds){
78
+ const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get();
79
+ if (!member.exists) continue;
80
+ const org = await readSiteCareOrg(firestore, orgId);
81
+ if (org && orgHasSiteCare(org)) return {
82
+ orgId,
83
+ org,
84
+ uid: user.uid,
85
+ email
86
+ };
87
+ }
88
+ return null;
89
+ }
90
+ /** The words of a message, above any quoted history. */ export function siteCareMessageBody(message) {
91
+ var _message_text;
92
+ const plain = (((_message_text = message.text) == null ? void 0 : _message_text.trim()) ? message.text : htmlToPlainText(message.html)).replace(/\r\n?/g, '\n');
93
+ return stripQuotedHistory(plain).trim();
94
+ }
95
+ /** Files one received message addressed to the Site Care address. */ export async function fileSiteCareInboundEmail(firestore, input, deps = {}) {
96
+ var _input_findAccount;
97
+ const { message } = input;
98
+ const body = siteCareMessageBody(message);
99
+ const sender = emailAddressOf(message.from);
100
+ if (input.target.kind === 'reply') {
101
+ var _ticket_get, _input_findAccount1;
102
+ const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get();
103
+ const orgId = String((_ticket_get = ticket.get('orgId')) != null ? _ticket_get : '');
104
+ const match = sender ? await findSiteCareWorkspaceForSender(firestore, (_input_findAccount1 = input.findAccount) != null ? _input_findAccount1 : findSiteCareAccount, sender) : null;
105
+ // Only a member of the request's own workspace may add to it.
106
+ const member = match && orgId ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists : false;
107
+ if (ticket.exists && member && match) {
108
+ if (!body) return {
109
+ outcome: 'empty'
110
+ };
111
+ await appendSiteCareReply(firestore, {
112
+ ticketId: ticket.id,
113
+ from: {
114
+ uid: match.uid,
115
+ email: match.email
116
+ },
117
+ body,
118
+ dedupeKey: message.messageId || message.id
119
+ }, deps);
120
+ return {
121
+ outcome: 'replied',
122
+ requestId: ticket.id
123
+ };
124
+ }
125
+ // A reply that cannot join its request is read as a new one below.
126
+ }
127
+ const match = sender ? await findSiteCareWorkspaceForSender(firestore, (_input_findAccount = input.findAccount) != null ? _input_findAccount : findSiteCareAccount, sender) : null;
128
+ if (!match) {
129
+ if (sender) {
130
+ var _deps_email;
131
+ await ((_deps_email = deps.email) != null ? _deps_email : sendSiteCareEmail)({
132
+ key: SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY,
133
+ to: sender,
134
+ org: null,
135
+ requestId: null,
136
+ merge: {
137
+ 'sender.email': sender
138
+ },
139
+ fallback: {
140
+ subject: 'We could not match your email to an account',
141
+ text: `We got your message from ${sender}, but no workspace with Site Care has that address as a member. ` + 'Please send it again from the email address you sign in with.'
142
+ }
143
+ });
144
+ }
145
+ return {
146
+ outcome: 'unknown-sender'
147
+ };
148
+ }
149
+ if (!body && !threadSubject(message.subject)) return {
150
+ outcome: 'empty'
151
+ };
152
+ const opened = await openSiteCareRequest(firestore, {
153
+ orgId: match.orgId,
154
+ org: match.org,
155
+ hostId: null,
156
+ subject: threadSubject(message.subject) || body.split('\n')[0].slice(0, 150) || 'A change by email',
157
+ body: body || threadSubject(message.subject),
158
+ requester: {
159
+ uid: match.uid,
160
+ email: match.email
161
+ },
162
+ source: 'email',
163
+ dedupeKey: message.messageId || message.id
164
+ }, deps);
165
+ return {
166
+ outcome: 'opened',
167
+ requestId: opened.ticketId
168
+ };
169
+ }
170
+
171
+ //# sourceMappingURL=site-care-inbound.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-inbound.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n emailAddressOf,\n htmlToPlainText,\n stripQuotedHistory,\n threadSubject,\n} from '@aglyn/aglyn/app-utils/email-text'\nimport { SITE_CARE_INBOUND_LOCAL_PART } from '@aglyn/aglyn/app-utils/site-care'\nimport {\n SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY,\n type ReceivedEmail,\n} from '@aglyn/shared-util-email'\nimport {\n appendSiteCareReply,\n openSiteCareRequest,\n orgHasSiteCare,\n readSiteCareOrg,\n type SiteCareDeps,\n} from './site-care-requests'\nimport { findUserByEmailAcrossPools } from './auth-pools'\nimport { sendSiteCareEmail } from './site-care-emails'\n\n/**\n * THE SITE CARE ADDRESS (AGL-3959): `care@<inbound mail domain>`.\n *\n * An owner emails or forwards a change to the address and it becomes a Site\n * Care request on their workspace, matched by the sender's address against\n * the members of workspaces that have Site Care. A reply to any Site Care\n * email goes to `care+<requestId>@…` and joins that request's thread, when\n * the sender is a member of its workspace. A sender who matches nobody gets\n * a reply asking them to write from the address on the account; the message\n * itself is not kept.\n */\n\n/** What a received message was addressed to, of the Site Care address. */\nexport type SiteCareInboundTarget = { kind: 'new' } | { kind: 'reply'; requestId: string }\n\n/** The Site Care target among a message's recipients, or null. */\nexport function siteCareInboundTarget(\n recipients: readonly string[],\n domain: string,\n): SiteCareInboundTarget | null {\n let found: SiteCareInboundTarget | null = null\n for (const value of recipients) {\n // Validated (and lowercased) for the domain, but the local part is read\n // as written: a request id is a case-sensitive Firestore id, and\n // lowercasing `care+AbC…` would look up a ticket that does not exist.\n const address = emailAddressOf(value)\n if (!address) continue\n const raw = String(value ?? '').trim()\n const written = (/<([^<>]+)>\\s*$/.exec(raw)?.[1] ?? raw).trim()\n const at = written.lastIndexOf('@')\n if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain.toLowerCase()) continue\n const local = written.slice(0, at)\n if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {\n found = found ?? { kind: 'new' }\n continue\n }\n const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`\n if (local.toLowerCase().startsWith(prefix)) {\n const requestId = local.slice(prefix.length)\n // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape\n // is refused rather than looked up.\n if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return { kind: 'reply', requestId }\n }\n }\n return found\n}\n\nexport interface SiteCareSenderMatch {\n orgId: string\n org: Record<string, unknown>\n uid: string\n email: string\n}\n\n/** The account an address signs in with: its uid, or null when it has none. */\nexport type SiteCareAccountLookup = (email: string) => Promise<{ uid: string } | null>\n\n/**\n * Every pool, not only the project's: an owner who signs in through SSO is a\n * GCIP tenant user the project pool never returns (AGL-1122), and their mail\n * would be answered as a stranger's.\n */\nexport const findSiteCareAccount: SiteCareAccountLookup = async (email) => {\n const found = await findUserByEmailAcrossPools(email).catch(() => null)\n return found ? { uid: found.record.uid } : null\n}\n\n/**\n * The Site Care workspace a sender belongs to: the account their address\n * signs in with (in any pool), then the workspaces it is a member of, the\n * first with Site Care in force (by id, so the choice is stable).\n */\nexport async function findSiteCareWorkspaceForSender(\n firestore: FirebaseFirestore.Firestore,\n findAccount: SiteCareAccountLookup,\n sender: string,\n): Promise<SiteCareSenderMatch | null> {\n const email = emailAddressOf(sender)\n if (!email) return null\n const user = await findAccount(email).catch(() => null)\n if (!user) return null\n const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get()\n const orgIds = memberships.docs.map((doc) => doc.id).sort()\n for (const orgId of orgIds) {\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get()\n if (!member.exists) continue\n const org = await readSiteCareOrg(firestore, orgId)\n if (org && orgHasSiteCare(org)) return { orgId, org, uid: user.uid, email }\n }\n return null\n}\n\n/** The words of a message, above any quoted history. */\nexport function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string {\n const plain = (message.text?.trim() ? message.text : htmlToPlainText(message.html)).replace(/\\r\\n?/g, '\\n')\n return stripQuotedHistory(plain).trim()\n}\n\nexport type SiteCareInboundOutcome =\n | { outcome: 'opened'; requestId: string }\n | { outcome: 'replied'; requestId: string }\n | { outcome: 'unknown-sender' }\n | { outcome: 'empty' }\n\n/** Files one received message addressed to the Site Care address. */\nexport async function fileSiteCareInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n target: SiteCareInboundTarget\n message: ReceivedEmail\n /** The seam a spec replaces; every auth pool by default. */\n findAccount?: SiteCareAccountLookup\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareInboundOutcome> {\n const { message } = input\n const body = siteCareMessageBody(message)\n const sender = emailAddressOf(message.from)\n if (input.target.kind === 'reply') {\n const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get()\n const orgId = String(ticket.get('orgId') ?? '')\n const match = sender ? await findSiteCareWorkspaceForSender(firestore, input.findAccount ?? findSiteCareAccount, sender) : null\n // Only a member of the request's own workspace may add to it.\n const member =\n match && orgId\n ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists\n : false\n if (ticket.exists && member && match) {\n if (!body) return { outcome: 'empty' }\n await appendSiteCareReply(\n firestore,\n {\n ticketId: ticket.id,\n from: { uid: match.uid, email: match.email },\n body,\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'replied', requestId: ticket.id }\n }\n // A reply that cannot join its request is read as a new one below.\n }\n const match = sender ? await findSiteCareWorkspaceForSender(firestore, input.findAccount ?? findSiteCareAccount, sender) : null\n if (!match) {\n if (sender) {\n await (deps.email ?? sendSiteCareEmail)({\n key: SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY,\n to: sender,\n org: null,\n requestId: null,\n merge: { 'sender.email': sender },\n fallback: {\n subject: 'We could not match your email to an account',\n text:\n `We got your message from ${sender}, but no workspace with Site Care has that address as a member. ` +\n 'Please send it again from the email address you sign in with.',\n },\n })\n }\n return { outcome: 'unknown-sender' }\n }\n if (!body && !threadSubject(message.subject)) return { outcome: 'empty' }\n const opened = await openSiteCareRequest(\n firestore,\n {\n orgId: match.orgId,\n org: match.org,\n hostId: null,\n subject: threadSubject(message.subject) || body.split('\\n')[0].slice(0, 150) || 'A change by email',\n body: body || threadSubject(message.subject),\n requester: { uid: match.uid, email: match.email },\n source: 'email',\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'opened', requestId: opened.ticketId }\n}\n"],"names":["emailAddressOf","htmlToPlainText","stripQuotedHistory","threadSubject","SITE_CARE_INBOUND_LOCAL_PART","SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY","appendSiteCareReply","openSiteCareRequest","orgHasSiteCare","readSiteCareOrg","findUserByEmailAcrossPools","sendSiteCareEmail","siteCareInboundTarget","recipients","domain","found","value","address","raw","String","trim","written","exec","at","lastIndexOf","slice","toLowerCase","local","kind","prefix","startsWith","requestId","length","test","findSiteCareAccount","email","catch","uid","record","findSiteCareWorkspaceForSender","firestore","findAccount","sender","user","memberships","collection","doc","limit","get","orgIds","docs","map","id","sort","orgId","member","exists","org","siteCareMessageBody","message","plain","text","html","replace","fileSiteCareInboundEmail","input","deps","body","from","target","ticket","match","outcome","ticketId","dedupeKey","messageId","key","to","merge","fallback","subject","opened","hostId","split","requester","source"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,eAAe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D;IACA,mEAAmE;IACrE;IACA,MAAMmB,QAAQ7B,SAAS,MAAMH,+BAA+BC,YAAWyB,qBAAAA,MAAMxB,WAAW,YAAjBwB,qBAAqB/B,qBAAqBQ,UAAU;IAC3H,IAAI,CAAC6B,OAAO;QACV,IAAI7B,QAAQ;gBACHwB;YAAP,MAAM,EAACA,cAAAA,KAAK/B,KAAK,YAAV+B,cAAcvD,mBAAmB;gBACtCiE,KAAKvE;gBACLwE,IAAInC;gBACJe,KAAK;gBACL1B,WAAW;gBACX+C,OAAO;oBAAE,gBAAgBpC;gBAAO;gBAChCqC,UAAU;oBACRC,SAAS;oBACTnB,MACE,CAAC,yBAAyB,EAAEnB,OAAO,gEAAgE,CAAC,GACpG;gBACJ;YACF;QACF;QACA,OAAO;YAAE8B,SAAS;QAAiB;IACrC;IACA,IAAI,CAACL,QAAQ,CAAChE,cAAcwD,QAAQqB,OAAO,GAAG,OAAO;QAAER,SAAS;IAAQ;IACxE,MAAMS,SAAS,MAAM1E,oBACnBiC,WACA;QACEc,OAAOiB,MAAMjB,KAAK;QAClBG,KAAKc,MAAMd,GAAG;QACdyB,QAAQ;QACRF,SAAS7E,cAAcwD,QAAQqB,OAAO,KAAKb,KAAKgB,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC1D,KAAK,CAAC,GAAG,QAAQ;QAChF0C,MAAMA,QAAQhE,cAAcwD,QAAQqB,OAAO;QAC3CI,WAAW;YAAE/C,KAAKkC,MAAMlC,GAAG;YAAEF,OAAOoC,MAAMpC,KAAK;QAAC;QAChDkD,QAAQ;QACRX,WAAWf,QAAQgB,SAAS,IAAIhB,QAAQP,EAAE;IAC5C,GACAc;IAEF,OAAO;QAAEM,SAAS;QAAUzC,WAAWkD,OAAOR,QAAQ;IAAC;AACzD"}
@@ -0,0 +1,64 @@
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 SiteCareProject } from '@aglyn/aglyn/app-utils/site-care-project';
18
+ import { type ProjectInvoiceState } from './site-care-project-stripe';
19
+ import type { SiteCareStripeOptions } from './site-care-stripe';
20
+ /**
21
+ * SITE CARE PROJECTS IN THE DAILY RECONCILIATION (AGL-3970).
22
+ *
23
+ * The same scheduled check as extra time (`reconcileSiteCare` calls this):
24
+ * each project invoice the record holds against the Stripe invoice it
25
+ * names — status, and the amount before tax — and each Stripe invoice that
26
+ * names a project against a record that holds it. Any difference is a
27
+ * finding on `billing.siteCareReconciliation`. It compares and reports and
28
+ * never changes either side: the fix is a person's, from the project.
29
+ */
30
+ export type SiteCareProjectFindingCode = 'project-invoice-stuck' | 'project-invoice-failed' | 'project-invoice-missing' | 'project-invoice-status' | 'project-invoice-amount' | 'project-invoice-without-row' | 'project-status';
31
+ export interface SiteCareProjectFinding {
32
+ orgId: string;
33
+ projectId: string | null;
34
+ code: SiteCareProjectFindingCode;
35
+ detail: string;
36
+ }
37
+ export interface ProjectRow {
38
+ id: string;
39
+ project: SiteCareProject;
40
+ /** The status stored on the document, which every write recomputes. */
41
+ storedStatus: string;
42
+ }
43
+ /** Compares one workspace's projects with its Stripe invoices. Pure. */
44
+ export declare function compareSiteCareProjects(input: {
45
+ orgId: string;
46
+ projects: readonly ProjectRow[];
47
+ /** Every Stripe invoice the record names, plus any listed that name a project. */
48
+ invoices: ReadonlyMap<string, ProjectInvoiceState | null>;
49
+ /** Listed invoices that name one of this workspace's projects. */
50
+ listed: readonly ProjectInvoiceState[];
51
+ }): SiteCareProjectFinding[];
52
+ export interface SiteCareProjectReconcileResult {
53
+ projects: number;
54
+ findings: SiteCareProjectFinding[];
55
+ errors: string[];
56
+ }
57
+ /**
58
+ * Reads every project still open, or settled within the window, and
59
+ * compares each workspace's with Stripe.
60
+ */
61
+ export declare function reconcileSiteCareProjects(firestore: FirebaseFirestore.Firestore, input: {
62
+ nowMs: number;
63
+ stripe?: SiteCareStripeOptions;
64
+ }): Promise<SiteCareProjectReconcileResult>;