@aglyn/plugins-ai 1.0.0-beta.216 → 1.0.0-beta.218
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 +17 -17
- package/src/lib/activity/ai-activity-actions.js +2 -1
- package/src/lib/activity/ai-activity-actions.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +9 -1
- package/src/lib/jobs/ai-job-drafts.js +11 -4
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.js +1 -2
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +9 -246
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/server/ai-admin-org.js +4 -25
- package/src/lib/server/ai-admin-org.js.map +1 -1
- package/src/lib/server/ai-admin-user.js +2 -19
- package/src/lib/server/ai-admin-user.js.map +1 -1
- package/src/lib/server/ai-insight-digest-route.js +8 -1
- package/src/lib/server/ai-insight-digest-route.js.map +1 -1
- package/src/lib/usage/ai-allotment-alerts.d.ts +3 -0
- package/src/lib/usage/ai-allotment-alerts.js +12 -7
- package/src/lib/usage/ai-allotment-alerts.js.map +1 -1
- package/src/lib/usage/assist-signal-mining.js +1 -1
- package/src/lib/usage/assist-signal-mining.js.map +1 -1
|
@@ -19,7 +19,6 @@ import { emailUnverifiedResponse, firebaseAdmin, isImpersonationSession, readOrg
|
|
|
19
19
|
import { assistUsageMonth } from "../usage/assist-usage.js";
|
|
20
20
|
import { assistRefusalCounts } from "../usage/assist-refusals.js";
|
|
21
21
|
import { readOrgAiUsageByUser } from "../usage/ai-usage-by-user.js";
|
|
22
|
-
import { recordAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit";
|
|
23
22
|
import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
24
23
|
import { addonKindFromPriceId } from "@aglyn/tenant-data-admin/server/billing-addons";
|
|
25
24
|
import { orgMarginRow } from "@aglyn/aglyn/app-utils/margin-utilization";
|
|
@@ -42,15 +41,11 @@ import { composeStaffOrgAiAddon, composeStaffOrgAiMargin, composeStaffOrgAiOvera
|
|
|
42
41
|
* rollup for the month; and, when the add-on is on, ONE Stripe subscription
|
|
43
42
|
* lookup that is cached in-process — see `addonSinceFor`.
|
|
44
43
|
*
|
|
45
|
-
* ##
|
|
44
|
+
* ## No audit row
|
|
46
45
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* path — through the same writer that records a staff member opening a
|
|
51
|
-
* customer's email. No `subjectUid`: the row is about the org, and naming
|
|
52
|
-
* every uid on the leaderboard would put a row on ten people's pages for one
|
|
53
|
-
* staff glance at a table.
|
|
46
|
+
* The card loads every time the staff org page opens, so an `adminAudit` row
|
|
47
|
+
* per load recorded page views rather than decisions and buried the org's
|
|
48
|
+
* real admin actions under them. The route only reads.
|
|
54
49
|
*/ /** Generation jobs read per request; the counts are a floor past it. */ const JOBS_SCAN = 200;
|
|
55
50
|
/** How many jobs the card lists. */ const JOBS_RECENT = 10;
|
|
56
51
|
/** How many people the leaderboard names. */ const TOP_USERS = 10;
|
|
@@ -292,22 +287,6 @@ async function handler(request) {
|
|
|
292
287
|
// mirror — the same merge the margin route and the org detail read make.
|
|
293
288
|
const org = _extends({}, (_orgSnap_data = orgSnap.data()) != null ? _orgSnap_data : {}, billingSnap.exists ? billingSnap.data() : {});
|
|
294
289
|
const monthDoc = monthSnap.exists ? (_monthSnap_data = monthSnap.data()) != null ? _monthSnap_data : {} : null;
|
|
295
|
-
/*
|
|
296
|
-
* The row is written BEFORE the person-shaped read is served, and it is
|
|
297
|
-
* awaited: a card that rendered the leaderboard and then failed to
|
|
298
|
-
* record the look would be the access this collection exists to never
|
|
299
|
-
* lose. A failed write logs and still serves — the card is not a closed
|
|
300
|
-
* collection the way the delivery log is — but the order is the point.
|
|
301
|
-
*/ try {
|
|
302
|
-
await recordAdminAudit({
|
|
303
|
-
actorUid: decoded.uid,
|
|
304
|
-
action: 'org.ai-viewed',
|
|
305
|
-
target: `orgs/${orgId}/assistUsage`,
|
|
306
|
-
note: `AI card opened for ${month}`
|
|
307
|
-
});
|
|
308
|
-
} catch (error) {
|
|
309
|
-
console.error('[ai/admin/org] audit write failed', error);
|
|
310
|
-
}
|
|
311
290
|
const [jobs, users, since] = await Promise.all([
|
|
312
291
|
readOrgAiJobsSummary(db, orgId, month),
|
|
313
292
|
readOrgAiTopUsers(db, orgId, month),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-admin-org.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 isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n orgCogsInputFrom,\n pluginRequestFromWeb,\n} from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n readOrgBilling,\n} from '@aglyn/tenant-data-admin'\nimport { assistUsageMonth } from '../usage/assist-usage'\nimport { assistRefusalCounts } from '../usage/assist-refusals'\nimport { readOrgAiUsageByUser } from '../usage/ai-usage-by-user'\nimport { recordAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { addonKindFromPriceId } from '@aglyn/tenant-data-admin/server/billing-addons'\nimport { orgMarginRow } from '@aglyn/aglyn/app-utils/margin-utilization'\nimport {\n assistCogsAlertThresholdUsd,\n assistMarginMultiple,\n} from '@aglyn/aglyn/app-utils/usage-budget'\nimport {\n composeStaffOrgAiAddon,\n composeStaffOrgAiMargin,\n composeStaffOrgAiOverage,\n composeStaffOrgAiPool,\n composeStaffOrgAiTokens,\n emptyJobCounts,\n STAFF_ORG_AI_JOB_STATUSES,\n type StaffOrgAiAddon,\n type StaffOrgAiJob,\n type StaffOrgAiJobs,\n type StaffOrgAiResponse,\n type StaffOrgAiUser,\n} from '../usage/staff-org-ai'\n\n/**\n * THE STAFF AI CARD'S BACKING READ (AGL-2930).\n *\n * One request composes everything the card on the staff org page shows: the\n * add-on and when it was bought, the credit pool and its parts, the month's\n * overage and the org's own ceilings, the refusal counter, the generation\n * jobs, the per-user rollup and the margin. Staff-gated exactly as\n * `/api/admin/org-usage` is, and read-only — every access below is a `get()`.\n *\n * ## The reads, stated\n *\n * The org document and its billing mirror; this month's `assistUsage`\n * document; the newest usage rollup (for the contribution margin, the same\n * read the margin route makes); a bounded page of `aiJobs`; the per-user\n * rollup for the month; and, when the add-on is on, ONE Stripe subscription\n * lookup that is cached in-process — see `addonSinceFor`.\n *\n * ## The `access` audit row\n *\n * Opening the card reads per-user attribution, which is the one thing on it\n * that is about a person rather than a workspace. So the open is recorded to\n * `adminAudit` as an ACCESS — `org.ai-viewed`, target the org's assist usage\n * path — through the same writer that records a staff member opening a\n * customer's email. No `subjectUid`: the row is about the org, and naming\n * every uid on the leaderboard would put a row on ten people's pages for one\n * staff glance at a table.\n */\n\n/** Generation jobs read per request; the counts are a floor past it. */\nconst JOBS_SCAN = 200\n\n/** How many jobs the card lists. */\nconst JOBS_RECENT = 10\n\n/** How many people the leaderboard names. */\nconst TOP_USERS = 10\n\n/**\n * How long a Stripe answer to \"when was the add-on bought\" is kept.\n *\n * The date does not move once the item exists, and the card is opened far\n * more often than an add-on is bought, so the only cost of a stale entry is\n * a card that says \"since —\" for up to this long after a purchase. The\n * alternative — a Stripe round trip on every render — is the thing the brief\n * forbade.\n */\nconst ADDON_SINCE_TTL_MS = 15 * 60 * 1000\n\ninterface AddonSince {\n since: string | null\n sinceSource: StaffOrgAiAddon['sinceSource']\n at: number\n}\n\nconst addonSinceCache = new Map<string, AddonSince>()\n\n/** Test seam: drop every cached Stripe answer. */\nexport function resetAddonSinceCache(): void {\n addonSinceCache.clear()\n}\n\n/**\n * The instant the add-on's subscription item was created, from Stripe.\n *\n * The org document carries the add-on as a quantity (`seatAddons.aiAddon`)\n * and nothing about WHEN — the webhook mirrors items, not their dates. Stripe\n * has it as `created` on the subscription item, found by the price id the\n * add-on sells at (`addonKindFromPriceId`), so a rename or a price change\n * does not lose it.\n */\nasync function addonSinceFor(orgId: string): Promise<AddonSince> {\n const cached = addonSinceCache.get(orgId)\n if (cached && Date.now() - cached.at < ADDON_SINCE_TTL_MS) return cached\n const answer = await readAddonSince(orgId)\n addonSinceCache.set(orgId, answer)\n return answer\n}\n\nasync function readAddonSince(orgId: string): Promise<AddonSince> {\n const at = Date.now()\n const stripeKey = process.env.STRIPE_SECRET_KEY\n if (!stripeKey) return { since: null, sinceSource: 'unavailable', at }\n try {\n const customerId = (await readOrgBilling(orgId)).stripeCustomerId\n if (!customerId) return { since: null, sinceSource: 'no-subscription', at }\n const response = await fetch(\n `https://api.stripe.com/v1/subscriptions?customer=${encodeURIComponent(\n String(customerId),\n )}&status=all&limit=10`,\n { headers: { Authorization: `Bearer ${stripeKey}` } },\n )\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n console.error('[ai/admin/org] Stripe subscription lookup failed', {\n orgId,\n status: response.status,\n detail: payload?.error?.message ?? null,\n })\n return { since: null, sinceSource: 'unavailable', at }\n }\n const subscriptions = (payload?.data ?? []) as Array<{\n status?: string\n items?: { data?: Array<{ created?: number; price?: { id?: string } }> }\n }>\n // The LIVE subscription's item, when one exists: an add-on on a canceled\n // subscription is not an add-on the org has, and `hasAiAddon` already\n // says so — the date beside \"off\" would only confuse.\n const live = subscriptions.filter((subscription) =>\n isLiveSubscriptionStatus(subscription.status),\n )\n for (const subscription of live.length ? live : subscriptions) {\n for (const item of subscription.items?.data ?? []) {\n if (addonKindFromPriceId(item.price?.id) !== 'aiAddon') continue\n const created = Number(item.created)\n if (Number.isFinite(created) && created > 0) {\n return {\n since: new Date(created * 1000).toISOString(),\n sinceSource: 'stripe',\n at,\n }\n }\n }\n }\n return { since: null, sinceSource: 'stripe', at }\n } catch (error) {\n console.error('[ai/admin/org] Stripe subscription lookup threw', error)\n return { since: null, sinceSource: 'unavailable', at }\n }\n}\n\nconst toIso = (value: unknown): string | null => {\n const converted = (value as { toDate?: () => Date } | null)?.toDate?.()\n if (converted instanceof Date) return converted.toISOString()\n if (value instanceof Date) return value.toISOString()\n return null\n}\n\n/**\n * The month's generation jobs, summarized (AGL-2904's collection).\n *\n * Reads `orgs/{orgId}/aiJobs` by `createdAt` from the first instant of the\n * month, newest first, up to `JOBS_SCAN`. An org with no such collection\n * answers an empty snapshot, which is the honest \"no generation jobs yet\";\n * a read that FAILED answers `null`, which the card renders as a failure\n * rather than as an idle org. The field names are the ones `AiJob` declares\n * in `ai-jobs.types.ts`: `kind`, `status`, `creditsReserved`, `creditsSpent`,\n * `createdAt`, `createdBy`.\n */\nexport async function readOrgAiJobsSummary(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n month: string,\n): Promise<StaffOrgAiJobs | null> {\n try {\n const monthStart = new Date(`${month}-01T00:00:00.000Z`)\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('aiJobs')\n .where('createdAt', '>=', monthStart)\n .orderBy('createdAt', 'desc')\n .limit(JOBS_SCAN + 1)\n .get()\n const truncated = snapshot.docs.length > JOBS_SCAN\n const docs = truncated ? snapshot.docs.slice(0, JOBS_SCAN) : snapshot.docs\n const counts = emptyJobCounts()\n const recent: StaffOrgAiJob[] = []\n for (const doc of docs) {\n const status = String(doc.get('status') ?? '')\n if ((STAFF_ORG_AI_JOB_STATUSES as readonly string[]).includes(status)) {\n counts[status as keyof typeof counts] += 1\n }\n if (recent.length < JOBS_RECENT) {\n recent.push({\n id: doc.id,\n kind: String(doc.get('kind') ?? ''),\n status,\n creditsReserved: Number(doc.get('creditsReserved') ?? 0) || 0,\n creditsSpent: Number(doc.get('creditsSpent') ?? 0) || 0,\n createdAt: toIso(doc.get('createdAt')),\n createdBy:\n typeof doc.get('createdBy') === 'string'\n ? String(doc.get('createdBy'))\n : null,\n })\n }\n }\n return { counts, recent, truncated }\n } catch (error) {\n console.error('[ai/admin/org] jobs read failed', error)\n return null\n }\n}\n\n/**\n * The month's per-user rollup, dearest first (AGL-2928).\n *\n * `readOrgAiUsageByUser` is the one reader of\n * `orgs/{orgId}/aiUsageByUser/{uid}/months/{month}` — the customer's Usage\n * table reads through it too — joined to the roster for names and carrying\n * each person's share of the org's measured spend. The card keeps the\n * dearest `TOP_USERS`.\n */\nasync function readOrgAiTopUsers(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n month: string,\n): Promise<StaffOrgAiUser[]> {\n try {\n const usage = await readOrgAiUsageByUser(firestore, orgId, month)\n return usage.rows.slice(0, TOP_USERS).map((row) => ({\n uid: row.uid,\n name: row.name,\n credits: row.credits,\n estCostUsd: row.estCostUsd,\n share: row.share,\n requests: row.requests,\n refusals: row.refusals,\n byKind: row.byKind,\n byHost: row.byHost,\n }))\n } catch (error) {\n console.error('[ai/admin/org] per-user read failed', error)\n return []\n }\n}\n\nasync function handler(request: Request): Promise<Response> {\n const {\n method,\n query,\n headers: rawHeaders,\n } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken)\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n const orgId = String(query.orgId ?? '')\n if (!orgId) return Response.json({ error: 'Missing orgId' }, { status: 400 })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n if (!decoded['staff']) {\n return Response.json({ error: 'Staff only' }, { status: 403 })\n }\n\n const now = new Date()\n const month = assistUsageMonth(now)\n const db = firebaseAdmin.app().firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n\n const [orgSnap, billingSnap, monthSnap, rollupSnap] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n orgRef.collection('assistUsage').doc(month).get(),\n orgRef.collection('usage').orderBy('month', 'desc').limit(1).get(),\n ])\n if (!orgSnap.exists) {\n return Response.json({ error: 'No such organization' }, { status: 404 })\n }\n // Org doc FIRST so a stale inline `subscription` loses to the billing\n // mirror — the same merge the margin route and the org detail read make.\n const org = {\n ...(orgSnap.data() ?? {}),\n ...(billingSnap.exists ? billingSnap.data() : {}),\n } as Record<string, unknown>\n const monthDoc = monthSnap.exists ? (monthSnap.data() ?? {}) : null\n\n /*\n * The row is written BEFORE the person-shaped read is served, and it is\n * awaited: a card that rendered the leaderboard and then failed to\n * record the look would be the access this collection exists to never\n * lose. A failed write logs and still serves — the card is not a closed\n * collection the way the delivery log is — but the order is the point.\n */\n try {\n await recordAdminAudit({\n actorUid: decoded.uid,\n action: 'org.ai-viewed',\n target: `orgs/${orgId}/assistUsage`,\n note: `AI card opened for ${month}`,\n })\n } catch (error) {\n console.error('[ai/admin/org] audit write failed', error)\n }\n\n const [jobs, users, since] = await Promise.all([\n readOrgAiJobsSummary(db, orgId, month),\n readOrgAiTopUsers(db, orgId, month),\n addonSinceFor(orgId),\n ])\n\n const pool = composeStaffOrgAiPool(org as never, monthDoc, now)\n // The overage line is an invoice, so it is priced off what the month\n // DREW; everything below it is our bill, so it reads what the month\n // COST (AGL-3015).\n const overage = composeStaffOrgAiOverage(org as never, pool.billedUsd)\n const addon = composeStaffOrgAiAddon(org as never, {\n since: since.since,\n sinceSource: since.sinceSource,\n })\n const thresholdUsd = assistCogsAlertThresholdUsd(\n process.env.ASSIST_ORG_MONTHLY_COGS_ALERT_USD,\n )\n const rollupDoc = rollupSnap.docs[0]\n // The whole-org contribution margin, on the same row the margin\n // utilization page builds — with THIS month's live assist spend in\n // place of the figure frozen onto the rollup, as that route does.\n const contributionRow = rollupDoc\n ? orgMarginRow({\n orgId,\n name: (org['name'] as string | undefined) ?? null,\n org: org as never,\n month: String(rollupDoc.get('month') ?? rollupDoc.id),\n rollup: {\n ...orgCogsInputFrom(rollupDoc.data()),\n assistCostUsd: pool.providerUsd,\n },\n })\n : null\n const margin = composeStaffOrgAiMargin({\n org: org as never,\n pool,\n overage,\n addon,\n thresholdUsd,\n multiple: assistMarginMultiple(pool.providerUsd, thresholdUsd),\n contribution: {\n month: contributionRow?.month ?? null,\n marginPct: contributionRow?.marginPct ?? null,\n rating: contributionRow?.rating ?? null,\n },\n })\n\n const body: StaffOrgAiResponse = {\n month,\n addon,\n pool,\n overage,\n refusals: assistRefusalCounts(monthDoc?.['refusals']),\n jobs,\n users,\n margin,\n tokens: composeStaffOrgAiTokens(monthDoc),\n }\n return Response.json(body, { status: 200 })\n } catch (error) {\n // An unverifiable credential is a 401, not a fault of ours\n // (AGL-1993). Null for anything else, so a real failure keeps its 500.\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/admin/org]', error)\n return Response.json({ error: 'AI lookup failed' }, { status: 500 })\n }\n}\n\nexport { handler as GET }\n"],"names":["isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","orgCogsInputFrom","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","readOrgBilling","assistUsageMonth","assistRefusalCounts","readOrgAiUsageByUser","recordAdminAudit","invalidIdTokenResponse","addonKindFromPriceId","orgMarginRow","assistCogsAlertThresholdUsd","assistMarginMultiple","composeStaffOrgAiAddon","composeStaffOrgAiMargin","composeStaffOrgAiOverage","composeStaffOrgAiPool","composeStaffOrgAiTokens","emptyJobCounts","STAFF_ORG_AI_JOB_STATUSES","JOBS_SCAN","JOBS_RECENT","TOP_USERS","ADDON_SINCE_TTL_MS","addonSinceCache","Map","resetAddonSinceCache","clear","addonSinceFor","orgId","cached","get","Date","now","at","answer","readAddonSince","set","stripeKey","process","env","STRIPE_SECRET_KEY","since","sinceSource","customerId","stripeCustomerId","response","fetch","encodeURIComponent","String","headers","Authorization","payload","json","catch","ok","console","error","status","detail","message","subscriptions","data","live","filter","subscription","length","item","items","price","id","created","Number","isFinite","toISOString","toIso","value","converted","toDate","readOrgAiJobsSummary","firestore","month","monthStart","snapshot","collection","doc","where","orderBy","limit","truncated","docs","slice","counts","recent","includes","push","kind","creditsReserved","creditsSpent","createdAt","createdBy","readOrgAiTopUsers","usage","rows","map","row","uid","name","credits","estCostUsd","share","requests","refusals","byKind","byHost","handler","request","query","method","rawHeaders","Response","authorization","idToken","startsWith","undefined","orgSnap","monthSnap","org","rollupDoc","decoded","app","auth","verifyIdToken","email_verified","db","orgRef","billingSnap","rollupSnap","Promise","all","exists","monthDoc","actorUid","action","target","note","jobs","users","pool","overage","billedUsd","addon","thresholdUsd","ASSIST_ORG_MONTHLY_COGS_ALERT_USD","contributionRow","rollup","assistCostUsd","providerUsd","margin","multiple","contribution","marginPct","rating","body","tokens","unauthenticated","GET"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,EACzBC,gBAAgB,EAChBC,oBAAoB,QACf,sBAAqB;AAC5B,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,EACtBC,cAAc,QACT,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,mBAAmB,QAAQ,8BAA0B;AAC9D,SAASC,oBAAoB,QAAQ,+BAA2B;AAChE,SAASC,gBAAgB,QAAQ,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,mEAAmE;QACnE,kEAAkE;QAClE,MAAMgE,kBAAkB1B,YACpBtH,aAAa;YACXmB;YACA8E,IAAI,GAAGoB,YAAAA,GAAG,CAAC,OAAO,YAAXA,YAAsC;YAC7CA,KAAKA;YACL9C,OAAOhC,QAAO+E,iBAAAA,UAAUjG,GAAG,CAAC,oBAAdiG,iBAA0BA,UAAU1D,EAAE;YACpDqF,QAAQ,aACH7J,iBAAiBkI,UAAUlE,IAAI;gBAClC8F,eAAeR,KAAKS,WAAW;;QAEnC,KACA;QACJ,MAAMC,SAAShJ,wBAAwB;YACrCiH,KAAKA;YACLqB;YACAC;YACAE;YACAC;YACAO,UAAUnJ,qBAAqBwI,KAAKS,WAAW,EAAEL;YACjDQ,cAAc;gBACZ/E,KAAK,UAAEyE,mCAAAA,gBAAiBzE,KAAK,mBAAI;gBACjCgF,SAAS,WAAEP,mCAAAA,gBAAiBO,SAAS,oBAAI;gBACzCC,MAAM,WAAER,mCAAAA,gBAAiBQ,MAAM,oBAAI;YACrC;QACF;QAEA,MAAMC,OAA2B;YAC/BlF;YACAsE;YACAH;YACAC;YACArC,UAAU3G,oBAAoBwI,4BAAAA,QAAU,CAAC,WAAW;YACpDK;YACAC;YACAW;YACAM,QAAQnJ,wBAAwB4H;QAClC;QACA,OAAOrB,SAASnE,IAAI,CAAC8G,MAAM;YAAEzG,QAAQ;QAAI;IAC3C,EAAE,OAAOD,OAAO;QACd,2DAA2D;QAC3D,uEAAuE;QACvE,MAAM4G,kBAAkB7J,uBAAuBiD;QAC/C,IAAI4G,iBAAiB,OAAOA;QAC5B7G,QAAQC,KAAK,CAAC,kBAAkBA;QAChC,OAAO+D,SAASnE,IAAI,CAAC;YAAEI,OAAO;QAAmB,GAAG;YAAEC,QAAQ;QAAI;IACpE;AACF;AAEA,SAASyD,WAAWmD,GAAG,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-admin-org.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 isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n orgCogsInputFrom,\n pluginRequestFromWeb,\n} from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n readOrgBilling,\n} from '@aglyn/tenant-data-admin'\nimport { assistUsageMonth } from '../usage/assist-usage'\nimport { assistRefusalCounts } from '../usage/assist-refusals'\nimport { readOrgAiUsageByUser } from '../usage/ai-usage-by-user'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { addonKindFromPriceId } from '@aglyn/tenant-data-admin/server/billing-addons'\nimport { orgMarginRow } from '@aglyn/aglyn/app-utils/margin-utilization'\nimport {\n assistCogsAlertThresholdUsd,\n assistMarginMultiple,\n} from '@aglyn/aglyn/app-utils/usage-budget'\nimport {\n composeStaffOrgAiAddon,\n composeStaffOrgAiMargin,\n composeStaffOrgAiOverage,\n composeStaffOrgAiPool,\n composeStaffOrgAiTokens,\n emptyJobCounts,\n STAFF_ORG_AI_JOB_STATUSES,\n type StaffOrgAiAddon,\n type StaffOrgAiJob,\n type StaffOrgAiJobs,\n type StaffOrgAiResponse,\n type StaffOrgAiUser,\n} from '../usage/staff-org-ai'\n\n/**\n * THE STAFF AI CARD'S BACKING READ (AGL-2930).\n *\n * One request composes everything the card on the staff org page shows: the\n * add-on and when it was bought, the credit pool and its parts, the month's\n * overage and the org's own ceilings, the refusal counter, the generation\n * jobs, the per-user rollup and the margin. Staff-gated exactly as\n * `/api/admin/org-usage` is, and read-only — every access below is a `get()`.\n *\n * ## The reads, stated\n *\n * The org document and its billing mirror; this month's `assistUsage`\n * document; the newest usage rollup (for the contribution margin, the same\n * read the margin route makes); a bounded page of `aiJobs`; the per-user\n * rollup for the month; and, when the add-on is on, ONE Stripe subscription\n * lookup that is cached in-process — see `addonSinceFor`.\n *\n * ## No audit row\n *\n * The card loads every time the staff org page opens, so an `adminAudit` row\n * per load recorded page views rather than decisions and buried the org's\n * real admin actions under them. The route only reads.\n */\n\n/** Generation jobs read per request; the counts are a floor past it. */\nconst JOBS_SCAN = 200\n\n/** How many jobs the card lists. */\nconst JOBS_RECENT = 10\n\n/** How many people the leaderboard names. */\nconst TOP_USERS = 10\n\n/**\n * How long a Stripe answer to \"when was the add-on bought\" is kept.\n *\n * The date does not move once the item exists, and the card is opened far\n * more often than an add-on is bought, so the only cost of a stale entry is\n * a card that says \"since —\" for up to this long after a purchase. The\n * alternative — a Stripe round trip on every render — is the thing the brief\n * forbade.\n */\nconst ADDON_SINCE_TTL_MS = 15 * 60 * 1000\n\ninterface AddonSince {\n since: string | null\n sinceSource: StaffOrgAiAddon['sinceSource']\n at: number\n}\n\nconst addonSinceCache = new Map<string, AddonSince>()\n\n/** Test seam: drop every cached Stripe answer. */\nexport function resetAddonSinceCache(): void {\n addonSinceCache.clear()\n}\n\n/**\n * The instant the add-on's subscription item was created, from Stripe.\n *\n * The org document carries the add-on as a quantity (`seatAddons.aiAddon`)\n * and nothing about WHEN — the webhook mirrors items, not their dates. Stripe\n * has it as `created` on the subscription item, found by the price id the\n * add-on sells at (`addonKindFromPriceId`), so a rename or a price change\n * does not lose it.\n */\nasync function addonSinceFor(orgId: string): Promise<AddonSince> {\n const cached = addonSinceCache.get(orgId)\n if (cached && Date.now() - cached.at < ADDON_SINCE_TTL_MS) return cached\n const answer = await readAddonSince(orgId)\n addonSinceCache.set(orgId, answer)\n return answer\n}\n\nasync function readAddonSince(orgId: string): Promise<AddonSince> {\n const at = Date.now()\n const stripeKey = process.env.STRIPE_SECRET_KEY\n if (!stripeKey) return { since: null, sinceSource: 'unavailable', at }\n try {\n const customerId = (await readOrgBilling(orgId)).stripeCustomerId\n if (!customerId) return { since: null, sinceSource: 'no-subscription', at }\n const response = await fetch(\n `https://api.stripe.com/v1/subscriptions?customer=${encodeURIComponent(\n String(customerId),\n )}&status=all&limit=10`,\n { headers: { Authorization: `Bearer ${stripeKey}` } },\n )\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n console.error('[ai/admin/org] Stripe subscription lookup failed', {\n orgId,\n status: response.status,\n detail: payload?.error?.message ?? null,\n })\n return { since: null, sinceSource: 'unavailable', at }\n }\n const subscriptions = (payload?.data ?? []) as Array<{\n status?: string\n items?: { data?: Array<{ created?: number; price?: { id?: string } }> }\n }>\n // The LIVE subscription's item, when one exists: an add-on on a canceled\n // subscription is not an add-on the org has, and `hasAiAddon` already\n // says so — the date beside \"off\" would only confuse.\n const live = subscriptions.filter((subscription) =>\n isLiveSubscriptionStatus(subscription.status),\n )\n for (const subscription of live.length ? live : subscriptions) {\n for (const item of subscription.items?.data ?? []) {\n if (addonKindFromPriceId(item.price?.id) !== 'aiAddon') continue\n const created = Number(item.created)\n if (Number.isFinite(created) && created > 0) {\n return {\n since: new Date(created * 1000).toISOString(),\n sinceSource: 'stripe',\n at,\n }\n }\n }\n }\n return { since: null, sinceSource: 'stripe', at }\n } catch (error) {\n console.error('[ai/admin/org] Stripe subscription lookup threw', error)\n return { since: null, sinceSource: 'unavailable', at }\n }\n}\n\nconst toIso = (value: unknown): string | null => {\n const converted = (value as { toDate?: () => Date } | null)?.toDate?.()\n if (converted instanceof Date) return converted.toISOString()\n if (value instanceof Date) return value.toISOString()\n return null\n}\n\n/**\n * The month's generation jobs, summarized (AGL-2904's collection).\n *\n * Reads `orgs/{orgId}/aiJobs` by `createdAt` from the first instant of the\n * month, newest first, up to `JOBS_SCAN`. An org with no such collection\n * answers an empty snapshot, which is the honest \"no generation jobs yet\";\n * a read that FAILED answers `null`, which the card renders as a failure\n * rather than as an idle org. The field names are the ones `AiJob` declares\n * in `ai-jobs.types.ts`: `kind`, `status`, `creditsReserved`, `creditsSpent`,\n * `createdAt`, `createdBy`.\n */\nexport async function readOrgAiJobsSummary(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n month: string,\n): Promise<StaffOrgAiJobs | null> {\n try {\n const monthStart = new Date(`${month}-01T00:00:00.000Z`)\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection('aiJobs')\n .where('createdAt', '>=', monthStart)\n .orderBy('createdAt', 'desc')\n .limit(JOBS_SCAN + 1)\n .get()\n const truncated = snapshot.docs.length > JOBS_SCAN\n const docs = truncated ? snapshot.docs.slice(0, JOBS_SCAN) : snapshot.docs\n const counts = emptyJobCounts()\n const recent: StaffOrgAiJob[] = []\n for (const doc of docs) {\n const status = String(doc.get('status') ?? '')\n if ((STAFF_ORG_AI_JOB_STATUSES as readonly string[]).includes(status)) {\n counts[status as keyof typeof counts] += 1\n }\n if (recent.length < JOBS_RECENT) {\n recent.push({\n id: doc.id,\n kind: String(doc.get('kind') ?? ''),\n status,\n creditsReserved: Number(doc.get('creditsReserved') ?? 0) || 0,\n creditsSpent: Number(doc.get('creditsSpent') ?? 0) || 0,\n createdAt: toIso(doc.get('createdAt')),\n createdBy:\n typeof doc.get('createdBy') === 'string'\n ? String(doc.get('createdBy'))\n : null,\n })\n }\n }\n return { counts, recent, truncated }\n } catch (error) {\n console.error('[ai/admin/org] jobs read failed', error)\n return null\n }\n}\n\n/**\n * The month's per-user rollup, dearest first (AGL-2928).\n *\n * `readOrgAiUsageByUser` is the one reader of\n * `orgs/{orgId}/aiUsageByUser/{uid}/months/{month}` — the customer's Usage\n * table reads through it too — joined to the roster for names and carrying\n * each person's share of the org's measured spend. The card keeps the\n * dearest `TOP_USERS`.\n */\nasync function readOrgAiTopUsers(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n month: string,\n): Promise<StaffOrgAiUser[]> {\n try {\n const usage = await readOrgAiUsageByUser(firestore, orgId, month)\n return usage.rows.slice(0, TOP_USERS).map((row) => ({\n uid: row.uid,\n name: row.name,\n credits: row.credits,\n estCostUsd: row.estCostUsd,\n share: row.share,\n requests: row.requests,\n refusals: row.refusals,\n byKind: row.byKind,\n byHost: row.byHost,\n }))\n } catch (error) {\n console.error('[ai/admin/org] per-user read failed', error)\n return []\n }\n}\n\nasync function handler(request: Request): Promise<Response> {\n const {\n method,\n query,\n headers: rawHeaders,\n } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken)\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n const orgId = String(query.orgId ?? '')\n if (!orgId) return Response.json({ error: 'Missing orgId' }, { status: 400 })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n if (!decoded['staff']) {\n return Response.json({ error: 'Staff only' }, { status: 403 })\n }\n\n const now = new Date()\n const month = assistUsageMonth(now)\n const db = firebaseAdmin.app().firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n\n const [orgSnap, billingSnap, monthSnap, rollupSnap] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n orgRef.collection('assistUsage').doc(month).get(),\n orgRef.collection('usage').orderBy('month', 'desc').limit(1).get(),\n ])\n if (!orgSnap.exists) {\n return Response.json({ error: 'No such organization' }, { status: 404 })\n }\n // Org doc FIRST so a stale inline `subscription` loses to the billing\n // mirror — the same merge the margin route and the org detail read make.\n const org = {\n ...(orgSnap.data() ?? {}),\n ...(billingSnap.exists ? billingSnap.data() : {}),\n } as Record<string, unknown>\n const monthDoc = monthSnap.exists ? (monthSnap.data() ?? {}) : null\n\n const [jobs, users, since] = await Promise.all([\n readOrgAiJobsSummary(db, orgId, month),\n readOrgAiTopUsers(db, orgId, month),\n addonSinceFor(orgId),\n ])\n\n const pool = composeStaffOrgAiPool(org as never, monthDoc, now)\n // The overage line is an invoice, so it is priced off what the month\n // DREW; everything below it is our bill, so it reads what the month\n // COST (AGL-3015).\n const overage = composeStaffOrgAiOverage(org as never, pool.billedUsd)\n const addon = composeStaffOrgAiAddon(org as never, {\n since: since.since,\n sinceSource: since.sinceSource,\n })\n const thresholdUsd = assistCogsAlertThresholdUsd(\n process.env.ASSIST_ORG_MONTHLY_COGS_ALERT_USD,\n )\n const rollupDoc = rollupSnap.docs[0]\n // The whole-org contribution margin, on the same row the margin\n // utilization page builds — with THIS month's live assist spend in\n // place of the figure frozen onto the rollup, as that route does.\n const contributionRow = rollupDoc\n ? orgMarginRow({\n orgId,\n name: (org['name'] as string | undefined) ?? null,\n org: org as never,\n month: String(rollupDoc.get('month') ?? rollupDoc.id),\n rollup: {\n ...orgCogsInputFrom(rollupDoc.data()),\n assistCostUsd: pool.providerUsd,\n },\n })\n : null\n const margin = composeStaffOrgAiMargin({\n org: org as never,\n pool,\n overage,\n addon,\n thresholdUsd,\n multiple: assistMarginMultiple(pool.providerUsd, thresholdUsd),\n contribution: {\n month: contributionRow?.month ?? null,\n marginPct: contributionRow?.marginPct ?? null,\n rating: contributionRow?.rating ?? null,\n },\n })\n\n const body: StaffOrgAiResponse = {\n month,\n addon,\n pool,\n overage,\n refusals: assistRefusalCounts(monthDoc?.['refusals']),\n jobs,\n users,\n margin,\n tokens: composeStaffOrgAiTokens(monthDoc),\n }\n return Response.json(body, { status: 200 })\n } catch (error) {\n // An unverifiable credential is a 401, not a fault of ours\n // (AGL-1993). Null for anything else, so a real failure keeps its 500.\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/admin/org]', error)\n return Response.json({ error: 'AI lookup failed' }, { status: 500 })\n }\n}\n\nexport { handler as GET }\n"],"names":["isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","orgCogsInputFrom","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","readOrgBilling","assistUsageMonth","assistRefusalCounts","readOrgAiUsageByUser","invalidIdTokenResponse","addonKindFromPriceId","orgMarginRow","assistCogsAlertThresholdUsd","assistMarginMultiple","composeStaffOrgAiAddon","composeStaffOrgAiMargin","composeStaffOrgAiOverage","composeStaffOrgAiPool","composeStaffOrgAiTokens","emptyJobCounts","STAFF_ORG_AI_JOB_STATUSES","JOBS_SCAN","JOBS_RECENT","TOP_USERS","ADDON_SINCE_TTL_MS","addonSinceCache","Map","resetAddonSinceCache","clear","addonSinceFor","orgId","cached","get","Date","now","at","answer","readAddonSince","set","stripeKey","process","env","STRIPE_SECRET_KEY","since","sinceSource","customerId","stripeCustomerId","response","fetch","encodeURIComponent","String","headers","Authorization","payload","json","catch","ok","console","error","status","detail","message","subscriptions","data","live","filter","subscription","length","item","items","price","id","created","Number","isFinite","toISOString","toIso","value","converted","toDate","readOrgAiJobsSummary","firestore","month","monthStart","snapshot","collection","doc","where","orderBy","limit","truncated","docs","slice","counts","recent","includes","push","kind","creditsReserved","creditsSpent","createdAt","createdBy","readOrgAiTopUsers","usage","rows","map","row","uid","name","credits","estCostUsd","share","requests","refusals","byKind","byHost","handler","request","query","method","rawHeaders","Response","authorization","idToken","startsWith","undefined","orgSnap","monthSnap","org","rollupDoc","decoded","app","auth","verifyIdToken","email_verified","db","orgRef","billingSnap","rollupSnap","Promise","all","exists","monthDoc","jobs","users","pool","overage","billedUsd","addon","thresholdUsd","ASSIST_ORG_MONTHLY_COGS_ALERT_USD","contributionRow","rollup","assistCostUsd","providerUsd","margin","multiple","contribution","marginPct","rating","body","tokens","unauthenticated","GET"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,G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ifiedResponse, firebaseAdmin, isImpersonationSession } from "@aglyn/tenant-data-admin";
|
|
18
18
|
import { readUserAiUsageMonths } from "../usage/ai-usage-by-user.js";
|
|
19
|
-
import { recordAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit";
|
|
20
19
|
import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
21
20
|
/**
|
|
22
21
|
* ONE ACCOUNT'S AI USAGE ACROSS ORGANIZATIONS (AGL-2928) — the staff user
|
|
@@ -29,9 +28,8 @@ import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token
|
|
|
29
28
|
* person has left is not listed, and its months expire on the retention
|
|
30
29
|
* window.
|
|
31
30
|
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* account, and that is exactly the row their page exists to show.
|
|
31
|
+
* Read only, and not audited: the card loads with every open of the staff
|
|
32
|
+
* user page, the same reason the org card writes no row.
|
|
35
33
|
*/ /** The most workspaces one account is walked across. */ const MAX_ORGS = 50;
|
|
36
34
|
async function handler(request) {
|
|
37
35
|
var _headers_authorization, _query_uid;
|
|
@@ -71,21 +69,6 @@ async function handler(request) {
|
|
|
71
69
|
}
|
|
72
70
|
const firestore = firebaseAdmin.app().firestore();
|
|
73
71
|
const reverse = await firestore.collection('users').doc(uid).collection('orgs').limit(MAX_ORGS).get();
|
|
74
|
-
// Recorded BEFORE the person-shaped read is served, and awaited, for
|
|
75
|
-
// the reason the org card gives: a card that rendered and then failed
|
|
76
|
-
// to record the look would be the access this collection exists to
|
|
77
|
-
// never lose.
|
|
78
|
-
try {
|
|
79
|
-
await recordAdminAudit({
|
|
80
|
-
actorUid: decoded.uid,
|
|
81
|
-
action: 'user.ai-usage-viewed',
|
|
82
|
-
target: `users/${uid}`,
|
|
83
|
-
subjectUid: uid,
|
|
84
|
-
note: `AI usage opened across ${reverse.size} workspace(s)`
|
|
85
|
-
});
|
|
86
|
-
} catch (error) {
|
|
87
|
-
console.error('[ai/admin/user] audit write failed', error);
|
|
88
|
-
}
|
|
89
72
|
const rows = [];
|
|
90
73
|
for (const entry of reverse.docs){
|
|
91
74
|
const months = await readUserAiUsageMonths(firestore, entry.id, uid);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-admin-user.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 { pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n} from '@aglyn/tenant-data-admin'\nimport { readUserAiUsageMonths } from '../usage/ai-usage-by-user'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-admin-user.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 { pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n} from '@aglyn/tenant-data-admin'\nimport { readUserAiUsageMonths } from '../usage/ai-usage-by-user'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\n\n/**\n * ONE ACCOUNT'S AI USAGE ACROSS ORGANIZATIONS (AGL-2928) — the staff user\n * page's card, beside `admin/users/detail`.\n *\n * Walks the account's reverse index of memberships, the same read the detail\n * route makes, and lists each workspace's months for this uid newest first.\n * A membership walk rather than a collection-group query, so the card works\n * the moment it ships and needs no index deployed first; a workspace the\n * person has left is not listed, and its months expire on the retention\n * window.\n *\n * Read only, and not audited: the card loads with every open of the staff\n * user page, the same reason the org card writes no row.\n */\n\n/** The most workspaces one account is walked across. */\nconst MAX_ORGS = 50\n\nexport interface StaffUserAiUsageRow {\n orgId: string\n orgName: string | null\n slug: string | null\n month: string\n credits: number\n requests: number\n refusals: number\n}\n\nasync function handler(request: Request): Promise<Response> {\n const { method, query, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n const uid = String(query.uid ?? '').trim()\n if (!uid) return Response.json({ error: 'Missing uid' }, { status: 400 })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n if (!decoded['staff']) {\n return Response.json({ error: 'Staff only' }, { status: 403 })\n }\n const firestore = firebaseAdmin.app().firestore()\n const reverse = await firestore\n .collection('users')\n .doc(uid)\n .collection('orgs')\n .limit(MAX_ORGS)\n .get()\n\n const rows: StaffUserAiUsageRow[] = []\n for (const entry of reverse.docs) {\n const months = await readUserAiUsageMonths(firestore, entry.id, uid)\n for (const month of months) {\n rows.push({\n orgId: entry.id,\n orgName: typeof entry.get('orgName') === 'string' ? String(entry.get('orgName')) : null,\n slug: typeof entry.get('slug') === 'string' ? String(entry.get('slug')) : null,\n month: month.month,\n credits: month.credits,\n requests: month.requests,\n refusals: month.refusals,\n })\n }\n }\n // Newest month first, dearest workspace first within it.\n rows.sort(\n (a, b) => b.month.localeCompare(a.month) || b.credits - a.credits,\n )\n return Response.json(\n { uid, rows, truncated: reverse.size >= MAX_ORGS },\n { status: 200 },\n )\n } catch (error) {\n // An unverifiable credential is a 401, not a fault of ours\n // (AGL-1993). Null for anything else, so a real failure keeps its 500.\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/admin/user]', error)\n return Response.json({ error: 'AI usage lookup failed' }, { status: 500 })\n }\n}\n\nexport { handler as GET }\n"],"names":["pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","readUserAiUsageMonths","invalidIdTokenResponse","MAX_ORGS","handler","request","headers","query","method","rawHeaders","Response","json","error","status","authorization","idToken","startsWith","slice","length","undefined","uid","String","trim","decoded","app","auth","verifyIdToken","email_verified","firestore","reverse","collection","doc","limit","get","rows","entry","docs","months","id","month","push","orgId","orgName","slug","credits","requests","refusals","sort","a","b","localeCompare","truncated","size","unauthenticated","console","GET"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,sBAAqB;AAC1D,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,qBAAqB,QAAQ,+BAA2B;AACjE,SAASC,sBAAsB,QAAQ,mDAAkD;AAEzF;;;;;;;;;;;;;CAaC,GAED,sDAAsD,GACtD,MAAMC,WAAW;AAYjB,eAAeC,QAAQC,OAAgB;QAMfC,wBAKHC;IAVnB,MAAM,EAAEC,MAAM,EAAED,KAAK,EAAED,SAASG,UAAU,EAAE,GAAG,MAAMZ,qBAAqBQ;IAC1E,MAAMC,UAAUG;IAChB,IAAID,WAAW,OAAO;QACpB,OAAOE,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAqB,GAAG;YAAEC,QAAQ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AAMF,GAAG,CAAC,YAAY,WAAWZ,OAAOc,MAAMF,GAAG,CAAC,WAAW;oBAC1EM,OAAOA,MAAMA,KAAK;oBAClBK,SAASL,MAAMK,OAAO;oBACtBC,UAAUN,MAAMM,QAAQ;oBACxBC,UAAUP,MAAMO,QAAQ;gBAC1B;YACF;QACF;QACA,yDAAyD;QACzDZ,KAAKa,IAAI,CACP,CAACC,GAAGC,IAAMA,EAAEV,KAAK,CAACW,aAAa,CAACF,EAAET,KAAK,KAAKU,EAAEL,OAAO,GAAGI,EAAEJ,OAAO;QAEnE,OAAOlC,SAASC,IAAI,CAClB;YAAES;YAAKc;YAAMiB,WAAWtB,QAAQuB,IAAI,IAAIjD;QAAS,GACjD;YAAEU,QAAQ;QAAI;IAElB,EAAE,OAAOD,OAAO;QACd,2DAA2D;QAC3D,uEAAuE;QACvE,MAAMyC,kBAAkBnD,uBAAuBU;QAC/C,IAAIyC,iBAAiB,OAAOA;QAC5BC,QAAQ1C,KAAK,CAAC,mBAAmBA;QACjC,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAyB,GAAG;YAAEC,QAAQ;QAAI;IAC1E;AACF;AAEA,SAAST,WAAWmD,GAAG,GAAE"}
|
|
@@ -19,6 +19,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
19
19
|
// and the jobs it creates are held by the same pause on the beat.
|
|
20
20
|
import { writeCronBeat } from "@aglyn/aglyn/app-utils/health-report";
|
|
21
21
|
import { rateLimitedRetryAtMs, sendEmail } from "@aglyn/shared-util-email";
|
|
22
|
+
import { withoutMailWithheldAccounts } from "@aglyn/tenant-data-admin/server/account-mail";
|
|
22
23
|
import { filterSuppressedEmails } from "@aglyn/tenant-data-admin/server/email-suppression";
|
|
23
24
|
import { meterPlatformEmail } from "@aglyn/tenant-data-admin/server/email-metering";
|
|
24
25
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
@@ -95,7 +96,13 @@ import { runAiInsightDigestSweep } from "../insights/ai-insight-digest.js";
|
|
|
95
96
|
firestore,
|
|
96
97
|
now: new Date(),
|
|
97
98
|
flagValue: flags['release_ai_generative'],
|
|
98
|
-
|
|
99
|
+
// The digest's audience: a locked or disabled account is not told
|
|
100
|
+
// (AGL-3418).
|
|
101
|
+
listMembers: async (orgId)=>{
|
|
102
|
+
const members = await listOrgMembers(orgId);
|
|
103
|
+
const reachable = new Set(await withoutMailWithheldAccounts(members.map((member)=>member.$id)));
|
|
104
|
+
return members.filter((member)=>reachable.has(member.$id));
|
|
105
|
+
},
|
|
99
106
|
mayGenerate: (orgId, hostId, member)=>memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'),
|
|
100
107
|
paused: async (orgId)=>Boolean(await featureLockdownRefusal({
|
|
101
108
|
feature: 'ai-generate',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-insight-digest-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: exempt — server-internal cron (x-cron-secret) with no user\n// caller; it asks each workspace's ai-generate pause before it creates a job,\n// and the jobs it creates are held by the same pause on the beat.\n\nimport { writeCronBeat } from '@aglyn/aglyn/app-utils/health-report'\nimport { rateLimitedRetryAtMs, sendEmail } from '@aglyn/shared-util-email'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { featureLockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport { listOrgMembers, memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { getServerReleaseFlagValues } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { safeEqual } from '@aglyn/tenant-data-admin/server/safe-equal'\nimport {\n AI_INSIGHTS_DIGEST_CRON_ID,\n runAiInsightDigestSweep,\n type AiInsightDigestDeps,\n} from '../insights/ai-insight-digest'\n\n/**\n * The weekly insights' scheduled route (AGL-2915):\n * `POST /api/admin/ai-insights-digest`.\n *\n * Cloud Scheduler calls it at 06:00 and 14:00 UTC through\n * `consoleAiInsightsDigest` in `cloud/functions`, on the console's\n * `CRON_SECRET`: 501 while the secret is unset, 401 without it. Monday's\n * first run makes the week's digests, which the AI jobs beat then writes, and\n * every run after it delivers what is written — see `ai-insight-digest.ts`.\n * `/api/admin/` is the path because the console's edge lets the cron secret's\n * header through there. It stamps `ai-insights-digest` for\n * `/api/health/crons` on every authorized call.\n */\nexport async function POST(request: Request): Promise<Response> {\n if (request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const secret = process.env.CRON_SECRET\n if (!secret) {\n return Response.json({ error: 'The weekly insights are not configured (CRON_SECRET).' }, { status: 501 })\n }\n if (\n !safeEqual(request.headers.get('x-cron-secret'), secret) &&\n !safeEqual(request.headers.get('authorization'), `Bearer ${secret}`)\n ) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n const firestore = firebaseAdmin.app().firestore()\n // The inventory row's id, written out: `cron-beat-wiring.spec.ts` finds a\n // job's stamp by the quoted id beside the call.\n await writeCronBeat(firestore, 'ai-insights-digest' satisfies typeof AI_INSIGHTS_DIGEST_CRON_ID)\n\n let cursor: string | null = null\n try {\n const body = (await request.json()) as { cursor?: unknown } | null\n const raw = body?.cursor\n cursor = typeof raw === 'string' && raw && !raw.includes('/') ? raw : null\n } catch {\n // A bodyless POST is the first call of a run.\n }\n\n try {\n // The platform switch holds the whole run, as it holds the jobs beat.\n if (await featureLockdownRefusal({ feature: 'ai-generate' })) {\n return Response.json({ held: true, done: true, nextCursor: null }, { status: 200 })\n }\n const flags = await getServerReleaseFlagValues()\n const deps: AiInsightDigestDeps = {\n firestore,\n now: new Date(),\n flagValue: flags['release_ai_generative'],\n listMembers: listOrgMembers,\n mayGenerate: (orgId, hostId, member) => memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'),\n paused: async (orgId) => Boolean(await featureLockdownRefusal({ feature: 'ai-generate', orgId })),\n notify: (uid, payload) => notifyUsers([uid], { type: 'content.insightsDigest', ...payload }),\n send: async (email) => {\n const recipients = await filterSuppressedEmails([email.to], firestore)\n if (!recipients.length) return { sent: false, rateLimited: false }\n // The `ai-insights-digest` system email (AGL-3367), in the org's brand.\n const content = await renderSystemEmailContent(\n 'ai-insights-digest',\n { 'site.name': email.siteName, 'digest.body': email.text },\n systemEmailBrand(email.org),\n { subject: email.subject, text: email.text },\n )\n const result = await sendEmail({\n to: recipients,\n ...content,\n fromName: email.fromName,\n context: 'ai-insights-digest',\n priority: 'bulk',\n })\n if (result.sent) {\n await meterPlatformEmail().catch(() => undefined)\n return { sent: true, rateLimited: false }\n }\n return { sent: false, rateLimited: rateLimitedRetryAtMs(result) !== null }\n },\n // An email link must be absolute; with no console URL configured the\n // digest says where to look without one.\n consoleOrigin: (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, ''),\n }\n const report = await runAiInsightDigestSweep(deps, { cursor })\n return Response.json(report, { status: 200 })\n } catch (error) {\n console.error('ai insights digest run failed', error)\n return Response.json({ error: 'The weekly insights run failed' }, { status: 500 })\n }\n}\n"],"names":["writeCronBeat","rateLimitedRetryAtMs","sendEmail","filterSuppressedEmails","meterPlatformEmail","firebaseAdmin","featureLockdownRefusal","notifyUsers","renderSystemEmailContent","systemEmailBrand","listOrgMembers","memberHasPermissionOnHost","getServerReleaseFlagValues","safeEqual","runAiInsightDigestSweep","POST","request","method","Response","json","error","status","secret","process","env","CRON_SECRET","headers","get","firestore","app","cursor","body","raw","includes","feature","held","done","nextCursor","flags","deps","now","Date","flagValue","listMembers","mayGenerate","orgId","hostId","member","paused","Boolean","notify","uid","payload","type","send","email","recipients","to","length","sent","rateLimited","content","siteName","text","org","subject","result","fromName","context","priority","catch","undefined","consoleOrigin","NEXT_PUBLIC_CONSOLE_URL","trim","replace","report","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,2EAA2E;AAC3E,8EAA8E;AAC9E,kEAAkE;AAElE,SAASA,aAAa,QAAQ,uCAAsC;AACpE,SAASC,oBAAoB,EAAEC,SAAS,QAAQ,2BAA0B;AAC1E,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,cAAc,EAAEC,yBAAyB,QAAQ,gDAA+C;AACzG,SAASC,0BAA0B,QAAQ,gDAA+C;AAC1F,SAASC,SAAS,QAAQ,6CAA4C;AACtE,SAEEC,uBAAuB,QAElB,mCAA+B;AAEtC;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,KAAKC,OAAgB;IACzC,IAAIA,QAAQC,MAAM,KAAK,QAAQ;QAC7B,OAAOC,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAqB,GAAG;YAAEC,QAAQ;QAAI;IACtE;IACA,MAAMC,SAASC,QAAQC,GAAG,CAACC,WAAW;IACtC,IAAI,CAACH,QAAQ;QACX,OAAOJ,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAwD,GAA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aAAa,MAAMrD,uBAAuB;oBAACoD,MAAME,EAAE;iBAAC,EAAE7B;gBAC5D,IAAI,CAAC4B,WAAWE,MAAM,EAAE,OAAO;oBAAEC,MAAM;oBAAOC,aAAa;gBAAM;gBACjE,wEAAwE;gBACxE,MAAMC,UAAU,MAAMrD,yBACpB,sBACA;oBAAE,aAAa+C,MAAMO,QAAQ;oBAAE,eAAeP,MAAMQ,IAAI;gBAAC,GACzDtD,iBAAiB8C,MAAMS,GAAG,GAC1B;oBAAEC,SAASV,MAAMU,OAAO;oBAAEF,MAAMR,MAAMQ,IAAI;gBAAC;gBAE7C,MAAMG,SAAS,MAAMhE,UAAU;oBAC7BuD,IAAID;mBACDK;oBACHM,UAAUZ,MAAMY,QAAQ;oBACxBC,SAAS;oBACTC,UAAU;;gBAEZ,IAAIH,OAAOP,IAAI,EAAE;oBACf,MAAMvD,qBAAqBkE,KAAK,CAAC,IAAMC;oBACvC,OAAO;wBAAEZ,MAAM;wBAAMC,aAAa;oBAAM;gBAC1C;gBACA,OAAO;oBAAED,MAAM;oBAAOC,aAAa3D,qBAAqBiE,YAAY;gBAAK;YAC3E;YACA,qEAAqE;YACrE,yCAAyC;YACzCM,eAAe,EAACjD,uCAAAA,QAAQC,GAAG,CAACiD,uBAAuB,YAAnClD,uCAAuC,IAAImD,IAAI,GAAGC,OAAO,CAAC,QAAQ;QACpF;QACA,MAAMC,SAAS,MAAM9D,wBAAwByB,MAAM;YAAET;QAAO;QAC5D,OAAOZ,SAASC,IAAI,CAACyD,QAAQ;YAAEvD,QAAQ;QAAI;IAC7C,EAAE,OAAOD,OAAO;QACdyD,QAAQzD,KAAK,CAAC,iCAAiCA;QAC/C,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiC,GAAG;YAAEC,QAAQ;QAAI;IAClF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-insight-digest-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: exempt — server-internal cron (x-cron-secret) with no user\n// caller; it asks each workspace's ai-generate pause before it creates a job,\n// and the jobs it creates are held by the same pause on the beat.\n\nimport { writeCronBeat } from '@aglyn/aglyn/app-utils/health-report'\nimport { rateLimitedRetryAtMs, sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { featureLockdownRefusal } from '@aglyn/tenant-data-admin/server/lockdown'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport { listOrgMembers, memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { getServerReleaseFlagValues } from '@aglyn/tenant-data-admin/server/release-flags'\nimport { safeEqual } from '@aglyn/tenant-data-admin/server/safe-equal'\nimport {\n AI_INSIGHTS_DIGEST_CRON_ID,\n runAiInsightDigestSweep,\n type AiInsightDigestDeps,\n} from '../insights/ai-insight-digest'\n\n/**\n * The weekly insights' scheduled route (AGL-2915):\n * `POST /api/admin/ai-insights-digest`.\n *\n * Cloud Scheduler calls it at 06:00 and 14:00 UTC through\n * `consoleAiInsightsDigest` in `cloud/functions`, on the console's\n * `CRON_SECRET`: 501 while the secret is unset, 401 without it. Monday's\n * first run makes the week's digests, which the AI jobs beat then writes, and\n * every run after it delivers what is written — see `ai-insight-digest.ts`.\n * `/api/admin/` is the path because the console's edge lets the cron secret's\n * header through there. It stamps `ai-insights-digest` for\n * `/api/health/crons` on every authorized call.\n */\nexport async function POST(request: Request): Promise<Response> {\n if (request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const secret = process.env.CRON_SECRET\n if (!secret) {\n return Response.json({ error: 'The weekly insights are not configured (CRON_SECRET).' }, { status: 501 })\n }\n if (\n !safeEqual(request.headers.get('x-cron-secret'), secret) &&\n !safeEqual(request.headers.get('authorization'), `Bearer ${secret}`)\n ) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n const firestore = firebaseAdmin.app().firestore()\n // The inventory row's id, written out: `cron-beat-wiring.spec.ts` finds a\n // job's stamp by the quoted id beside the call.\n await writeCronBeat(firestore, 'ai-insights-digest' satisfies typeof AI_INSIGHTS_DIGEST_CRON_ID)\n\n let cursor: string | null = null\n try {\n const body = (await request.json()) as { cursor?: unknown } | null\n const raw = body?.cursor\n cursor = typeof raw === 'string' && raw && !raw.includes('/') ? raw : null\n } catch {\n // A bodyless POST is the first call of a run.\n }\n\n try {\n // The platform switch holds the whole run, as it holds the jobs beat.\n if (await featureLockdownRefusal({ feature: 'ai-generate' })) {\n return Response.json({ held: true, done: true, nextCursor: null }, { status: 200 })\n }\n const flags = await getServerReleaseFlagValues()\n const deps: AiInsightDigestDeps = {\n firestore,\n now: new Date(),\n flagValue: flags['release_ai_generative'],\n // The digest's audience: a locked or disabled account is not told\n // (AGL-3418).\n listMembers: async (orgId) => {\n const members = await listOrgMembers(orgId)\n const reachable = new Set(\n await withoutMailWithheldAccounts(members.map((member) => member.$id)),\n )\n return members.filter((member) => reachable.has(member.$id))\n },\n mayGenerate: (orgId, hostId, member) => memberHasPermissionOnHost(orgId, hostId, member, 'ai.generate'),\n paused: async (orgId) => Boolean(await featureLockdownRefusal({ feature: 'ai-generate', orgId })),\n notify: (uid, payload) => notifyUsers([uid], { type: 'content.insightsDigest', ...payload }),\n send: async (email) => {\n const recipients = await filterSuppressedEmails([email.to], firestore)\n if (!recipients.length) return { sent: false, rateLimited: false }\n // The `ai-insights-digest` system email (AGL-3367), in the org's brand.\n const content = await renderSystemEmailContent(\n 'ai-insights-digest',\n { 'site.name': email.siteName, 'digest.body': email.text },\n systemEmailBrand(email.org),\n { subject: email.subject, text: email.text },\n )\n const result = await sendEmail({\n to: recipients,\n ...content,\n fromName: email.fromName,\n context: 'ai-insights-digest',\n priority: 'bulk',\n })\n if (result.sent) {\n await meterPlatformEmail().catch(() => undefined)\n return { sent: true, rateLimited: false }\n }\n return { sent: false, rateLimited: rateLimitedRetryAtMs(result) !== null }\n },\n // An email link must be absolute; with no console URL configured the\n // digest says where to look without one.\n consoleOrigin: (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, ''),\n }\n const report = await runAiInsightDigestSweep(deps, { cursor })\n return Response.json(report, { status: 200 })\n } catch (error) {\n console.error('ai insights digest run failed', error)\n return Response.json({ error: 'The weekly insights run failed' }, { status: 500 })\n }\n}\n"],"names":["writeCronBeat","rateLimitedRetryAtMs","sendEmail","withoutMailWithheldAccounts","filterSuppressedEmails","meterPlatformEmail","firebaseAdmin","featureLockdownRefusal","notifyUsers","renderSystemEmailContent","systemEmailBrand","listOrgMembers","memberHasPermissionOnHost","getServerReleaseFlagValues","safeEqual","runAiInsightDigestSweep","POST","request","method","Response","json","error","status","secret","process","env","CRON_SECRET","headers","get","firestore","app","cursor","body","raw","includes","feature","held","done","nextCursor","flags","deps","now","Date","flagValue","listMembers","orgId","members","reachable","Set","map","member","$id","filter","has","mayGenerate","hostId","paused","Boolean","notify","uid","payload","type","send","email","recipients","to","length","sent","rateLimited","content","siteName","text","org","subject","result","fromName","context","priority","catch","undefined","consoleOrigin","NEXT_PUBLIC_CONSOLE_URL","trim","replace","report","console"],"mappings":";AAAA;;;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E,OAAO;oBAAEC,MAAM;oBAAOC,aAAa;gBAAM;gBACjE,wEAAwE;gBACxE,MAAMC,UAAU,MAAM5D,yBACpB,sBACA;oBAAE,aAAasD,MAAMO,QAAQ;oBAAE,eAAeP,MAAMQ,IAAI;gBAAC,GACzD7D,iBAAiBqD,MAAMS,GAAG,GAC1B;oBAAEC,SAASV,MAAMU,OAAO;oBAAEF,MAAMR,MAAMQ,IAAI;gBAAC;gBAE7C,MAAMG,SAAS,MAAMxE,UAAU;oBAC7B+D,IAAID;mBACDK;oBACHM,UAAUZ,MAAMY,QAAQ;oBACxBC,SAAS;oBACTC,UAAU;;gBAEZ,IAAIH,OAAOP,IAAI,EAAE;oBACf,MAAM9D,qBAAqByE,KAAK,CAAC,IAAMC;oBACvC,OAAO;wBAAEZ,MAAM;wBAAMC,aAAa;oBAAM;gBAC1C;gBACA,OAAO;oBAAED,MAAM;oBAAOC,aAAanE,qBAAqByE,YAAY;gBAAK;YAC3E;YACA,qEAAqE;YACrE,yCAAyC;YACzCM,eAAe,EAACxD,uCAAAA,QAAQC,GAAG,CAACwD,uBAAuB,YAAnCzD,uCAAuC,IAAI0D,IAAI,GAAGC,OAAO,CAAC,QAAQ;QACpF;QACA,MAAMC,SAAS,MAAMrE,wBAAwByB,MAAM;YAAET;QAAO;QAC5D,OAAOZ,SAASC,IAAI,CAACgE,QAAQ;YAAE9D,QAAQ;QAAI;IAC7C,EAAE,OAAOD,OAAO;QACdgE,QAAQhE,KAAK,CAAC,iCAAiCA;QAC/C,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiC,GAAG;YAAEC,QAAQ;QAAI;IAClF;AACF"}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { sendEmail } from '@aglyn/shared-util-email';
|
|
18
|
+
import { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail';
|
|
18
19
|
import { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering';
|
|
19
20
|
import { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression';
|
|
20
21
|
import { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications';
|
|
@@ -62,6 +63,8 @@ export interface AiAllotmentAlertChannels {
|
|
|
62
63
|
send: typeof sendEmail;
|
|
63
64
|
filter: typeof filterSuppressedEmails;
|
|
64
65
|
meter: typeof meterPlatformEmail;
|
|
66
|
+
/** The uids given, minus locked or disabled accounts (AGL-3418). */
|
|
67
|
+
reachable: typeof withoutMailWithheldAccounts;
|
|
65
68
|
}
|
|
66
69
|
/** Take the marker for `threshold` this month; `false` when it was taken. */
|
|
67
70
|
export declare function claimAiAllotmentAlert(firestore: FirebaseFirestore.Firestore, orgId: string, subject: string, month: string, threshold: AiAllotmentThreshold): Promise<boolean>;
|
|
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { buildRoute, Route } from "@aglyn/aglyn/app-utils/console-routes";
|
|
18
18
|
import { sendEmail } from "@aglyn/shared-util-email";
|
|
19
|
+
import { withoutMailWithheldAccounts } from "@aglyn/tenant-data-admin/server/account-mail";
|
|
19
20
|
import { meterPlatformEmail } from "@aglyn/tenant-data-admin/server/email-metering";
|
|
20
21
|
import { filterSuppressedEmails } from "@aglyn/tenant-data-admin/server/email-suppression";
|
|
21
22
|
import { notifyUsers } from "@aglyn/tenant-data-admin/server/notifications";
|
|
@@ -25,7 +26,8 @@ const DEFAULT_CHANNELS = {
|
|
|
25
26
|
notify: notifyUsers,
|
|
26
27
|
send: sendEmail,
|
|
27
28
|
filter: filterSuppressedEmails,
|
|
28
|
-
meter: meterPlatformEmail
|
|
29
|
+
meter: meterPlatformEmail,
|
|
30
|
+
reachable: withoutMailWithheldAccounts
|
|
29
31
|
};
|
|
30
32
|
/** The console's absolute origin for an email link, or `''` when unset. */ function consoleOrigin() {
|
|
31
33
|
var _process_env_NEXT_PUBLIC_CONSOLE_URL;
|
|
@@ -49,9 +51,12 @@ const DEFAULT_CHANNELS = {
|
|
|
49
51
|
return true;
|
|
50
52
|
});
|
|
51
53
|
}
|
|
52
|
-
async function recipientsFor(firestore, orgId, standing) {
|
|
54
|
+
async function recipientsFor(firestore, orgId, standing, reachable) {
|
|
53
55
|
const orgRef = firestore.collection('orgs').doc(orgId);
|
|
54
56
|
const members = await orgRef.collection('members').get();
|
|
57
|
+
// A locked or disabled account is told nothing, by either channel; it is
|
|
58
|
+
// still named when the alert is about it.
|
|
59
|
+
const open = new Set(await reachable(members.docs.map((member)=>member.id)));
|
|
55
60
|
const managerUids = [];
|
|
56
61
|
const managerEmails = [];
|
|
57
62
|
let subjectEmail = null;
|
|
@@ -60,13 +65,13 @@ async function recipientsFor(firestore, orgId, standing) {
|
|
|
60
65
|
var _member_get;
|
|
61
66
|
const role = member.get('role');
|
|
62
67
|
const email = String((_member_get = member.get('email')) != null ? _member_get : '').trim();
|
|
63
|
-
if (role === 'owner' || role === 'admin') {
|
|
68
|
+
if ((role === 'owner' || role === 'admin') && open.has(member.id)) {
|
|
64
69
|
managerUids.push(member.id);
|
|
65
70
|
if (email.includes('@')) managerEmails.push(email);
|
|
66
71
|
}
|
|
67
72
|
if (standing.uid && member.id === standing.uid) {
|
|
68
73
|
var _member_get1;
|
|
69
|
-
subjectEmail = email.includes('@') ? email : null;
|
|
74
|
+
subjectEmail = email.includes('@') && open.has(member.id) ? email : null;
|
|
70
75
|
subjectName = String((_member_get1 = member.get('displayName')) != null ? _member_get1 : '').trim() || email;
|
|
71
76
|
}
|
|
72
77
|
}
|
|
@@ -78,7 +83,7 @@ async function recipientsFor(firestore, orgId, standing) {
|
|
|
78
83
|
return {
|
|
79
84
|
managerUids,
|
|
80
85
|
managerEmails,
|
|
81
|
-
subjectUid: standing.scope === 'host' ? null : standing.uid,
|
|
86
|
+
subjectUid: standing.scope === 'host' || !standing.uid || !open.has(standing.uid) ? null : standing.uid,
|
|
82
87
|
subjectEmail: standing.scope === 'host' ? null : subjectEmail,
|
|
83
88
|
subjectName: subjectName || (standing.scope === 'host' ? 'this' : 'A member')
|
|
84
89
|
};
|
|
@@ -87,13 +92,13 @@ async function recipientsFor(firestore, orgId, standing) {
|
|
|
87
92
|
* Announce every crossing the reservation found. Never throws, and answers
|
|
88
93
|
* how many were announced — one failing crossing does not stop the next.
|
|
89
94
|
*/ export async function announceAiAllotmentAlerts(firestore, input, channels = {}) {
|
|
90
|
-
const { notify, send, filter, meter } = _extends({}, DEFAULT_CHANNELS, channels);
|
|
95
|
+
const { notify, send, filter, meter, reachable } = _extends({}, DEFAULT_CHANNELS, channels);
|
|
91
96
|
let announced = 0;
|
|
92
97
|
for (const { standing, threshold } of input.alerts){
|
|
93
98
|
try {
|
|
94
99
|
const claimed = await claimAiAllotmentAlert(firestore, input.orgId, standing.subject, input.month, threshold);
|
|
95
100
|
if (!claimed) continue;
|
|
96
|
-
const recipients = await recipientsFor(firestore, input.orgId, standing);
|
|
101
|
+
const recipients = await recipientsFor(firestore, input.orgId, standing, reachable);
|
|
97
102
|
const copy = aiAllotmentAlertCopy({
|
|
98
103
|
scope: standing.scope,
|
|
99
104
|
threshold,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/usage/ai-allotment-alerts.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n aiAllotmentAlertCopy,\n type AiAllotmentStanding,\n type AiAllotmentThreshold,\n} from '../model/ai-allotments'\nimport { aiAllotmentRef } from './ai-allotments'\n\n/**\n * A SOFT allotment's 80% and 100% (AGL-2942), through the alert pipeline's\n * two channels: the console notification every usage threshold writes\n * (`billing.usage`, to `users/{uid}/notifications`) and the email beside it,\n * sent past the platform suppression list and metered as platform mail —\n * the same primitives the usage-alert sweep composes.\n *\n * Told when the request that finds the subject at a threshold is admitted,\n * rather than on the next daily sweep: an allotment is a line a manager drew\n * for one person or one site, and a day's delay is most of what a soft line\n * is for. The sweep is untouched.\n *\n * ## Who is told\n *\n * The workspace's owners and admins — the audience of every usage alert —\n * and, for a member's or a collaborator's allotment, the person it is for.\n * The person gets the words without the Billing link, which a collaborator\n * cannot open.\n *\n * ## Once per threshold per month\n *\n * The marker is `alerted: { month, threshold }` on the allotment itself,\n * claimed in a transaction before anything is sent, so two requests at the\n * line cannot both announce it. A write to the allotment clears the marker,\n * so a raised allotment announces its own next crossing.\n */\n\n/** A crossing to announce, as the reservation measured it. */\nexport interface AiAllotmentAlertInput {\n orgId: string\n /** The workspace's slug, for the Billing link; `null` omits the link. */\n orgSlug: string | null\n month: string\n alerts: ReadonlyArray<{ standing: AiAllotmentStanding; threshold: AiAllotmentThreshold }>\n}\n\n/** The pipeline's primitives, replaceable in a spec. */\nexport interface AiAllotmentAlertChannels {\n notify: typeof notifyUsers\n send: typeof sendEmail\n filter: typeof filterSuppressedEmails\n meter: typeof meterPlatformEmail\n}\n\nconst DEFAULT_CHANNELS: AiAllotmentAlertChannels = {\n notify: notifyUsers,\n send: sendEmail,\n filter: filterSuppressedEmails,\n meter: meterPlatformEmail,\n}\n\n/** The console's absolute origin for an email link, or `''` when unset. */\nfunction consoleOrigin(): string {\n return (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, '')\n}\n\n/** Take the marker for `threshold` this month; `false` when it was taken. */\nexport async function claimAiAllotmentAlert(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n subject: string,\n month: string,\n threshold: AiAllotmentThreshold,\n): Promise<boolean> {\n const ref = aiAllotmentRef(firestore.collection('orgs').doc(orgId), subject)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const alerted = snapshot.get('alerted') as { month?: unknown; threshold?: unknown } | null\n if (alerted?.month === month && Number(alerted?.threshold) >= threshold) return false\n tx.set(ref, { alerted: { month, threshold } }, { merge: true })\n return true\n })\n}\n\ninterface Recipients {\n managerUids: string[]\n managerEmails: string[]\n subjectUid: string | null\n subjectEmail: string | null\n subjectName: string\n}\n\nasync function recipientsFor(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n standing: AiAllotmentStanding,\n): Promise<Recipients> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const members = await orgRef.collection('members').get()\n const managerUids: string[] = []\n const managerEmails: string[] = []\n let subjectEmail: string | null = null\n let subjectName = ''\n for (const member of members.docs) {\n const role = member.get('role')\n const email = String(member.get('email') ?? '').trim()\n if (role === 'owner' || role === 'admin') {\n managerUids.push(member.id)\n if (email.includes('@')) managerEmails.push(email)\n }\n if (standing.uid && member.id === standing.uid) {\n subjectEmail = email.includes('@') ? email : null\n subjectName = String(member.get('displayName') ?? '').trim() || email\n }\n }\n if (standing.scope === 'host' && standing.hostId) {\n const host = await firestore.collection('hosts').doc(standing.hostId).get()\n subjectName =\n String(host.get('displayName') ?? '').trim() ||\n String(host.get('subdomain') ?? '').trim()\n }\n return {\n managerUids,\n managerEmails,\n subjectUid: standing.scope === 'host' ? null : standing.uid,\n subjectEmail: standing.scope === 'host' ? null : subjectEmail,\n subjectName: subjectName || (standing.scope === 'host' ? 'this' : 'A member'),\n }\n}\n\n/**\n * Announce every crossing the reservation found. Never throws, and answers\n * how many were announced — one failing crossing does not stop the next.\n */\nexport async function announceAiAllotmentAlerts(\n firestore: FirebaseFirestore.Firestore,\n input: AiAllotmentAlertInput,\n channels: Partial<AiAllotmentAlertChannels> = {},\n): Promise<number> {\n const { notify, send, filter, meter } = { ...DEFAULT_CHANNELS, ...channels }\n let announced = 0\n for (const { standing, threshold } of input.alerts) {\n try {\n const claimed = await claimAiAllotmentAlert(\n firestore,\n input.orgId,\n standing.subject,\n input.month,\n threshold,\n )\n if (!claimed) continue\n const recipients = await recipientsFor(firestore, input.orgId, standing)\n const copy = aiAllotmentAlertCopy({\n scope: standing.scope,\n threshold,\n used: standing.used,\n credits: standing.credits,\n name: recipients.subjectName,\n })\n const link = input.orgSlug\n ? `${buildRoute(Route.MANAGE_BILLING_USAGE, { orgSlug: input.orgSlug })}#ai-allotments`\n : null\n await notify(recipients.managerUids, {\n type: 'billing.usage',\n title: copy.title,\n body: copy.body,\n orgId: input.orgId,\n ...(link ? { link } : {}),\n })\n if (recipients.subjectUid && !recipients.managerUids.includes(recipients.subjectUid)) {\n await notify([recipients.subjectUid], {\n type: 'billing.usage',\n title: copy.title,\n body: copy.body,\n orgId: input.orgId,\n })\n }\n const origin = consoleOrigin()\n const managerText = link && origin ? `${copy.body}\\n\\n${origin}${link}` : copy.body\n const managers = await filter(recipients.managerEmails)\n if (managers.length) {\n const result = await send({\n to: managers,\n subject: copy.title,\n text: managerText,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n const subjectAddress = recipients.subjectEmail\n ? (await filter([recipients.subjectEmail])).filter(\n (address) => !managers.includes(address),\n )\n : []\n if (subjectAddress.length) {\n const result = await send({\n to: subjectAddress,\n subject: copy.title,\n text: copy.body,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n announced += 1\n } catch (error) {\n console.error('[ai-allotments] announcing a crossing failed', input.orgId, standing.subject, error)\n }\n }\n return announced\n}\n"],"names":["buildRoute","Route","sendEmail","meterPlatformEmail","filterSuppressedEmails","notifyUsers","aiAllotmentAlertCopy","aiAllotmentRef","DEFAULT_CHANNELS","notify","send","filter","meter","consoleOrigin","process","env","NEXT_PUBLIC_CONSOLE_URL","trim","replace","claimAiAllotmentAlert","firestore","orgId","subject","month","threshold","ref","collection","doc","runTransaction","tx","snapshot","get","exists","alerted","Number","set","merge","recipientsFor","standing","orgRef","members","managerUids","managerEmails","subjectEmail","subjectName","member","docs","role","email","String","push","id","includes","uid","scope","hostId","host","subjectUid","announceAiAllotmentAlerts","input","channels","announced","alerts","claimed","recipients","copy","used","credits","name","link","orgSlug","MANAGE_BILLING_USAGE","type","title","body","origin","managerText","managers","length","result","to","text","context","sent","catch","undefined","subjectAddress","address","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,oBAAoB,QAGf,4BAAwB;AAC/B,SAASC,cAAc,QAAQ,qBAAiB;AA8ChD,MAAMC,mBAA6C;IACjDC,QAAQJ;IACRK,MAAMR;IACNS,QAAQP;IACRQ,OAAOT;AACT;AAEA,yEAAyE,GACzE,SAASU;QACCC;IAAR,OAAO,EAACA,uCAAAA,QAAQC,GAAG,CAACC,uBAAuB,YAAnCF,uCAAuC,IAAIG,IAAI,GAAGC,OAAO,CAAC,QAAQ;AAC5E;AAEA,2EAA2E,GAC3E,OAAO,eAAeC,sBACpBC,SAAsC,EACtCC,KAAa,EACbC,OAAe,EACfC,KAAa,EACbC,SAA+B;IAE/B,MAAMC,MAAMlB,eAAea,UAAUM,UAAU,CAAC,QAAQC,GAAG,CAACN,QAAQC;IACpE,OAAOF,UAAUQ,cAAc,CAAC,OAAOC;QACrC,MAA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AAI;oBACfQ,SAAS;gBACX;gBACA,IAAIH,OAAOI,IAAI,EAAE,MAAMvE,QAAQwE,KAAK,CAAC,IAAMC;YAC7C;YACAxB,aAAa;QACf,EAAE,OAAO2B,OAAO;YACdC,QAAQD,KAAK,CAAC,gDAAgD7B,MAAMtC,KAAK,EAAEiB,SAAShB,OAAO,EAAEkE;QAC/F;IACF;IACA,OAAO3B;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/usage/ai-allotment-alerts.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n aiAllotmentAlertCopy,\n type AiAllotmentStanding,\n type AiAllotmentThreshold,\n} from '../model/ai-allotments'\nimport { aiAllotmentRef } from './ai-allotments'\n\n/**\n * A SOFT allotment's 80% and 100% (AGL-2942), through the alert pipeline's\n * two channels: the console notification every usage threshold writes\n * (`billing.usage`, to `users/{uid}/notifications`) and the email beside it,\n * sent past the platform suppression list and metered as platform mail —\n * the same primitives the usage-alert sweep composes.\n *\n * Told when the request that finds the subject at a threshold is admitted,\n * rather than on the next daily sweep: an allotment is a line a manager drew\n * for one person or one site, and a day's delay is most of what a soft line\n * is for. The sweep is untouched.\n *\n * ## Who is told\n *\n * The workspace's owners and admins — the audience of every usage alert —\n * and, for a member's or a collaborator's allotment, the person it is for.\n * The person gets the words without the Billing link, which a collaborator\n * cannot open.\n *\n * ## Once per threshold per month\n *\n * The marker is `alerted: { month, threshold }` on the allotment itself,\n * claimed in a transaction before anything is sent, so two requests at the\n * line cannot both announce it. A write to the allotment clears the marker,\n * so a raised allotment announces its own next crossing.\n */\n\n/** A crossing to announce, as the reservation measured it. */\nexport interface AiAllotmentAlertInput {\n orgId: string\n /** The workspace's slug, for the Billing link; `null` omits the link. */\n orgSlug: string | null\n month: string\n alerts: ReadonlyArray<{ standing: AiAllotmentStanding; threshold: AiAllotmentThreshold }>\n}\n\n/** The pipeline's primitives, replaceable in a spec. */\nexport interface AiAllotmentAlertChannels {\n notify: typeof notifyUsers\n send: typeof sendEmail\n filter: typeof filterSuppressedEmails\n meter: typeof meterPlatformEmail\n /** The uids given, minus locked or disabled accounts (AGL-3418). */\n reachable: typeof withoutMailWithheldAccounts\n}\n\nconst DEFAULT_CHANNELS: AiAllotmentAlertChannels = {\n notify: notifyUsers,\n send: sendEmail,\n filter: filterSuppressedEmails,\n meter: meterPlatformEmail,\n reachable: withoutMailWithheldAccounts,\n}\n\n/** The console's absolute origin for an email link, or `''` when unset. */\nfunction consoleOrigin(): string {\n return (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, '')\n}\n\n/** Take the marker for `threshold` this month; `false` when it was taken. */\nexport async function claimAiAllotmentAlert(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n subject: string,\n month: string,\n threshold: AiAllotmentThreshold,\n): Promise<boolean> {\n const ref = aiAllotmentRef(firestore.collection('orgs').doc(orgId), subject)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const alerted = snapshot.get('alerted') as { month?: unknown; threshold?: unknown } | null\n if (alerted?.month === month && Number(alerted?.threshold) >= threshold) return false\n tx.set(ref, { alerted: { month, threshold } }, { merge: true })\n return true\n })\n}\n\ninterface Recipients {\n managerUids: string[]\n managerEmails: string[]\n subjectUid: string | null\n subjectEmail: string | null\n subjectName: string\n}\n\nasync function recipientsFor(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n standing: AiAllotmentStanding,\n reachable: AiAllotmentAlertChannels['reachable'],\n): Promise<Recipients> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const members = await orgRef.collection('members').get()\n // A locked or disabled account is told nothing, by either channel; it is\n // still named when the alert is about it.\n const open = new Set(await reachable(members.docs.map((member) => member.id)))\n const managerUids: string[] = []\n const managerEmails: string[] = []\n let subjectEmail: string | null = null\n let subjectName = ''\n for (const member of members.docs) {\n const role = member.get('role')\n const email = String(member.get('email') ?? '').trim()\n if ((role === 'owner' || role === 'admin') && open.has(member.id)) {\n managerUids.push(member.id)\n if (email.includes('@')) managerEmails.push(email)\n }\n if (standing.uid && member.id === standing.uid) {\n subjectEmail = email.includes('@') && open.has(member.id) ? email : null\n subjectName = String(member.get('displayName') ?? '').trim() || email\n }\n }\n if (standing.scope === 'host' && standing.hostId) {\n const host = await firestore.collection('hosts').doc(standing.hostId).get()\n subjectName =\n String(host.get('displayName') ?? '').trim() ||\n String(host.get('subdomain') ?? '').trim()\n }\n return {\n managerUids,\n managerEmails,\n subjectUid:\n standing.scope === 'host' || !standing.uid || !open.has(standing.uid)\n ? null\n : standing.uid,\n subjectEmail: standing.scope === 'host' ? null : subjectEmail,\n subjectName: subjectName || (standing.scope === 'host' ? 'this' : 'A member'),\n }\n}\n\n/**\n * Announce every crossing the reservation found. Never throws, and answers\n * how many were announced — one failing crossing does not stop the next.\n */\nexport async function announceAiAllotmentAlerts(\n firestore: FirebaseFirestore.Firestore,\n input: AiAllotmentAlertInput,\n channels: Partial<AiAllotmentAlertChannels> = {},\n): Promise<number> {\n const { notify, send, filter, meter, reachable } = { ...DEFAULT_CHANNELS, ...channels }\n let announced = 0\n for (const { standing, threshold } of input.alerts) {\n try {\n const claimed = await claimAiAllotmentAlert(\n firestore,\n input.orgId,\n standing.subject,\n input.month,\n threshold,\n )\n if (!claimed) continue\n const recipients = await recipientsFor(firestore, input.orgId, standing, reachable)\n const copy = aiAllotmentAlertCopy({\n scope: standing.scope,\n threshold,\n used: standing.used,\n credits: standing.credits,\n name: recipients.subjectName,\n })\n const link = input.orgSlug\n ? `${buildRoute(Route.MANAGE_BILLING_USAGE, { orgSlug: input.orgSlug })}#ai-allotments`\n : null\n await notify(recipients.managerUids, {\n type: 'billing.usage',\n title: copy.title,\n body: copy.body,\n orgId: input.orgId,\n ...(link ? { link } : {}),\n })\n if (recipients.subjectUid && !recipients.managerUids.includes(recipients.subjectUid)) {\n await notify([recipients.subjectUid], {\n type: 'billing.usage',\n title: copy.title,\n body: copy.body,\n orgId: input.orgId,\n })\n }\n const origin = consoleOrigin()\n const managerText = link && origin ? `${copy.body}\\n\\n${origin}${link}` : copy.body\n const managers = await filter(recipients.managerEmails)\n if (managers.length) {\n const result = await send({\n to: managers,\n subject: copy.title,\n text: managerText,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n const subjectAddress = recipients.subjectEmail\n ? (await filter([recipients.subjectEmail])).filter(\n (address) => !managers.includes(address),\n )\n : []\n if (subjectAddress.length) {\n const result = await send({\n to: subjectAddress,\n subject: copy.title,\n text: copy.body,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n announced += 1\n } catch (error) {\n console.error('[ai-allotments] announcing a crossing failed', input.orgId, standing.subject, error)\n }\n }\n return announced\n}\n"],"names":["buildRoute","Route","sendEmail","withoutMailWithheldAccounts","meterPlatformEmail","filterSuppressedEmails","notifyUsers","aiAllotmentAlertCopy","aiAllotmentRef","DEFAULT_CHANNELS","notify","send","filter","meter","reachable","consoleOrigin","process","env","NEXT_PUBLIC_CONSOLE_URL","trim","replace","claimAiAllotmentAlert","firestore","orgId","subject","month","threshold","ref","collection","doc","runTransaction","tx","snapshot","get","exists","alerted","Number","set","merge","recipientsFor","standing","orgRef","members","open","Set","docs","map","member","id","managerUids","managerEmails","subjectEmail","subjectName","role","email","String","has","push","includes","uid","scope","hostId","host","subjectUid","announceAiAllotmentAlerts","input","channels","announced","alerts","claimed","recipients","copy","used","credits","name","link","orgSlug","MANAGE_BILLING_USAGE","type","title","body","origin","managerText","managers","length","result","to","text","context","sent","catch","undefined","subjectAddress","address","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,2BAA2B,QAAQ,+CAA8C;AAC1F,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,oBAAoB,QAGf,4BAAwB;AAC/B,SAASC,cAAc,QAAQ,qBAAiB;AAgDhD,MAAMC,mBAA6C;IACjDC,QAAQJ;IACRK,MAAMT;IACNU,QAAQP;IACRQ,OAAOT;IACPU,WAAWX;AACb;AAEA,yEAAyE,GACzE,SAASY;QACCC;IAAR,OAAO,EAACA,uCAAAA,QAAQC,GAAG,CAACC,uBAAuB,YAAnCF,uCAAuC,IAAIG,IAAI,GAAGC,OAAO,CAAC,QAAQ;AAC5E;AAEA,2EAA2E,GAC3E,OAAO,eAAeC,sBACpBC,SAAsC,EACtCC,KAAa,EACbC,OAAe,EACfC,KAAa,EACbC,SAA+B;IAE/B,MAAMC,MAAMnB,eAAec,UAAUM,UAAU,CAAC,QAAQC,GAAG,CAACN,QAAQC;IACpE,OAAOF,UAAUQ,cAAc,CAAC,OAAOC;QACrC,MAAMC,WAAW,MAAMD,GAAGE,GAAG,CAACN;QAC9B,IAAI,CAACK,SAASE,MAAM,EAAE,OAAO;QAC7B,MAAMC,UAAUH,SAASC,GAAG,CAA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Y;aAAC,CAAA,EAAGvC,MAAM,CAC9C,CAACiF,UAAY,CAACV,SAASzB,QAAQ,CAACmC,YAElC,EAAE;YACN,IAAID,eAAeR,MAAM,EAAE;gBACzB,MAAMC,SAAS,MAAM1E,KAAK;oBACxB2E,IAAIM;oBACJpE,SAAS+C,KAAKQ,KAAK;oBACnBQ,MAAMhB,KAAKS,IAAI;oBACfQ,SAAS;gBACX;gBACA,IAAIH,OAAOI,IAAI,EAAE,MAAM5E,QAAQ6E,KAAK,CAAC,IAAMC;YAC7C;YACAxB,aAAa;QACf,EAAE,OAAO2B,OAAO;YACdC,QAAQD,KAAK,CAAC,gDAAgD7B,MAAM1C,KAAK,EAAEiB,SAAShB,OAAO,EAAEsE;QAC/F;IACF;IACA,OAAO3B;AACT"}
|
|
@@ -286,7 +286,7 @@ const number = (value)=>{
|
|
|
286
286
|
cacheWrite: totals.cacheWriteTokens
|
|
287
287
|
});
|
|
288
288
|
for (const _ref of kinds){
|
|
289
|
-
|
|
289
|
+
const [kind, _ref1] = _ref, { outputs } = _ref1, bucket = _object_without_properties_loose(_ref1, [
|
|
290
290
|
"outputs"
|
|
291
291
|
]);
|
|
292
292
|
totals.byKind[kind] = _extends({}, bucket, {
|