@aglyn/plugins-ai 1.4.0 → 1.5.0
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/insights/ai-figure-readers.js +3 -2
- package/src/lib/insights/ai-figure-readers.js.map +1 -1
- package/src/lib/insights/ai-figure-summaries.d.ts +1 -0
- package/src/lib/insights/ai-figure-summaries.js +11 -1
- package/src/lib/insights/ai-figure-summaries.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.js +3 -10
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/model/ai-insight.js +2 -5
- package/src/lib/model/ai-insight.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-ai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,22 +25,22 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-enums": "1.
|
|
30
|
-
"@aglyn/shared-data-mdi": "1.
|
|
31
|
-
"@aglyn/shared-data-types": "1.
|
|
32
|
-
"@aglyn/shared-ui-email-campaigns": "1.
|
|
33
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
34
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
35
|
-
"@aglyn/shared-ui-theme": "1.
|
|
36
|
-
"@aglyn/shared-util-email": "1.
|
|
37
|
-
"@aglyn/shared-util-errors": "1.
|
|
38
|
-
"@aglyn/shared-util-http": "1.
|
|
39
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
40
|
-
"@aglyn/shared-util-tools": "1.
|
|
41
|
-
"@aglyn/tenant-data-admin": "1.
|
|
42
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
43
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.5.0",
|
|
29
|
+
"@aglyn/shared-data-enums": "1.5.0",
|
|
30
|
+
"@aglyn/shared-data-mdi": "1.5.0",
|
|
31
|
+
"@aglyn/shared-data-types": "1.5.0",
|
|
32
|
+
"@aglyn/shared-ui-email-campaigns": "1.5.0",
|
|
33
|
+
"@aglyn/shared-ui-jsx": "1.5.0",
|
|
34
|
+
"@aglyn/shared-ui-snackstack": "1.5.0",
|
|
35
|
+
"@aglyn/shared-ui-theme": "1.5.0",
|
|
36
|
+
"@aglyn/shared-util-email": "1.5.0",
|
|
37
|
+
"@aglyn/shared-util-errors": "1.5.0",
|
|
38
|
+
"@aglyn/shared-util-http": "1.5.0",
|
|
39
|
+
"@aglyn/shared-util-timestamp": "1.5.0",
|
|
40
|
+
"@aglyn/shared-util-tools": "1.5.0",
|
|
41
|
+
"@aglyn/tenant-data-admin": "1.5.0",
|
|
42
|
+
"@aglyn/tenant-feature-instance": "1.5.0",
|
|
43
|
+
"@aglyn/tenant-runtime": "1.5.0",
|
|
44
44
|
"@swc/helpers": "0.5.23"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
@@ -17,7 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { formPeriodKey, formStatsTotals } from "@aglyn/aglyn/app-utils/forms";
|
|
18
18
|
import { PLUGIN_FIGURE_MAX_ROWS, pluginFigureChange, pluginFigureDay, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
19
19
|
import { AI_PLUGIN_ID } from "../constants.js";
|
|
20
|
-
import { FORMS_WEEKLY_SUMMARY, SOURCES_WEEKLY_SUMMARY, TOP_PAGES_WEEKLY_SUMMARY, TRAFFIC_WEEKLY_SUMMARY } from "./ai-figure-summaries.js";
|
|
20
|
+
import { FORMS_WEEKLY_SUMMARY, SOURCES_WEEKLY_SUMMARY, TOP_PAGES_WEEKLY_SUMMARY, TRAFFIC_DAILY_WEEKLY_SUMMARY, TRAFFIC_WEEKLY_SUMMARY } from "./ai-figure-summaries.js";
|
|
21
21
|
/** The traffic windows: the Traffic card's own ranges. */ export const AI_TRAFFIC_WINDOWS = [
|
|
22
22
|
7,
|
|
23
23
|
14,
|
|
@@ -335,7 +335,8 @@ export function trafficFigureReaders(firestore) {
|
|
|
335
335
|
id: 'traffic.daily',
|
|
336
336
|
label: 'Traffic by day',
|
|
337
337
|
description: 'Page views and visitors on each day of the window, oldest first, for spotting a day that stood out.',
|
|
338
|
-
windows: AI_TRAFFIC_DAILY_WINDOWS
|
|
338
|
+
windows: AI_TRAFFIC_DAILY_WINDOWS,
|
|
339
|
+
weeklySummary: TRAFFIC_DAILY_WEEKLY_SUMMARY
|
|
339
340
|
}, async (db, request)=>{
|
|
340
341
|
const ids = [
|
|
341
342
|
...dayIds(request.now, request.days).current
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-readers.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 { formPeriodKey, formStatsTotals, type FormStats } from '@aglyn/aglyn/app-utils/forms'\nimport {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureDay,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRead,\n type PluginFigureRequest,\n type PluginFigureRow,\n type PluginFigureTable,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { AI_PLUGIN_ID } from '../constants'\nimport {\n FORMS_WEEKLY_SUMMARY,\n SOURCES_WEEKLY_SUMMARY,\n TOP_PAGES_WEEKLY_SUMMARY,\n TRAFFIC_WEEKLY_SUMMARY,\n} from './ai-figure-summaries'\n\n/**\n * The figure readers this plugin registers for records the PLATFORM keeps\n * (AGL-2915): a site's page-view counters and its forms' counters. Every\n * other reader an insight reads is registered by the plugin that owns its\n * records — commerce, bookings, marketing, the workspace's datasets — on the\n * `plugin-figures` seam, and nothing here reads their documents.\n *\n * Each reader answers with one compact table of aggregates, read-only and\n * about nobody: counts, sums and rates, labeled by a page path, a form's name\n * or a referring site — never a visitor or a submission.\n *\n * The readers use the arithmetic their console cards use: the Traffic card's\n * windows and change (`pluginFigureWindows`, `pluginFigureChange`, which are\n * that card's split and delta), and the forms plugin's month counters through\n * `formStatsTotals`, the one function every forms surface windows by.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** How a reader reaches Firestore: resolved when it reads, never when it registers. */\nexport type AiFigureFirestore = () => Firestore\n\n/** The traffic windows: the Traffic card's own ranges. */\nexport const AI_TRAFFIC_WINDOWS: readonly number[] = [7, 14, 30, 90]\n\n/** A day-by-day table fits a table's row bound only over a short window. */\nexport const AI_TRAFFIC_DAILY_WINDOWS: readonly number[] = [7, 14]\n\n/** Pages a pages table lists; the rest are counted in `omitted`. */\nexport const AI_TRAFFIC_TOP_PAGES = 10\n\n/** Referring sites, and campaign sources and campaigns, a sources table lists. */\nexport const AI_TRAFFIC_TOP_REFERRERS = 8\nexport const AI_TRAFFIC_TOP_CAMPAIGNS = 5\n\n/** Forms a forms table reads. */\nexport const AI_FORMS_READ_LIMIT = 100\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nconst num = (value: unknown): number => {\n const parsed = typeof value === 'number' ? value : Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\nconst round1 = (value: number): number => Math.round(value * 10) / 10\n\nconst share = (part: number, whole: number): number | null => (whole > 0 ? round1((part / whole) * 100) : null)\n\nfunction refused(status: 400 | 403 | 404, error: string): PluginFigureRead {\n return { ok: false, status, error }\n}\n\n/** A window's days as the table's period, oldest to newest. */\nfunction periodOf(request: PluginFigureRequest): PluginFigureTable['period'] {\n const { current } = pluginFigureWindows(request.now, request.days)\n return { from: current.from, to: current.to, days: request.days }\n}\n\n/** Every day id of the window and the one before it, newest first. */\nfunction dayIds(now: Date, days: number): { current: string[]; previous: string[] } {\n const { current, previous } = pluginFigureWindows(now, days)\n const walk = (startMs: number, endMs: number): string[] => {\n const ids: string[] = []\n for (let at = endMs - 86_400_000; at >= startMs; at -= 86_400_000) ids.push(pluginFigureDay(new Date(at)))\n return ids\n }\n return { current: walk(current.startMs, current.endMs), previous: walk(previous.startMs, previous.endMs) }\n}\n\n// ── Traffic ───────────────────────────────────────────────────────────────\n\ninterface TrafficDay {\n total: number\n visitors: number\n paths: Record<string, number>\n referrers: Record<string, number>\n utm: Record<string, Record<string, number>>\n}\n\nconst counts = (value: unknown): Record<string, number> => {\n const out: Record<string, number> = {}\n if (!value || typeof value !== 'object') return out\n for (const [key, count] of Object.entries(value as Record<string, unknown>)) {\n const n = num(count)\n if (n > 0) out[key] = n\n }\n return out\n}\n\nasync function readTrafficDays(\n firestore: Firestore,\n hostId: string,\n ids: readonly string[],\n): Promise<TrafficDay[]> {\n if (!ids.length) return []\n const collection = firestore.collection('hosts').doc(hostId).collection('analytics')\n const snapshots = await firestore.getAll(...ids.map((id) => collection.doc(id)))\n return snapshots.map((snapshot) => {\n const data = (snapshot.exists ? snapshot.data() : null) ?? {}\n const utm: Record<string, Record<string, number>> = {}\n for (const [param, values] of Object.entries((data['utm'] ?? {}) as Record<string, unknown>)) {\n utm[param] = counts(values)\n }\n return {\n total: num(data['total']),\n visitors: num(data['visitors']),\n paths: counts(data['paths']),\n referrers: counts(data['referrers']),\n utm,\n }\n })\n}\n\nfunction sumMaps(days: readonly TrafficDay[], pick: (day: TrafficDay) => Record<string, number>): Map<string, number> {\n const totals = new Map<string, number>()\n for (const day of days) {\n for (const [key, count] of Object.entries(pick(day))) totals.set(key, (totals.get(key) ?? 0) + count)\n }\n return totals\n}\n\nconst ranked = (totals: Map<string, number>): Array<[string, number]> =>\n [...totals.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n\nfunction siteReader(\n base: Omit<PluginFigureReader, 'read' | 'scope' | 'plugin'>,\n read: (firestore: Firestore, request: PluginFigureRequest & { hostId: string }) => Promise<PluginFigureRead>,\n firestore: AiFigureFirestore,\n plugin: string | null,\n): PluginFigureReader {\n return {\n ...base,\n scope: 'site',\n plugin,\n read: async (request) => {\n if (!request.hostId) return refused(400, 'Open a site to read its figures')\n if (!base.windows.includes(request.days)) return refused(400, 'That window is not one this reader covers')\n return read(firestore(), { ...request, hostId: request.hostId })\n },\n }\n}\n\nexport function trafficFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n const source = { label: 'Analytics', path: 'analytics' }\n const visitorsNote =\n 'Visitors are counted once per browser tab per day, so one person on two days counts twice.'\n return [\n siteReader(\n {\n id: 'traffic.summary',\n label: 'Traffic',\n description:\n 'Page views, visitors and views a day on the site over the window, each beside the window before it and the change.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TRAFFIC_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const total = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.total, 0)\n const visitors = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.visitors, 0)\n const views = total(current)\n const viewsBefore = total(previous)\n const perDay = Math.round(views / request.days)\n const perDayBefore = Math.round(viewsBefore / request.days)\n const table: PluginFigureTable = {\n title: 'Traffic',\n source,\n period: periodOf(request),\n columns: [\n { key: 'figure', label: 'Figure', kind: 'text' },\n { key: 'current', label: 'This window', kind: 'count' },\n { key: 'previous', label: 'Window before', kind: 'count' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows: [\n { figure: 'Page views', current: views, previous: viewsBefore, change: pluginFigureChange(views, viewsBefore) },\n {\n figure: 'Visitors',\n current: visitors(current),\n previous: visitors(previous),\n change: pluginFigureChange(visitors(current), visitors(previous)),\n },\n {\n figure: 'Page views a day',\n current: perDay,\n previous: perDayBefore,\n change: pluginFigureChange(perDay, perDayBefore),\n },\n ],\n omitted: 0,\n notes: [\n visitorsNote,\n ...(viewsBefore ? [] : ['The window before this one recorded no page views, so there is no change to compare.']),\n ],\n }\n return { ok: true, table }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.pages',\n label: 'Top pages',\n description: `The site's ${AI_TRAFFIC_TOP_PAGES} most viewed pages over the window, with each page's share of all views and its change from the window before.`,\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TOP_PAGES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const now = ranked(sumMaps(current, (day) => day.paths))\n const before = sumMaps(previous, (day) => day.paths)\n const all = now.reduce((sum, [, count]) => sum + count, 0)\n const rows: PluginFigureRow[] = now.slice(0, AI_TRAFFIC_TOP_PAGES).map(([path, views]) => ({\n page: path,\n views,\n share: share(views, all),\n change: pluginFigureChange(views, before.get(path) ?? null),\n }))\n return {\n ok: true,\n table: {\n title: 'Top pages',\n source,\n period: periodOf(request),\n columns: [\n { key: 'page', label: 'Page', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of views', kind: 'percent' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows,\n omitted: Math.max(0, now.length - rows.length),\n notes: [],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.sources',\n label: 'Traffic sources',\n description:\n 'Where visits came from over the window: the referring sites, and the campaign sources and campaigns links were tagged with, with each one’s views.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: SOURCES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const days = await readTrafficDays(db, request.hostId, dayIds(request.now, request.days).current)\n const all = days.reduce((sum, day) => sum + day.total, 0)\n // The collector stores a referring host with its dots as `_`, because a\n // Firestore field path cannot hold one; a host is read back as written.\n const referrers = ranked(sumMaps(days, (day) => day.referrers)).map(\n ([host, views]): [string, number] => [host.replace(/_/g, '.'), views],\n )\n const sources = ranked(sumMaps(days, (day) => day.utm['source'] ?? {}))\n const campaigns = ranked(sumMaps(days, (day) => day.utm['campaign'] ?? {}))\n const rowsOf = (entries: Array<[string, number]>, limit: number, type: string) =>\n entries.slice(0, limit).map(([name, views]) => ({ source: name, type, views, share: share(views, all) }))\n const rows = [\n ...rowsOf(referrers, AI_TRAFFIC_TOP_REFERRERS, 'Referring site'),\n ...rowsOf(sources, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign source'),\n ...rowsOf(campaigns, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign'),\n ]\n return {\n ok: true,\n table: {\n title: 'Traffic sources',\n source,\n period: periodOf(request),\n columns: [\n { key: 'source', label: 'Source', kind: 'text' },\n { key: 'type', label: 'Kind', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of all views', kind: 'percent' },\n ],\n rows,\n omitted:\n Math.max(0, referrers.length - AI_TRAFFIC_TOP_REFERRERS) +\n Math.max(0, sources.length - AI_TRAFFIC_TOP_CAMPAIGNS) +\n Math.max(0, campaigns.length - AI_TRAFFIC_TOP_CAMPAIGNS),\n notes: ['A visit with no referring site, such as a typed address, is in no row.'],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.daily',\n label: 'Traffic by day',\n description: 'Page views and visitors on each day of the window, oldest first, for spotting a day that stood out.',\n windows: AI_TRAFFIC_DAILY_WINDOWS,\n },\n async (db, request) => {\n const ids = [...dayIds(request.now, request.days).current].reverse()\n const days = await readTrafficDays(db, request.hostId, ids)\n return {\n ok: true,\n table: {\n title: 'Traffic by day',\n source,\n period: periodOf(request),\n columns: [\n { key: 'day', label: 'Day', kind: 'date' },\n { key: 'views', label: 'Page views', kind: 'count' },\n { key: 'visitors', label: 'Visitors', kind: 'count' },\n ],\n rows: days.map((day, index) => ({ day: ids[index], views: day.total, visitors: day.visitors })),\n omitted: 0,\n notes: [visitorsNote],\n },\n }\n },\n firestore,\n null,\n ),\n ]\n}\n\n// ── Forms ─────────────────────────────────────────────────────────────────\n\nexport function formsFigureReader(firestore: AiFigureFirestore): PluginFigureReader {\n return siteReader(\n {\n id: 'forms.performance',\n label: 'Forms',\n description:\n 'Each form’s views, submissions, the share of views that became a submission, and leads, over the calendar months the window falls in.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: FORMS_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const { current } = pluginFigureWindows(request.now, request.days)\n const from = formPeriodKey(current.startMs)\n const to = formPeriodKey(current.endMs - 1)\n const snapshot = await db\n .collection('hosts')\n .doc(request.hostId)\n .collection('forms')\n .limit(AI_FORMS_READ_LIMIT)\n .get()\n const forms = snapshot.docs\n .map((doc) => ({ doc, data: (doc.data() ?? {}) as Record<string, unknown> }))\n .filter(({ data }) => !data['deletedAt'])\n .map(({ doc, data }) => {\n const totals = formStatsTotals(data['stats'] as FormStats | undefined, { from, to })\n // Every submission to a form is counted on it, so a form with none\n // recorded in the window had none: 0, not a blank the answer has to\n // hedge over (AGL-3834). Leads are counted only on a form that\n // routes them, so one that does reads 0 the same way, and a form\n // that never has keeps a blank, which the table's note explains.\n const submissions = totals.submissions ?? 0\n const routesLeads = (data['routing'] as { lead?: unknown } | undefined)?.lead === true\n return {\n form: str(data['displayName']) || doc.id,\n views: totals.views,\n submissions,\n completion: totals.views ? share(submissions, totals.views) : null,\n leads: totals.leads ?? (routesLeads ? 0 : null),\n }\n })\n .sort((a, b) => b.submissions - a.submissions || a.form.localeCompare(b.form))\n const monthStart = from ? `${from}-01` : current.from\n return {\n ok: true,\n table: {\n title: 'Forms',\n source: { label: 'Forms', path: 'forms' },\n period: {\n from: monthStart,\n to: current.to,\n days: Math.round((Date.parse(current.to) - Date.parse(monthStart)) / 86_400_000) + 1,\n },\n columns: [\n { key: 'form', label: 'Form', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'submissions', label: 'Submissions', kind: 'count' },\n { key: 'completion', label: 'Views that became a submission', kind: 'percent' },\n { key: 'leads', label: 'Leads', kind: 'count' },\n ],\n rows: forms.slice(0, PLUGIN_FIGURE_MAX_ROWS),\n omitted: Math.max(0, forms.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: [\n 'Form figures are kept by calendar month, so they cover whole months from the first day of the month the window starts in.',\n 'Views are counted in the visitor’s browser and submissions on the server, so a rate can pass 100%.',\n 'A blank Leads figure means the form does not add its submissions to Leads.',\n ],\n },\n }\n },\n firestore,\n 'forms',\n )\n}\n\n/** Every reader this plugin registers, for the platform's own records. */\nexport function aiFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n return [...trafficFigureReaders(firestore), formsFigureReader(firestore)]\n}\n\n/**\n * Registers them from the console surface, the one surface that runs insight\n * jobs. By a call, never by an import (AGL-3025).\n */\nexport function registerAiFigureReaders(firestore: AiFigureFirestore): void {\n for (const reader of aiFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: AI_PLUGIN_ID })\n }\n}\n"],"names":["formPeriodKey","formStatsTotals","PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureDay","pluginFigureWindows","registerPluginFigureReader","AI_PLUGIN_ID","FORMS_WEEKLY_SUMMARY","SOURCES_WEEKLY_SUMMARY","TOP_PAGES_WEEKLY_SUMMARY","TRAFFIC_WEEKLY_SUMMARY","AI_TRAFFIC_WINDOWS","AI_TRAFFIC_DAILY_WINDOWS","AI_TRAFFIC_TOP_PAGES","AI_TRAFFIC_TOP_REFERRERS","AI_TRAFFIC_TOP_CAMPAIGNS","AI_FORMS_READ_LIMIT","str","value","trim","num","parsed","Number","isFinite","round1","Math","round","share","part","whole","refused","status","error","ok","periodOf","request","current","now","days","from","to","dayIds","previous","walk","startMs","endMs","ids","at","push","Date","counts","out","key","count","Object","entries","n","readTrafficDays","firestore","hostId","length","collection","doc","snapshots","getAll","map","id","snapshot","data","exists","utm","param","values","total","visitors","paths","referrers","sumMaps","pick","totals","Map","day","set","get","ranked","sort","a","b","localeCompare","siteReader","base","read","plugin","scope","windows","includes","trafficFigureReaders","source","label","path","visitorsNote","description","weeklySummary","db","Promise","all","reduce","sum","views","viewsBefore","perDay","perDayBefore","table","title","period","columns","kind","rows","figure","change","omitted","notes","before","slice","page","max","host","replace","sources","campaigns","rowsOf","limit","type","name","reverse","index","formsFigureReader","forms","docs","filter","submissions","routesLeads","lead","form","completion","leads","monthStart","parse","aiFigureReaders","registerAiFigureReaders","reader","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,QAAwB,+BAA8B;AAC7F,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,eAAe,EACfC,mBAAmB,EACnBC,0BAA0B,QAMrB,6CAA4C;AACnD,SAASC,YAAY,QAAQ,kBAAc;AAC3C,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,wBAAwB,EACxBC,sBAAsB,QACjB,2BAAuB;AAwB9B,wDAAwD,GACxD,OAAO,MAAMC,qBAAwC;IAAC;IAAG;IAAI;IAAI;CAAG,CAAA;AAEpE,0EAA0E,GAC1E,OAAO,MAAMC,2BAA8C;IAAC;IAAG;CAAG,CAAA;AAElE,kEAAkE,GAClE,OAAO,MAAMC,uBAAuB,GAAE;AAEtC,gFAAgF,GAChF,OAAO,MAAMC,2BAA2B,EAAC;AACzC,OAAO,MAAMC,2BAA2B,E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OAAO;wBAASkB,MAAM;oBAAQ;iBAC/C;gBACDC,MAAMoB,MAAMd,KAAK,CAAC,GAAG1H;gBACrBuH,SAAS/F,KAAKoG,GAAG,CAAC,GAAGY,MAAM7E,MAAM,GAAG3D;gBACpCwH,OAAO;oBACL;oBACA;oBACA;iBACD;YACH;QACF;IACF,GACA/D,WACA;AAEJ;AAEA,wEAAwE,GACxE,OAAO,SAAS0F,gBAAgB1F,SAA4B;IAC1D,OAAO;WAAIsC,qBAAqBtC;QAAY8E,kBAAkB9E;KAAW;AAC3E;AAEA;;;CAGC,GACD,OAAO,SAAS2F,wBAAwB3F,SAA4B;IAClE,KAAK,MAAM4F,UAAUF,gBAAgB1F,WAAY;QAC/CrD,2BAA2BiJ,QAAQ;YAAEC,UAAUjJ;QAAa;IAC9D;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-readers.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 { formPeriodKey, formStatsTotals, type FormStats } from '@aglyn/aglyn/app-utils/forms'\nimport {\n PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureDay,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRead,\n type PluginFigureRequest,\n type PluginFigureRow,\n type PluginFigureTable,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { AI_PLUGIN_ID } from '../constants'\nimport {\n FORMS_WEEKLY_SUMMARY,\n SOURCES_WEEKLY_SUMMARY,\n TOP_PAGES_WEEKLY_SUMMARY,\n TRAFFIC_DAILY_WEEKLY_SUMMARY,\n TRAFFIC_WEEKLY_SUMMARY,\n} from './ai-figure-summaries'\n\n/**\n * The figure readers this plugin registers for records the PLATFORM keeps\n * (AGL-2915): a site's page-view counters and its forms' counters. Every\n * other reader an insight reads is registered by the plugin that owns its\n * records — commerce, bookings, marketing, the workspace's datasets — on the\n * `plugin-figures` seam, and nothing here reads their documents.\n *\n * Each reader answers with one compact table of aggregates, read-only and\n * about nobody: counts, sums and rates, labeled by a page path, a form's name\n * or a referring site — never a visitor or a submission.\n *\n * The readers use the arithmetic their console cards use: the Traffic card's\n * windows and change (`pluginFigureWindows`, `pluginFigureChange`, which are\n * that card's split and delta), and the forms plugin's month counters through\n * `formStatsTotals`, the one function every forms surface windows by.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** How a reader reaches Firestore: resolved when it reads, never when it registers. */\nexport type AiFigureFirestore = () => Firestore\n\n/** The traffic windows: the Traffic card's own ranges. */\nexport const AI_TRAFFIC_WINDOWS: readonly number[] = [7, 14, 30, 90]\n\n/** A day-by-day table fits a table's row bound only over a short window. */\nexport const AI_TRAFFIC_DAILY_WINDOWS: readonly number[] = [7, 14]\n\n/** Pages a pages table lists; the rest are counted in `omitted`. */\nexport const AI_TRAFFIC_TOP_PAGES = 10\n\n/** Referring sites, and campaign sources and campaigns, a sources table lists. */\nexport const AI_TRAFFIC_TOP_REFERRERS = 8\nexport const AI_TRAFFIC_TOP_CAMPAIGNS = 5\n\n/** Forms a forms table reads. */\nexport const AI_FORMS_READ_LIMIT = 100\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nconst num = (value: unknown): number => {\n const parsed = typeof value === 'number' ? value : Number(value)\n return Number.isFinite(parsed) ? parsed : 0\n}\n\nconst round1 = (value: number): number => Math.round(value * 10) / 10\n\nconst share = (part: number, whole: number): number | null => (whole > 0 ? round1((part / whole) * 100) : null)\n\nfunction refused(status: 400 | 403 | 404, error: string): PluginFigureRead {\n return { ok: false, status, error }\n}\n\n/** A window's days as the table's period, oldest to newest. */\nfunction periodOf(request: PluginFigureRequest): PluginFigureTable['period'] {\n const { current } = pluginFigureWindows(request.now, request.days)\n return { from: current.from, to: current.to, days: request.days }\n}\n\n/** Every day id of the window and the one before it, newest first. */\nfunction dayIds(now: Date, days: number): { current: string[]; previous: string[] } {\n const { current, previous } = pluginFigureWindows(now, days)\n const walk = (startMs: number, endMs: number): string[] => {\n const ids: string[] = []\n for (let at = endMs - 86_400_000; at >= startMs; at -= 86_400_000) ids.push(pluginFigureDay(new Date(at)))\n return ids\n }\n return { current: walk(current.startMs, current.endMs), previous: walk(previous.startMs, previous.endMs) }\n}\n\n// ── Traffic ───────────────────────────────────────────────────────────────\n\ninterface TrafficDay {\n total: number\n visitors: number\n paths: Record<string, number>\n referrers: Record<string, number>\n utm: Record<string, Record<string, number>>\n}\n\nconst counts = (value: unknown): Record<string, number> => {\n const out: Record<string, number> = {}\n if (!value || typeof value !== 'object') return out\n for (const [key, count] of Object.entries(value as Record<string, unknown>)) {\n const n = num(count)\n if (n > 0) out[key] = n\n }\n return out\n}\n\nasync function readTrafficDays(\n firestore: Firestore,\n hostId: string,\n ids: readonly string[],\n): Promise<TrafficDay[]> {\n if (!ids.length) return []\n const collection = firestore.collection('hosts').doc(hostId).collection('analytics')\n const snapshots = await firestore.getAll(...ids.map((id) => collection.doc(id)))\n return snapshots.map((snapshot) => {\n const data = (snapshot.exists ? snapshot.data() : null) ?? {}\n const utm: Record<string, Record<string, number>> = {}\n for (const [param, values] of Object.entries((data['utm'] ?? {}) as Record<string, unknown>)) {\n utm[param] = counts(values)\n }\n return {\n total: num(data['total']),\n visitors: num(data['visitors']),\n paths: counts(data['paths']),\n referrers: counts(data['referrers']),\n utm,\n }\n })\n}\n\nfunction sumMaps(days: readonly TrafficDay[], pick: (day: TrafficDay) => Record<string, number>): Map<string, number> {\n const totals = new Map<string, number>()\n for (const day of days) {\n for (const [key, count] of Object.entries(pick(day))) totals.set(key, (totals.get(key) ?? 0) + count)\n }\n return totals\n}\n\nconst ranked = (totals: Map<string, number>): Array<[string, number]> =>\n [...totals.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n\nfunction siteReader(\n base: Omit<PluginFigureReader, 'read' | 'scope' | 'plugin'>,\n read: (firestore: Firestore, request: PluginFigureRequest & { hostId: string }) => Promise<PluginFigureRead>,\n firestore: AiFigureFirestore,\n plugin: string | null,\n): PluginFigureReader {\n return {\n ...base,\n scope: 'site',\n plugin,\n read: async (request) => {\n if (!request.hostId) return refused(400, 'Open a site to read its figures')\n if (!base.windows.includes(request.days)) return refused(400, 'That window is not one this reader covers')\n return read(firestore(), { ...request, hostId: request.hostId })\n },\n }\n}\n\nexport function trafficFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n const source = { label: 'Analytics', path: 'analytics' }\n const visitorsNote =\n 'Visitors are counted once per browser tab per day, so one person on two days counts twice.'\n return [\n siteReader(\n {\n id: 'traffic.summary',\n label: 'Traffic',\n description:\n 'Page views, visitors and views a day on the site over the window, each beside the window before it and the change.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TRAFFIC_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const total = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.total, 0)\n const visitors = (days: TrafficDay[]) => days.reduce((sum, day) => sum + day.visitors, 0)\n const views = total(current)\n const viewsBefore = total(previous)\n const perDay = Math.round(views / request.days)\n const perDayBefore = Math.round(viewsBefore / request.days)\n const table: PluginFigureTable = {\n title: 'Traffic',\n source,\n period: periodOf(request),\n columns: [\n { key: 'figure', label: 'Figure', kind: 'text' },\n { key: 'current', label: 'This window', kind: 'count' },\n { key: 'previous', label: 'Window before', kind: 'count' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows: [\n { figure: 'Page views', current: views, previous: viewsBefore, change: pluginFigureChange(views, viewsBefore) },\n {\n figure: 'Visitors',\n current: visitors(current),\n previous: visitors(previous),\n change: pluginFigureChange(visitors(current), visitors(previous)),\n },\n {\n figure: 'Page views a day',\n current: perDay,\n previous: perDayBefore,\n change: pluginFigureChange(perDay, perDayBefore),\n },\n ],\n omitted: 0,\n notes: [\n visitorsNote,\n ...(viewsBefore ? [] : ['The window before this one recorded no page views, so there is no change to compare.']),\n ],\n }\n return { ok: true, table }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.pages',\n label: 'Top pages',\n description: `The site's ${AI_TRAFFIC_TOP_PAGES} most viewed pages over the window, with each page's share of all views and its change from the window before.`,\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: TOP_PAGES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = dayIds(request.now, request.days)\n const [current, previous] = await Promise.all([\n readTrafficDays(db, request.hostId, ids.current),\n readTrafficDays(db, request.hostId, ids.previous),\n ])\n const now = ranked(sumMaps(current, (day) => day.paths))\n const before = sumMaps(previous, (day) => day.paths)\n const all = now.reduce((sum, [, count]) => sum + count, 0)\n const rows: PluginFigureRow[] = now.slice(0, AI_TRAFFIC_TOP_PAGES).map(([path, views]) => ({\n page: path,\n views,\n share: share(views, all),\n change: pluginFigureChange(views, before.get(path) ?? null),\n }))\n return {\n ok: true,\n table: {\n title: 'Top pages',\n source,\n period: periodOf(request),\n columns: [\n { key: 'page', label: 'Page', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of views', kind: 'percent' },\n { key: 'change', label: 'Change', kind: 'change' },\n ],\n rows,\n omitted: Math.max(0, now.length - rows.length),\n notes: [],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.sources',\n label: 'Traffic sources',\n description:\n 'Where visits came from over the window: the referring sites, and the campaign sources and campaigns links were tagged with, with each one’s views.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: SOURCES_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const days = await readTrafficDays(db, request.hostId, dayIds(request.now, request.days).current)\n const all = days.reduce((sum, day) => sum + day.total, 0)\n // The collector stores a referring host with its dots as `_`, because a\n // Firestore field path cannot hold one; a host is read back as written.\n const referrers = ranked(sumMaps(days, (day) => day.referrers)).map(\n ([host, views]): [string, number] => [host.replace(/_/g, '.'), views],\n )\n const sources = ranked(sumMaps(days, (day) => day.utm['source'] ?? {}))\n const campaigns = ranked(sumMaps(days, (day) => day.utm['campaign'] ?? {}))\n const rowsOf = (entries: Array<[string, number]>, limit: number, type: string) =>\n entries.slice(0, limit).map(([name, views]) => ({ source: name, type, views, share: share(views, all) }))\n const rows = [\n ...rowsOf(referrers, AI_TRAFFIC_TOP_REFERRERS, 'Referring site'),\n ...rowsOf(sources, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign source'),\n ...rowsOf(campaigns, AI_TRAFFIC_TOP_CAMPAIGNS, 'Campaign'),\n ]\n return {\n ok: true,\n table: {\n title: 'Traffic sources',\n source,\n period: periodOf(request),\n columns: [\n { key: 'source', label: 'Source', kind: 'text' },\n { key: 'type', label: 'Kind', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'share', label: 'Share of all views', kind: 'percent' },\n ],\n rows,\n omitted:\n Math.max(0, referrers.length - AI_TRAFFIC_TOP_REFERRERS) +\n Math.max(0, sources.length - AI_TRAFFIC_TOP_CAMPAIGNS) +\n Math.max(0, campaigns.length - AI_TRAFFIC_TOP_CAMPAIGNS),\n notes: ['A visit with no referring site, such as a typed address, is in no row.'],\n },\n }\n },\n firestore,\n null,\n ),\n siteReader(\n {\n id: 'traffic.daily',\n label: 'Traffic by day',\n description: 'Page views and visitors on each day of the window, oldest first, for spotting a day that stood out.',\n windows: AI_TRAFFIC_DAILY_WINDOWS,\n weeklySummary: TRAFFIC_DAILY_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const ids = [...dayIds(request.now, request.days).current].reverse()\n const days = await readTrafficDays(db, request.hostId, ids)\n return {\n ok: true,\n table: {\n title: 'Traffic by day',\n source,\n period: periodOf(request),\n columns: [\n { key: 'day', label: 'Day', kind: 'date' },\n { key: 'views', label: 'Page views', kind: 'count' },\n { key: 'visitors', label: 'Visitors', kind: 'count' },\n ],\n rows: days.map((day, index) => ({ day: ids[index], views: day.total, visitors: day.visitors })),\n omitted: 0,\n notes: [visitorsNote],\n },\n }\n },\n firestore,\n null,\n ),\n ]\n}\n\n// ── Forms ─────────────────────────────────────────────────────────────────\n\nexport function formsFigureReader(firestore: AiFigureFirestore): PluginFigureReader {\n return siteReader(\n {\n id: 'forms.performance',\n label: 'Forms',\n description:\n 'Each form’s views, submissions, the share of views that became a submission, and leads, over the calendar months the window falls in.',\n windows: AI_TRAFFIC_WINDOWS,\n weeklySummary: FORMS_WEEKLY_SUMMARY,\n },\n async (db, request) => {\n const { current } = pluginFigureWindows(request.now, request.days)\n const from = formPeriodKey(current.startMs)\n const to = formPeriodKey(current.endMs - 1)\n const snapshot = await db\n .collection('hosts')\n .doc(request.hostId)\n .collection('forms')\n .limit(AI_FORMS_READ_LIMIT)\n .get()\n const forms = snapshot.docs\n .map((doc) => ({ doc, data: (doc.data() ?? {}) as Record<string, unknown> }))\n .filter(({ data }) => !data['deletedAt'])\n .map(({ doc, data }) => {\n const totals = formStatsTotals(data['stats'] as FormStats | undefined, { from, to })\n // Every submission to a form is counted on it, so a form with none\n // recorded in the window had none: 0, not a blank the answer has to\n // hedge over (AGL-3834). Leads are counted only on a form that\n // routes them, so one that does reads 0 the same way, and a form\n // that never has keeps a blank, which the table's note explains.\n const submissions = totals.submissions ?? 0\n const routesLeads = (data['routing'] as { lead?: unknown } | undefined)?.lead === true\n return {\n form: str(data['displayName']) || doc.id,\n views: totals.views,\n submissions,\n completion: totals.views ? share(submissions, totals.views) : null,\n leads: totals.leads ?? (routesLeads ? 0 : null),\n }\n })\n .sort((a, b) => b.submissions - a.submissions || a.form.localeCompare(b.form))\n const monthStart = from ? `${from}-01` : current.from\n return {\n ok: true,\n table: {\n title: 'Forms',\n source: { label: 'Forms', path: 'forms' },\n period: {\n from: monthStart,\n to: current.to,\n days: Math.round((Date.parse(current.to) - Date.parse(monthStart)) / 86_400_000) + 1,\n },\n columns: [\n { key: 'form', label: 'Form', kind: 'text' },\n { key: 'views', label: 'Views', kind: 'count' },\n { key: 'submissions', label: 'Submissions', kind: 'count' },\n { key: 'completion', label: 'Views that became a submission', kind: 'percent' },\n { key: 'leads', label: 'Leads', kind: 'count' },\n ],\n rows: forms.slice(0, PLUGIN_FIGURE_MAX_ROWS),\n omitted: Math.max(0, forms.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: [\n 'Form figures are kept by calendar month, so they cover whole months from the first day of the month the window starts in.',\n 'Views are counted in the visitor’s browser and submissions on the server, so a rate can pass 100%.',\n 'A blank Leads figure means the form does not add its submissions to Leads.',\n ],\n },\n }\n },\n firestore,\n 'forms',\n )\n}\n\n/** Every reader this plugin registers, for the platform's own records. */\nexport function aiFigureReaders(firestore: AiFigureFirestore): PluginFigureReader[] {\n return [...trafficFigureReaders(firestore), formsFigureReader(firestore)]\n}\n\n/**\n * Registers them from the console surface, the one surface that runs insight\n * jobs. By a call, never by an import (AGL-3025).\n */\nexport function registerAiFigureReaders(firestore: AiFigureFirestore): void {\n for (const reader of aiFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: AI_PLUGIN_ID })\n }\n}\n"],"names":["formPeriodKey","formStatsTotals","PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureDay","pluginFigureWindows","registerPluginFigureReader","AI_PLUGIN_ID","FORMS_WEEKLY_SUMMARY","SOURCES_WEEKLY_SUMMARY","TOP_PAGES_WEEKLY_SUMMARY","TRAFFIC_DAILY_WEEKLY_SUMMARY","TRAFFIC_WEEKLY_SUMMARY","AI_TRAFFIC_WINDOWS","AI_TRAFFIC_DAILY_WINDOWS","AI_TRAFFIC_TOP_PAGES","AI_TRAFFIC_TOP_REFERRERS","AI_TRAFFIC_TOP_CAMPAIGNS","AI_FORMS_READ_LIMIT","str","value","trim","num","parsed","Number","isFinite","round1","Math","round","share","part","whole","refused","status","error","ok","periodOf","request","current","now","days","from","to","dayIds","previous","walk","startMs","endMs","ids","at","push","Date","counts","out","key","count","Object","entries","n","readTrafficDays","firestore","hostId","length","collection","doc","snapshots","getAll","map","id","snapshot","data","exists","utm","param","values","total","visitors","paths","referrers","sumMaps","pick","totals","Map","day","set","get","ranked","sort","a","b","localeCompare","siteReader","base","read","plugin","scope","windows","includes","trafficFigureReaders","source","label","path","visitorsNote","description","weeklySummary","db","Promise","all","reduce","sum","views","viewsBefore","perDay","perDayBefore","table","title","period","columns","kind","rows","figure","change","omitted","notes","before","slice","page","max","host","replace","sources","campaigns","rowsOf","limit","type","name","reverse","index","formsFigureReader","forms","docs","filter","submissions","routesLeads","lead","form","completion","leads","monthStart","parse","aiFigureReaders","registerAiFigureReaders","reader","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,QAAwB,+BAA8B;AAC7F,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,eAAe,EACfC,mBAAmB,EACnBC,0BAA0B,QAMrB,6CAA4C;AACnD,SAASC,YAAY,QAAQ,kBAAc;AAC3C,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,wBAAwB,EACxBC,4BAA4B,EAC5BC,sBAAsB,QACjB,2BAAuB;AAwB9B,wDAAwD,GACxD,OAAO,MAAMC,qBAAwC;IAAC;IAAG;IAAI;IAAI;CAAG,CAAA;AAEpE,0EAA0E,GAC1E,OAAO,MAAMC,2BAA8C;IAAC;IAAG;CAAG,CAAA;AAElE,kEAAkE,GAClE,OAAO,MAAMC,uBAAuB,GAAE;AAEtC,gFAAgF,GAChF,OAAO,MAAMC,2BAA2B,EAAC;AACzC,OAAO,MAAMC,2BAA2B,EAAC;A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AAS8C,OAAO;wBAASkB,MAAM;oBAAQ;iBAC/C;gBACDC,MAAMoB,MAAMd,KAAK,CAAC,GAAG3H;gBACrBwH,SAAS/F,KAAKoG,GAAG,CAAC,GAAGY,MAAM7E,MAAM,GAAG5D;gBACpCyH,OAAO;oBACL;oBACA;oBACA;iBACD;YACH;QACF;IACF,GACA/D,WACA;AAEJ;AAEA,wEAAwE,GACxE,OAAO,SAAS0F,gBAAgB1F,SAA4B;IAC1D,OAAO;WAAIsC,qBAAqBtC;QAAY8E,kBAAkB9E;KAAW;AAC3E;AAEA;;;CAGC,GACD,OAAO,SAAS2F,wBAAwB3F,SAA4B;IAClE,KAAK,MAAM4F,UAAUF,gBAAgB1F,WAAY;QAC/CtD,2BAA2BkJ,QAAQ;YAAEC,UAAUlJ;QAAa;IAC9D;AACF"}
|
|
@@ -22,6 +22,7 @@ import type { PluginFigureWeeklySummary } from '@aglyn/aglyn/plugin-manager/plug
|
|
|
22
22
|
* the email rather than misreporting.
|
|
23
23
|
*/
|
|
24
24
|
export declare const TRAFFIC_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
|
|
25
|
+
export declare const TRAFFIC_DAILY_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
|
|
25
26
|
export declare const TOP_PAGES_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
|
|
26
27
|
export declare const SOURCES_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
|
|
27
28
|
export declare const FORMS_WEEKLY_SUMMARY: PluginFigureWeeklySummary;
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
-
import { figureCount, figureHasColumn, figureRanked, figureRow, figureStat, weeklySummaryDay } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
17
|
+
import { figureBars, figureCount, figureHasColumn, figureRanked, figureRow, figureStat, weeklySummaryDay } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
18
18
|
/**
|
|
19
19
|
* How the traffic and forms readers read in the weekly summary (AGL-3867).
|
|
20
20
|
* Each answers `null` for a week it has nothing to say about, and for a table
|
|
@@ -47,6 +47,16 @@ import { figureCount, figureHasColumn, figureRanked, figureRow, figureStat, week
|
|
|
47
47
|
};
|
|
48
48
|
}
|
|
49
49
|
};
|
|
50
|
+
export const TRAFFIC_DAILY_WEEKLY_SUMMARY = {
|
|
51
|
+
order: 15,
|
|
52
|
+
summarize: (table)=>{
|
|
53
|
+
const bars = figureHasColumn(table, 'views') ? figureBars(table, 'day', 'views') : [];
|
|
54
|
+
return bars.length ? {
|
|
55
|
+
title: 'Traffic by day',
|
|
56
|
+
bars
|
|
57
|
+
} : null;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
50
60
|
export const TOP_PAGES_WEEKLY_SUMMARY = {
|
|
51
61
|
order: 20,
|
|
52
62
|
summarize: (table)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-summaries.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginFigureWeeklySummary } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n figureCount,\n figureHasColumn,\n figureRanked,\n figureRow,\n figureStat,\n weeklySummaryDay,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\n\n/**\n * How the traffic and forms readers read in the weekly summary (AGL-3867).\n * Each answers `null` for a week it has nothing to say about, and for a table\n * that is not the shape it was written for, so a changed reader drops out of\n * the email rather than misreporting.\n */\n\nexport const TRAFFIC_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 10,\n summarize: (table) => {\n const visitors = figureRow(table, 'figure', 'Visitors')\n const views = figureRow(table, 'figure', 'Page views')\n if (!figureCount(visitors?.['current']) && !figureCount(views?.['current'])) return null\n return {\n title: 'Traffic',\n stats: [\n ...(visitors\n ? [figureStat(table, visitors, 'current', 'Visitors', { change: 'change', total: { one: 'visitor', many: 'visitors' } })]\n : []),\n ...(views ? [figureStat(table, views, 'current', 'Page views', { change: 'change' })] : []),\n ],\n }\n },\n}\n\nexport const TOP_PAGES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 20,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'page', 'views') : []\n return rows.length ? { title: 'Top pages', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const SOURCES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 30,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'source', 'views') : []\n return rows.length ? { title: 'Where visits came from', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const FORMS_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 40,\n summarize: (table) => {\n if (!figureHasColumn(table, 'submissions')) return null\n const total = table.rows.reduce((sum, row) => sum + figureCount(row['submissions']), 0)\n if (!total) return null\n // Form figures are kept by calendar month, so the block says so rather\n // than calling a month-to-date count \"last week\".\n const since = table.period ? weeklySummaryDay(table.period.from) : null\n return {\n title: 'Forms',\n stats: [\n {\n label: since ? `Submissions since ${since}` : 'Submissions',\n value: total.toLocaleString('en-US'),\n },\n ],\n rows: figureRanked(table, 'form', 'submissions'),\n }\n },\n}\n"],"names":["figureCount","figureHasColumn","figureRanked","figureRow","figureStat","weeklySummaryDay","TRAFFIC_WEEKLY_SUMMARY","order","summarize","table","visitors","views","title","stats","change","total","one","many","
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-figure-summaries.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginFigureWeeklySummary } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n figureBars,\n figureCount,\n figureHasColumn,\n figureRanked,\n figureRow,\n figureStat,\n weeklySummaryDay,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\n\n/**\n * How the traffic and forms readers read in the weekly summary (AGL-3867).\n * Each answers `null` for a week it has nothing to say about, and for a table\n * that is not the shape it was written for, so a changed reader drops out of\n * the email rather than misreporting.\n */\n\nexport const TRAFFIC_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 10,\n summarize: (table) => {\n const visitors = figureRow(table, 'figure', 'Visitors')\n const views = figureRow(table, 'figure', 'Page views')\n if (!figureCount(visitors?.['current']) && !figureCount(views?.['current'])) return null\n return {\n title: 'Traffic',\n stats: [\n ...(visitors\n ? [figureStat(table, visitors, 'current', 'Visitors', { change: 'change', total: { one: 'visitor', many: 'visitors' } })]\n : []),\n ...(views ? [figureStat(table, views, 'current', 'Page views', { change: 'change' })] : []),\n ],\n }\n },\n}\n\nexport const TRAFFIC_DAILY_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 15,\n summarize: (table) => {\n const bars = figureHasColumn(table, 'views') ? figureBars(table, 'day', 'views') : []\n return bars.length ? { title: 'Traffic by day', bars } : null\n },\n}\n\nexport const TOP_PAGES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 20,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'page', 'views') : []\n return rows.length ? { title: 'Top pages', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const SOURCES_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 30,\n summarize: (table) => {\n const rows = figureHasColumn(table, 'views') ? figureRanked(table, 'source', 'views') : []\n return rows.length ? { title: 'Where visits came from', rows: rows.map((row) => ({ ...row, value: `${row.value} views` })) } : null\n },\n}\n\nexport const FORMS_WEEKLY_SUMMARY: PluginFigureWeeklySummary = {\n order: 40,\n summarize: (table) => {\n if (!figureHasColumn(table, 'submissions')) return null\n const total = table.rows.reduce((sum, row) => sum + figureCount(row['submissions']), 0)\n if (!total) return null\n // Form figures are kept by calendar month, so the block says so rather\n // than calling a month-to-date count \"last week\".\n const since = table.period ? weeklySummaryDay(table.period.from) : null\n return {\n title: 'Forms',\n stats: [\n {\n label: since ? `Submissions since ${since}` : 'Submissions',\n value: total.toLocaleString('en-US'),\n },\n ],\n rows: figureRanked(table, 'form', 'submissions'),\n }\n },\n}\n"],"names":["figureBars","figureCount","figureHasColumn","figureRanked","figureRow","figureStat","weeklySummaryDay","TRAFFIC_WEEKLY_SUMMARY","order","summarize","table","visitors","views","title","stats","change","total","one","many","TRAFFIC_DAILY_WEEKLY_SUMMARY","bars","length","TOP_PAGES_WEEKLY_SUMMARY","rows","map","row","value","SOURCES_WEEKLY_SUMMARY","FORMS_WEEKLY_SUMMARY","reduce","sum","since","period","from","label","toLocaleString"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,UAAU,EACVC,WAAW,EACXC,eAAe,EACfC,YAAY,EACZC,SAAS,EACTC,UAAU,EACVC,gBAAgB,QACX,wCAAuC;AAE9C;;;;;CAKC,GAED,OAAO,MAAMC,yBAAoD;IAC/DC,OAAO;IACPC,WAAW,CAACC;QACV,MAAMC,WAAW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S,aAAKA;oBAAKC,OAAO,GAAGD,IAAIC,KAAK,CAAC,MAAM,CAAC;;QAAK,IAAI;IACjI;AACF,EAAC;AAED,OAAO,MAAME,uBAAkD;IAC7DpB,OAAO;IACPC,WAAW,CAACC;QACV,IAAI,CAACR,gBAAgBQ,OAAO,gBAAgB,OAAO;QACnD,MAAMM,QAAQN,MAAMa,IAAI,CAACM,MAAM,CAAC,CAACC,KAAKL,MAAQK,MAAM7B,YAAYwB,GAAG,CAAC,cAAc,GAAG;QACrF,IAAI,CAACT,OAAO,OAAO;QACnB,uEAAuE;QACvE,kDAAkD;QAClD,MAAMe,QAAQrB,MAAMsB,MAAM,GAAG1B,iBAAiBI,MAAMsB,MAAM,CAACC,IAAI,IAAI;QACnE,OAAO;YACLpB,OAAO;YACPC,OAAO;gBACL;oBACEoB,OAAOH,QAAQ,CAAC,kBAAkB,EAAEA,OAAO,GAAG;oBAC9CL,OAAOV,MAAMmB,cAAc,CAAC;gBAC9B;aACD;YACDZ,MAAMpB,aAAaO,OAAO,QAAQ;QACpC;IACF;AACF,EAAC"}
|
|
@@ -20,7 +20,7 @@ import { liveCustomDomain, TENANT_APEX } from "@aglyn/aglyn/app-utils/host-namin
|
|
|
20
20
|
import { hostRoleFor } from "@aglyn/aglyn/app-utils/organizations";
|
|
21
21
|
import { checkEntitlement, resolveBrandingProfile, resolveEffectivePlan } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
22
22
|
import { isReleaseFlagOnForOrg, parseOrgReleaseFlagOverrides } from "@aglyn/aglyn/app-utils/release-flags";
|
|
23
|
-
import { weeklySummaryFootnoteHtml, weeklySummaryPeriod, weeklySummaryPlainDates, weeklySummarySectionsHtml, weeklySummaryTilesHtml, weeklySummaryWeekday } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
23
|
+
import { weeklySummaryFootnoteHtml, weeklySummaryPeriod, weeklySummaryPlainDates, weeklySummarySectionsHtml, weeklySummaryTilesHtml, weeklySummaryRowLink, weeklySummaryWeekday } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
24
24
|
import { normalizePluginFigureTable, pluginFigureCellText, pluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
25
25
|
import { aiInsightDigestPeriod, aiInsightSourceHref, AI_INSIGHTS_COLLECTION, aiInsightIsoWeek } from "../model/ai-insight.js";
|
|
26
26
|
import { isAiOnForSite } from "../model/ai-site-switch.js";
|
|
@@ -108,14 +108,6 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
108
108
|
...new Set(rows)
|
|
109
109
|
].filter((row)=>Number.isInteger(row) && table.rows[row]);
|
|
110
110
|
}
|
|
111
|
-
/** A row's label as a person reads it, and the page it names, when it names one. */ function rowLabel(value, siteUrl) {
|
|
112
|
-
const label = String(value != null ? value : '');
|
|
113
|
-
const path = label.startsWith('/');
|
|
114
|
-
return {
|
|
115
|
-
label: label === '/' ? 'Home' : label,
|
|
116
|
-
url: path && siteUrl ? `${siteUrl}${label === '/' ? '' : label}` : null
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
111
|
/**
|
|
120
112
|
* A section's figures, from the table's own columns, so a reader added
|
|
121
113
|
* tomorrow draws without a line here: a table of days is a chart of the week
|
|
@@ -147,9 +139,10 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
147
139
|
const shown = figures.slice(0, change ? 1 : 2);
|
|
148
140
|
return {
|
|
149
141
|
rows: cited.slice(0, AI_INSIGHT_DIGEST_MAX_ROWS).map((index)=>{
|
|
142
|
+
var _row_label_key;
|
|
150
143
|
const row = table.rows[index];
|
|
151
144
|
const moved = change ? row[change.key] : null;
|
|
152
|
-
return _extends({},
|
|
145
|
+
return _extends({}, weeklySummaryRowLink(String((_row_label_key = row[label.key]) != null ? _row_label_key : ''), siteUrl), {
|
|
153
146
|
value: shown.map((column)=>text(column, row)).join(' · '),
|
|
154
147
|
change: typeof moved === 'number' ? moved : null
|
|
155
148
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-insight-digest.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 { FieldPath } from 'firebase-admin/firestore'\nimport { INSIGHT_DIGESTS_FIELD, insightDigestSubscribed, notificationMuted } from '@aglyn/aglyn/app-utils/notifications'\nimport { liveCustomDomain, TENANT_APEX } from '@aglyn/aglyn/app-utils/host-naming'\nimport { hostRoleFor } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement, resolveBrandingProfile, resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { isReleaseFlagOnForOrg, parseOrgReleaseFlagOverrides, type ReleaseFlagValue } from '@aglyn/aglyn/app-utils/release-flags'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n weeklySummaryFootnoteHtml,\n weeklySummaryPeriod,\n weeklySummaryPlainDates,\n weeklySummarySectionsHtml,\n weeklySummaryTilesHtml,\n weeklySummaryWeekday,\n type WeeklySummaryColors,\n type WeeklySummarySection,\n type WeeklySummarySectionBar,\n type WeeklySummarySectionRow,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\nimport {\n normalizePluginFigureTable,\n pluginFigureCellText,\n pluginFigureReader,\n type PluginFigureColumn,\n type PluginFigureSummaryStat,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n aiInsightDigestPeriod,\n aiInsightSourceHref,\n AI_INSIGHTS_COLLECTION,\n aiInsightIsoWeek,\n type AiInsight,\n type AiInsightRecord,\n type AiInsightTable,\n} from '../model/ai-insight'\nimport { isAiOnForSite } from '../model/ai-site-switch'\nimport { cancelAiJob, createAiJob, getAiJob } from '../jobs/ai-jobs'\n\n/**\n * THE WEEKLY INSIGHTS (AGL-2915): `POST /api/admin/ai-insights-digest`, twice\n * a day on the console's scheduler.\n *\n * ## Who asked for it\n *\n * A person turns weekly insights on for a workspace beside the answers\n * themselves (`users/{uid}.insightDigests.{orgId}`), and off there or in\n * Notifications. It is opt-in, because each digest is a generation the\n * workspace pays for. At the sweep, every rung is asked again rather than\n * trusted from the switch: the workspace's plan includes `aiGenerative`,\n * `release_ai_generative` is on for it, its AI is not paused, the site has AI\n * on, and the person still holds `ai.generate` on the site.\n *\n * ## Monday: one job per site\n *\n * On a Monday run, for each workspace with someone who asked, the sites those\n * people reach — the busiest `AI_INSIGHT_DIGEST_MAX_SITES` by yesterday's page\n * views — each get one `insight` job with the `digest` surface, created by the\n * first of them who may generate there. The job runs on the AI jobs beat like\n * any other: it reserves, meters and records its credits, and a workspace at\n * its band — a Free one that has used its credits — has its job parked by the\n * reservation like any other. `orgs/{orgId}/aiInsightDigests/{week}` records\n * the jobs; `aiInsightDigestQueue/{week}` lists the workspaces still owed a\n * delivery, so a run that delivers reads one document rather than every\n * workspace.\n *\n * ## Every run: deliver what is written\n *\n * A digest whose job is done and kept at least one insight is delivered once:\n * a `content.insightsDigest` notification (unless the person muted the\n * category) and an email through the platform's own sending path, to each\n * person who asked for the workspace's insights and reaches the site. A job\n * that failed, kept nothing, or parked for credits is SKIPPED SILENTLY: a\n * parked job is canceled rather than left to spend later, and nobody is told,\n * because nobody asked about that week in particular. A job still running\n * past `AI_INSIGHT_DIGEST_DEADLINE_MS` is canceled and skipped the same way.\n *\n * The email says only what the answer says, drawn to be run down rather than\n * read: the week's headline figures as tiles, then one section a topic, however\n * many insights cite it, each with its headline, the figures those insights\n * cite and a link to where they live. Every reader draws the same way, from its\n * table's own columns. It is sent by the platform to a person who asked for it,\n * never to a contact.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport const AI_INSIGHTS_DIGEST_CRON_ID = 'ai-insights-digest'\nexport const AI_INSIGHTS_DIGEST_PATH = 'admin/ai-insights-digest'\n\n/** Orgs one call reads; a chunk that times out never advances the cursor, so the safe size is one that finishes. */\nexport const AI_INSIGHT_DIGEST_ORG_CHUNK = 25\n\n/** Sites one workspace's digest covers a week. */\nexport const AI_INSIGHT_DIGEST_MAX_SITES = 5\n\n/** Sites a workspace's sweep reads before it ranks them. */\nexport const AI_INSIGHT_DIGEST_HOST_READ_LIMIT = 50\n\n/** Workspaces one run delivers to, per week. */\nexport const AI_INSIGHT_DIGEST_DELIVER_LIMIT = 100\n\n/** How long a digest's job may take before its week is given up. */\nexport const AI_INSIGHT_DIGEST_DEADLINE_MS = 48 * 60 * 60_000\n\n/**\n * The time one call works before it stops and leaves the rest to the next:\n * inside the plugin dispatcher's 60 s function ceiling, with room for the\n * reads before the first check and the reply after the last. A call killed\n * mid-send could send one person a site's digest twice, because a send is\n * stamped after it goes.\n */\nexport const AI_INSIGHT_DIGEST_RUN_BUDGET_MS = 45_000\n\nexport const AI_INSIGHT_DIGEST_MARKERS = 'aiInsightDigests'\nexport const AI_INSIGHT_DIGEST_QUEUE = 'aiInsightDigestQueue'\n\nexport type AiInsightDigestSiteState = 'pending' | 'delivered' | 'skipped'\n\nexport interface AiInsightDigestSite {\n jobId: string\n name: string\n state: AiInsightDigestSiteState\n /**\n * The people already sent this site's digest, so a run the send rate\n * stopped never sends one twice. Dropped when the site settles, so a\n * settled marker names no person.\n */\n sent?: Record<string, boolean>\n}\n\nexport interface AiInsightDigestMarker {\n week: string\n createdAtMs: number\n sites: Record<string, AiInsightDigestSite>\n}\n\n/** What a send answered: whether it went, and whether the platform's send rate refused it for now. */\nexport interface AiInsightDigestSendResult {\n sent: boolean\n rateLimited: boolean\n}\n\n/** Everything the sweep reaches beyond Firestore, so a spec can hold each one. */\nexport interface AiInsightDigestDeps {\n firestore: Firestore\n now: Date\n flagValue: ReleaseFlagValue\n listMembers: (orgId: string) => Promise<AglynOrgMember[]>\n mayGenerate: (orgId: string, hostId: string, member: AglynOrgMember) => Promise<boolean>\n paused: (orgId: string) => Promise<boolean>\n notify: (uid: string, payload: { title: string; body: string; link: string; orgId: string; hostId: string }) => Promise<void>\n send: (email: {\n to: string\n subject: string\n text: string\n fromName: string\n /** The site the digest is about, and the org whose brand it wears (AGL-3367). */\n siteName: string\n org: Record<string, unknown>\n /** The designed email's merge values, from {@link aiInsightDigestEmailParts}. */\n merge?: Record<string, string>\n }) => Promise<AiInsightDigestSendResult>\n /** The console's absolute origin for an email link, or `''` when none is configured. */\n consoleOrigin: string\n /** The org's email theme, as the digest's drawing needs it. */\n colors: (org: Record<string, unknown>) => WeeklySummaryColors\n /** The call's working time; `AI_INSIGHT_DIGEST_RUN_BUDGET_MS` unless a spec holds it. */\n budgetMs?: number\n}\n\nexport interface AiInsightDigestReport {\n week: string\n swept: number\n created: number\n delivered: number\n skipped: number\n /** The send rate refused or the call's time ran out; the run stops, and the next one delivers the rest. */\n deferred: boolean\n nextCursor: string | null\n done: boolean\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The week a Monday digest covers: the week the run falls in. */\nexport function aiInsightDigestWeek(now: Date): string {\n return aiInsightIsoWeek(now)\n}\n\n/** The week before, whose late digests a run still delivers. */\nfunction previousWeek(now: Date): string {\n return aiInsightIsoWeek(new Date(now.getTime() - 7 * 86_400_000))\n}\n\n/**\n * A digest email's words: the insights, the site's Analytics page, and where\n * to turn it off. The digest is an AI job metered against the workspace, so\n * it says what it drew, and it names the workspace a member of several asked\n * for it in.\n */\nexport function aiInsightDigestEmailText(input: {\n siteName: string\n productName: string\n insights: ReadonlyArray<{ text: string }>\n /** Absolute links, or `null` where no console origin is configured to build one from. */\n analyticsUrl: string | null\n settingsUrl: string | null\n /** The workspace the digest was asked for in; `''` falls back to \"this workspace\". */\n workspaceName?: string\n /** The AI credits the digest's job drew; 0 or absent says nothing. */\n creditsSpent?: number\n /** The week the figures cover, \"Oct 5 – Oct 11\"; absent says \"this week\". */\n periodLabel?: string\n}): string {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const drew = credits\n ? ` Writing it used ${credits.toLocaleString('en-US')} of ` +\n `${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n const forWhom = workspace || 'this workspace'\n return [\n input.periodLabel\n ? `Here is what ${input.siteName}'s figures showed last week, ${input.periodLabel}.${drew}`\n : `Here is what ${input.siteName}'s figures showed this week.${drew}`,\n '',\n ...input.insights.map((insight, index) => `${index + 1}. ${aiInsightDigestLine(insight)}`),\n '',\n input.analyticsUrl\n ? `Each of these is traced to the figures it cites. See them in ${input.productName}: ${input.analyticsUrl}`\n : `Each of these is traced to the figures it cites. See them on the site's Analytics page in ${input.productName}.`,\n '',\n input.settingsUrl\n ? `You asked for weekly insights for ${forWhom}. Turn them off in Notifications: ${input.settingsUrl}`\n : `You asked for weekly insights for ${forWhom}. Turn them off in your Notifications settings.`,\n ].join('\\n')\n}\n\n/** An insight in one line of plain text, its dates as a person says them. */\nfunction aiInsightDigestLine(insight: { text: string; headline?: string | null }): string {\n const text = weeklySummaryPlainDates(insight.text)\n return insight.headline ? `${insight.headline}: ${text}` : text\n}\n\n/** The most tiles the digest leads with: one row. */\nexport const AI_INSIGHT_DIGEST_MAX_TILES = 3\n\n/** The most rows a section lists. */\nexport const AI_INSIGHT_DIGEST_MAX_ROWS = 5\n\n/** The columns that hold a figure a row can show, as against a label or a change. */\nconst FIGURE_KINDS: ReadonlyArray<PluginFigureColumn['kind']> = ['count', 'money', 'percent', 'duration']\n\n/**\n * Each table the job read, as its reader's owner would headline it in the\n * weekly summary. Only a figure compared with the week before earns a tile: a\n * month's running count beside two weeks' does not read as the same kind of\n * thing.\n */\nfunction aiInsightDigestTiles(tables: readonly AiInsightTable[]): Array<{ ref: string; stats: readonly PluginFigureSummaryStat[] }> {\n return tables\n .flatMap((source) => {\n const summary = pluginFigureReader(source.reader)?.reader.weeklySummary\n const table = summary ? normalizePluginFigureTable(source) : null\n const stats = (table ? (summary?.summarize(table)?.stats ?? []) : []).filter((stat) => typeof stat.change === 'number')\n return stats.length ? [{ ref: source.ref, stats, order: summary?.order ?? 0 }] : []\n })\n .sort((a, b) => a.order - b.order)\n}\n\n/** The row numbers a set of insights cite in a table, each once, in the order they cite them. */\nfunction citedRows(insights: readonly AiInsight[], table: AiInsightTable): number[] {\n const rows = insights.flatMap((insight) =>\n insight.cites.filter((cite) => cite.table === table.ref).flatMap((cite) => cite.rows),\n )\n return [...new Set(rows)].filter((row) => Number.isInteger(row) && table.rows[row])\n}\n\n/** A row's label as a person reads it, and the page it names, when it names one. */\nfunction rowLabel(value: unknown, siteUrl: string | null): Pick<WeeklySummarySectionRow, 'label' | 'url'> {\n const label = String(value ?? '')\n const path = label.startsWith('/')\n return { label: label === '/' ? 'Home' : label, url: path && siteUrl ? `${siteUrl}${label === '/' ? '' : label}` : null }\n}\n\n/**\n * A section's figures, from the table's own columns, so a reader added\n * tomorrow draws without a line here: a table of days is a chart of the week\n * with the cited days marked, and any other is its cited rows, each with its\n * change where the table has one, else with its second figure.\n */\nfunction aiInsightDigestFigures(\n table: AiInsightTable,\n cited: readonly number[],\n siteUrl: string | null,\n): Pick<WeeklySummarySection, 'rows' | 'bars'> {\n const label = table.columns.find((column) => column.kind === 'text' || column.kind === 'date')\n const figures = table.columns.filter((column) => FIGURE_KINDS.includes(column.kind))\n const change = table.columns.find((column) => column.kind === 'change')\n if (!label || !figures.length || !cited.length) return {}\n // A `figure` row names what it counts. Any other row's count takes its column's word.\n const counted = label.key !== 'figure'\n const text = (column: PluginFigureColumn, row: AiInsightTable['rows'][number]) => {\n const cell = pluginFigureCellText(table, column.key, row[column.key])\n return counted && column.kind === 'count' ? `${cell} ${column.label.toLowerCase()}` : cell\n }\n if (label.kind === 'date') {\n const [figure] = figures\n const bars: WeeklySummarySectionBar[] = table.rows.map((row, index) => ({\n label: weeklySummaryWeekday(String(row[label.key])),\n value: Number(row[figure.key]) || 0,\n display: pluginFigureCellText(table, figure.key, row[figure.key]),\n marked: cited.includes(index),\n }))\n return { bars }\n }\n const shown = figures.slice(0, change ? 1 : 2)\n return {\n rows: cited.slice(0, AI_INSIGHT_DIGEST_MAX_ROWS).map((index) => {\n const row = table.rows[index]\n const moved = change ? row[change.key] : null\n return {\n ...rowLabel(row[label.key], siteUrl),\n value: shown.map((column) => text(column, row)).join(' · '),\n change: typeof moved === 'number' ? moved : null,\n }\n }),\n }\n}\n\n/** The digest's topics: one a table, however many insights cite it, in the order they first come up. */\nfunction aiInsightDigestSections(\n insights: readonly AiInsight[],\n input: { tables: readonly AiInsightTable[]; siteUrl: string | null; sourceUrl: (table: AiInsightTable) => string | null },\n): WeeklySummarySection[] {\n const groups = new Map<string, { table: AiInsightTable | null; insights: AiInsight[] }>()\n for (const insight of insights) {\n const ref = insight.cites[0]?.table ?? ''\n const group = groups.get(ref) ?? { table: input.tables.find((table) => table.ref === ref) ?? null, insights: [] }\n group.insights.push(insight)\n groups.set(ref, group)\n }\n return [...groups.values()].map(({ table, insights: said }) => {\n const url = table ? input.sourceUrl(table) : null\n return {\n title: table?.title ?? 'What changed',\n link: table && url ? { label: table.source.label, url } : null,\n points: said.map((insight) => ({\n headline: insight.headline?.trim() || null,\n text: weeklySummaryPlainDates(insight.text),\n })),\n ...(table ? aiInsightDigestFigures(table, citedRows(said, table), input.siteUrl) : {}),\n }\n })\n}\n\n/**\n * The digest's drawn parts: the week's figures as tiles, one section a topic,\n * and the small print. An insight that only says what the first tiles already\n * show is left out, so the email never makes a person read the same figures\n * twice.\n */\nexport function aiInsightDigestEmailHtml(input: {\n insights: readonly AiInsight[]\n tables: readonly AiInsightTable[]\n colors: WeeklySummaryColors\n /** The site's own address, which a row naming a page links to. */\n siteUrl: string | null\n /** Where a table's figures live in the console, absolute. */\n sourceUrl: (table: AiInsightTable) => string | null\n /** The sentence that says what the digest cost. */\n why: string\n settingsUrl: string | null\n}): Record<'digest.html' | 'digest.footnote', string> {\n const tiles = aiInsightDigestTiles(input.tables)\n const restated = (insight: AiInsight) =>\n insight.cites.length > 0 && insight.cites.every((cite) => cite.table === tiles[0]?.ref)\n const fresh = input.insights.filter((insight) => !restated(insight))\n return {\n 'digest.html':\n weeklySummaryTilesHtml(tiles.flatMap((part) => part.stats).slice(0, AI_INSIGHT_DIGEST_MAX_TILES), input.colors) +\n weeklySummarySectionsHtml(aiInsightDigestSections(fresh.length ? fresh : input.insights, input), input.colors),\n 'digest.footnote': weeklySummaryFootnoteHtml(\n input.why,\n input.settingsUrl ? { label: 'Turn off weekly insights', url: input.settingsUrl } : null,\n input.colors,\n ),\n }\n}\n\n/**\n * The same digest as {@link aiInsightDigestEmailText}, cut into the parts the\n * `ai-insights-digest` system email draws: the workspace and week above the\n * heading, the figures and insights, a button to the site's Analytics page,\n * what it cost, and where to turn it off.\n */\nexport function aiInsightDigestEmailParts(\n input: Parameters<typeof aiInsightDigestEmailText>[0],\n): Record<\n 'digest.eyebrow' | 'digest.intro' | 'digest.insights' | 'digest.analyticsUrl' | 'digest.why',\n string\n> {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const spent = credits\n ? ` Writing these used ${credits.toLocaleString('en-US')} of ${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n return {\n 'digest.eyebrow': [workspace, input.periodLabel?.trim()].filter(Boolean).join(' · '),\n 'digest.intro':\n `What ${input.siteName}'s figures showed ${input.periodLabel ? 'last week' : 'this week'}. ` +\n 'Each one is traced to the figures it cites, so you can check it on the Analytics page.',\n 'digest.insights': input.insights\n .map((insight, index) => `${index + 1}. ${aiInsightDigestLine(insight)}`)\n .join('\\n\\n'),\n 'digest.analyticsUrl': input.analyticsUrl ?? '',\n 'digest.why': `Every number here is checked against ${input.siteName}'s own figures.${spent}`,\n }\n}\n\nasync function readUsers(firestore: Firestore, uids: readonly string[]) {\n if (!uids.length) return new Map<string, FirebaseFirestore.DocumentSnapshot>()\n const docs = await firestore.getAll(...uids.map((uid) => firestore.collection('users').doc(uid)))\n return new Map(docs.map((doc) => [doc.id, doc]))\n}\n\n/** Creates one workspace's digests for the week; answers how many jobs it created. */\nasync function createOrgDigest(\n deps: AiInsightDigestDeps,\n orgDoc: FirebaseFirestore.QueryDocumentSnapshot,\n week: string,\n): Promise<number> {\n const { firestore, now } = deps\n const orgId = orgDoc.id\n const org = (orgDoc.data() ?? {}) as Record<string, unknown>\n if (!checkEntitlement(org as never, 'aiGenerative')) return 0\n const flagOn = isReleaseFlagOnForOrg(\n 'release_ai_generative',\n deps.flagValue,\n orgId,\n parseOrgReleaseFlagOverrides(org['releaseFlags']),\n resolveEffectivePlan(org as never),\n )\n if (!flagOn || (await deps.paused(orgId))) return 0\n const markerRef = orgDoc.ref.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n if ((await markerRef.get()).exists) return 0\n\n const members = (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const users = await readUsers(firestore, members.map((member) => member.$id).sort())\n const subscribers = members\n .filter((member) => insightDigestSubscribed(users.get(member.$id)?.get(INSIGHT_DIGESTS_FIELD), orgId))\n .sort((a, b) => a.$id.localeCompare(b.$id))\n if (!subscribers.length) return 0\n\n const hosts = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .limit(AI_INSIGHT_DIGEST_HOST_READ_LIMIT)\n .get()\n const yesterday = new Date(now.getTime() - 86_400_000).toISOString().slice(0, 10)\n const candidates: Array<{ hostId: string; name: string; creator: string; views: number }> = []\n for (const host of hosts.docs) {\n const data = host.data() ?? {}\n if (!isAiOnForSite(org, data)) continue\n let creator: string | null = null\n for (const member of subscribers) {\n if (hostRoleFor(member, host.id) !== null && (await deps.mayGenerate(orgId, host.id, member))) {\n creator = member.$id\n break\n }\n }\n if (!creator) continue\n const day = await host.ref.collection('analytics').doc(yesterday).get()\n candidates.push({\n hostId: host.id,\n name: str(data['displayName']) || str(data['name']) || str(data['subdomain']) || host.id,\n creator,\n views: Number(day.get('total') ?? 0) || 0,\n })\n }\n const chosen = candidates\n .sort((a, b) => b.views - a.views || a.hostId.localeCompare(b.hostId))\n .slice(0, AI_INSIGHT_DIGEST_MAX_SITES)\n if (!chosen.length) return 0\n\n const sites: Record<string, AiInsightDigestSite> = {}\n for (const site of chosen) {\n const job = await createAiJob(\n firestore,\n {\n orgId,\n hostId: site.hostId,\n kind: 'insight',\n brief: `Weekly insights for ${site.name}`,\n inputs: { surface: 'digest', week, through: weeklySummaryPeriod(now).to },\n createdBy: site.creator,\n },\n now,\n )\n sites[site.hostId] = { jobId: job.$id, name: site.name, state: 'pending' }\n }\n const marker: AiInsightDigestMarker = { week, createdAtMs: now.getTime(), sites }\n await markerRef.set(marker)\n await firestore\n .collection(AI_INSIGHT_DIGEST_QUEUE)\n .doc(week)\n .set({ week, pending: { [orgId]: true } }, { merge: true })\n return chosen.length\n}\n\n/** Delivers or settles one workspace's digests for a week; `deferred` when the send rate refused. */\nasync function deliverOrgDigest(\n deps: AiInsightDigestDeps,\n orgId: string,\n week: string,\n overBudget: () => boolean,\n): Promise<{ delivered: number; skipped: number; settled: boolean; deferred: boolean }> {\n const { firestore, now } = deps\n const orgRef = firestore.collection('orgs').doc(orgId)\n const markerRef = orgRef.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n const markerSnapshot = await markerRef.get()\n const result = { delivered: 0, skipped: 0, settled: true, deferred: false }\n if (!markerSnapshot.exists) return result\n const marker = markerSnapshot.data() as AiInsightDigestMarker\n const org = ((await orgRef.get()).data() ?? {}) as Record<string, unknown>\n let members: AglynOrgMember[] | null = null\n const branding = resolveBrandingProfile(org as never)\n\n for (const [hostId, site] of Object.entries(marker.sites ?? {})) {\n if (site.state !== 'pending') continue\n const settle = async (state: AiInsightDigestSiteState) => {\n // Replaced whole rather than merged, which drops `sent`.\n const settled: AiInsightDigestSite = { jobId: site.jobId, name: site.name, state }\n await markerRef.update({ [`sites.${hostId}`]: settled })\n if (state === 'delivered') result.delivered += 1\n else result.skipped += 1\n }\n const job = await getAiJob(firestore, orgId, site.jobId)\n if (!job || job.status === 'failed' || job.status === 'canceled') {\n await settle('skipped')\n continue\n }\n if (job.status !== 'done') {\n const late = now.getTime() - Number(marker.createdAtMs ?? 0) > AI_INSIGHT_DIGEST_DEADLINE_MS\n // A job parked for credits — a Free workspace at its band — is given up\n // rather than left to spend on a week that is already over.\n if (job.status === 'needs_input' || late) {\n await cancelAiJob(firestore, orgId, site.jobId, now)\n await settle('skipped')\n } else {\n result.settled = false\n }\n continue\n }\n const answer = await orgRef.collection(AI_INSIGHTS_COLLECTION).doc(site.jobId).get()\n const record = answer.exists ? (answer.data() as AiInsightRecord) : null\n if (!record?.insights?.length) {\n await settle('skipped')\n continue\n }\n\n members ??= (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const reaching = members.filter((member) => hostRoleFor(member, hostId) !== null)\n const users = await readUsers(firestore, reaching.map((member) => member.$id).sort())\n const host = (await firestore.collection('hosts').doc(hostId).get()).data() ?? {}\n const orgSlug = str(org['slug'])\n const subdomain = str(host['subdomain'])\n const origin = deps.consoleOrigin\n const analyticsUrl = origin && orgSlug && subdomain ? `${origin}/${orgSlug}/hosts/${subdomain}/analytics` : null\n for (const member of reaching.sort((a, b) => a.$id.localeCompare(b.$id))) {\n const user = users.get(member.$id)\n if (!insightDigestSubscribed(user?.get(INSIGHT_DIGESTS_FIELD), orgId)) continue\n if (site.sent?.[member.$id]) continue\n if (overBudget()) {\n // Out of time: what was sent is stamped, and the next run sends the rest.\n result.deferred = true\n result.settled = false\n return result\n }\n const address = str(member.email ?? user?.get('email')).toLowerCase()\n if (address.includes('@')) {\n const emailInput = {\n siteName: site.name,\n productName: branding.productName,\n insights: record.insights,\n analyticsUrl,\n settingsUrl: origin ? `${origin}/manage/notifications` : null,\n workspaceName: str(org['name']),\n creditsSpent: job.creditsSpent,\n periodLabel: aiInsightDigestPeriod(job.inputs, new Date(Number(marker.createdAtMs) || now.getTime())).label,\n }\n const parts = aiInsightDigestEmailParts(emailInput)\n const domain = liveCustomDomain(host as never) ?? (subdomain ? `${subdomain}.${TENANT_APEX}` : '')\n const sent = await deps.send({\n to: address,\n subject: `Your weekly insights for ${site.name}`,\n text: aiInsightDigestEmailText(emailInput),\n fromName: branding.fromName,\n siteName: site.name,\n org,\n merge: {\n ...parts,\n ...aiInsightDigestEmailHtml({\n insights: record.insights,\n tables: record.tables ?? [],\n colors: deps.colors(org),\n siteUrl: domain ? `https://${domain}` : null,\n sourceUrl: (table) => {\n const href = origin ? aiInsightSourceHref(table, { orgSlug, host: subdomain || null }) : null\n return href ? `${origin}${href}` : null\n },\n why: parts['digest.why'],\n settingsUrl: emailInput.settingsUrl,\n }),\n },\n })\n if (sent.rateLimited) {\n // Nothing is marked, so the next run delivers this site whole.\n result.deferred = true\n result.settled = false\n return result\n }\n }\n if (!notificationMuted(user?.get('notificationPrefs'), 'content.insightsDigest')) {\n await deps.notify(member.$id, {\n title: `Weekly insights · ${site.name}`,\n body: aiInsightDigestLine(record.insights[0]),\n link: `/${hostId}/analytics`,\n orgId,\n hostId,\n })\n }\n await markerRef.set({ sites: { [hostId]: { sent: { [member.$id]: true } } } }, { merge: true })\n }\n await settle('delivered')\n }\n return result\n}\n\n/**\n * One call of the sweep: delivery for this week and the last on the first\n * call, then — on a Monday — one chunk of workspaces' creation, resumed by\n * `cursor`. The response shape is the console crons' (`nextCursor`, `done`),\n * so the scheduler's loop carries a platform of any size across calls.\n */\nexport async function runAiInsightDigestSweep(\n deps: AiInsightDigestDeps,\n options: { cursor: string | null },\n): Promise<AiInsightDigestReport> {\n const { firestore, now } = deps\n const startedAtMs = Date.now()\n const budgetMs = deps.budgetMs ?? AI_INSIGHT_DIGEST_RUN_BUDGET_MS\n const overBudget = () => Date.now() - startedAtMs > budgetMs\n const week = aiInsightDigestWeek(now)\n const report: AiInsightDigestReport = {\n week,\n swept: 0,\n created: 0,\n delivered: 0,\n skipped: 0,\n deferred: false,\n nextCursor: null,\n done: true,\n }\n\n if (!options.cursor) {\n for (const owed of [previousWeek(now), week]) {\n const queueRef = firestore.collection(AI_INSIGHT_DIGEST_QUEUE).doc(owed)\n const pending = Object.entries(((await queueRef.get()).get('pending') ?? {}) as Record<string, unknown>)\n .filter(([, owed]) => owed === true)\n .map(([orgId]) => orgId)\n .sort()\n .slice(0, AI_INSIGHT_DIGEST_DELIVER_LIMIT)\n for (const orgId of pending) {\n if (overBudget()) {\n report.deferred = true\n return report\n }\n try {\n const delivered = await deliverOrgDigest(deps, orgId, owed, overBudget)\n report.delivered += delivered.delivered\n report.skipped += delivered.skipped\n if (delivered.settled) {\n await queueRef.set({ pending: { [orgId]: false } }, { merge: true })\n }\n if (delivered.deferred) {\n report.deferred = true\n return report\n }\n } catch (error) {\n console.error('ai insight digest delivery failed', { orgId, week: owed, error })\n }\n }\n }\n }\n\n // Monday is the week's first day by ISO 8601, and the day a digest is made.\n if (now.getUTCDay() !== 1) return report\n\n let query = firestore.collection('orgs').orderBy(FieldPath.documentId()).limit(AI_INSIGHT_DIGEST_ORG_CHUNK + 1)\n if (options.cursor) query = query.startAfter(firestore.collection('orgs').doc(options.cursor))\n const page = await query.get()\n const orgs = page.docs.slice(0, AI_INSIGHT_DIGEST_ORG_CHUNK)\n for (const [index, orgDoc] of orgs.entries()) {\n if (overBudget()) {\n // Out of time: the next call resumes after the last workspace read. A\n // call that read none has no cursor to hand on, and the next scheduled\n // run starts the week's workspaces again, which the markers make safe.\n report.nextCursor = index ? orgs[index - 1].id : (options.cursor ?? null)\n report.done = report.nextCursor === null\n return report\n }\n report.swept += 1\n try {\n report.created += await createOrgDigest(deps, orgDoc, week)\n } catch (error) {\n console.error('ai insight digest creation failed', { orgId: orgDoc.id, week, error })\n }\n }\n const more = page.docs.length > AI_INSIGHT_DIGEST_ORG_CHUNK\n report.nextCursor = more ? (orgs[orgs.length - 1]?.id ?? null) : null\n report.done = !more\n return report\n}\n"],"names":["FieldPath","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","notificationMuted","liveCustomDomain","TENANT_APEX","hostRoleFor","checkEntitlement","resolveBrandingProfile","resolveEffectivePlan","isReleaseFlagOnForOrg","parseOrgReleaseFlagOverrides","weeklySummaryFootnoteHtml","weeklySummaryPeriod","weeklySummaryPlainDates","weeklySummarySectionsHtml","weeklySummaryTilesHtml","weeklySummaryWeekday","normalizePluginFigureTable","pluginFigureCellText","pluginFigureReader","aiInsightDigestPeriod","aiInsightSourceHref","AI_INSIGHTS_COLLECTION","aiInsightIsoWeek","isAiOnForSite","cancelAiJob","createAiJob","getAiJob","AI_INSIGHTS_DIGEST_CRON_ID","AI_INSIGHTS_DIGEST_PATH","AI_INSIGHT_DIGEST_ORG_CHUNK","AI_INSIGHT_DIGEST_MAX_SITES","AI_INSIGHT_DIGEST_HOST_READ_LIMIT","AI_INSIGHT_DIGEST_DELIVER_LIMIT","AI_INSIGHT_DIGEST_DEADLINE_MS","AI_INSIGHT_DIGEST_RUN_BUDGET_MS","AI_INSIGHT_DIGEST_MARKERS","AI_INSIGHT_DIGEST_QUEUE","str","value","trim","aiInsightDigestWeek","now","previousWeek","Date","getTime","aiInsightDigestEmailText","input","workspace","workspaceName","credits","Math","max","round","Number","creditsSpent","drew","toLocaleString","forWhom","periodLabel","siteName","insights","map","insight","index","aiInsightDigestLine","analyticsUrl","productName","settingsUrl","join","text","headline","AI_INSIGHT_DIGEST_MAX_TILES","AI_INSIGHT_DIGEST_MAX_ROWS","FIGURE_KINDS","aiInsightDigestTiles","tables","flatMap","source","summary","reader","weeklySummary","table","stats","summarize","filter","stat","change","length","ref","order","sort","a","b","citedRows","rows","cites","cite","Set","row","isInteger","rowLabel","siteUrl","label","String","path","startsWith","url","aiInsightDigestFigures","cited","columns","find","column","kind","figures","includes","counted","key","cell","toLowerCase","figure","bars","display","marked","shown","slice","moved","aiInsightDigestSections","groups","Map","group","get","push","set","values","said","sourceUrl","title","link","points","aiInsightDigestEmailHtml","tiles","restated","every","fresh","part","colors","why","aiInsightDigestEmailParts","spent","Boolean","readUsers","firestore","uids","docs","getAll","uid","collection","doc","id","createOrgDigest","deps","orgDoc","week","orgId","org","data","flagOn","flagValue","paused","markerRef","exists","members","listMembers","member","orgSuspended","users","$id","subscribers","localeCompare","hosts","where","limit","yesterday","toISOString","candidates","host","day","creator","mayGenerate","hostId","name","views","chosen","sites","site","job","brief","inputs","surface","through","to","createdBy","jobId","state","marker","createdAtMs","pending","merge","deliverOrgDigest","overBudget","orgRef","markerSnapshot","result","delivered","skipped","settled","deferred","branding","Object","entries","record","settle","update","status","late","answer","reaching","orgSlug","subdomain","origin","consoleOrigin","user","sent","address","email","emailInput","parts","domain","send","subject","fromName","href","rateLimited","notify","body","runAiInsightDigestSweep","options","orgs","startedAtMs","budgetMs","report","swept","created","nextCursor","done","cursor","owed","queueRef","error","console","getUTCDay","query","orderBy","documentId","startAfter","page","more"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,2BAA0B;AACpD,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,iBAAiB,QAAQ,uCAAsC;AACxH,SAASC,gBAAgB,EAAEC,WAAW,QAAQ,qCAAoC;AAClF,SAASC,WAAW,QAAQ,uCAAsC;AAClE,SAASC,gBAAgB,EAAEC,sBAAsB,EAAEC,oBAAoB,QAAQ,2CAA0C;AACzH,SAASC,qBAAqB,EAAEC,4BAA4B,QAA+B,uCAAsC;AAEjI,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,uBAAuB,EACvBC,yBAAyB,EACzBC,sBAAsB,EACtBC,oBAAoB,QAKf,wCAAuC;AAC9C,SACEC,0BAA0B,EAC1BC,oBAAoB,EACpBC,kBAAkB,QAGb,6CAA4C;AACnD,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,sBAAsB,EACtBC,gBAAgB,QAIX,yBAAqB;AAC5B,SAASC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IACf,OAAOhB;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-insight-digest.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 { FieldPath } from 'firebase-admin/firestore'\nimport { INSIGHT_DIGESTS_FIELD, insightDigestSubscribed, notificationMuted } from '@aglyn/aglyn/app-utils/notifications'\nimport { liveCustomDomain, TENANT_APEX } from '@aglyn/aglyn/app-utils/host-naming'\nimport { hostRoleFor } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement, resolveBrandingProfile, resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { isReleaseFlagOnForOrg, parseOrgReleaseFlagOverrides, type ReleaseFlagValue } from '@aglyn/aglyn/app-utils/release-flags'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n weeklySummaryFootnoteHtml,\n weeklySummaryPeriod,\n weeklySummaryPlainDates,\n weeklySummarySectionsHtml,\n weeklySummaryTilesHtml,\n weeklySummaryRowLink,\n weeklySummaryWeekday,\n type WeeklySummaryColors,\n type WeeklySummarySection,\n type WeeklySummarySectionBar,\n type WeeklySummarySectionRow,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\nimport {\n normalizePluginFigureTable,\n pluginFigureCellText,\n pluginFigureReader,\n type PluginFigureColumn,\n type PluginFigureSummaryStat,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n aiInsightDigestPeriod,\n aiInsightSourceHref,\n AI_INSIGHTS_COLLECTION,\n aiInsightIsoWeek,\n type AiInsight,\n type AiInsightRecord,\n type AiInsightTable,\n} from '../model/ai-insight'\nimport { isAiOnForSite } from '../model/ai-site-switch'\nimport { cancelAiJob, createAiJob, getAiJob } from '../jobs/ai-jobs'\n\n/**\n * THE WEEKLY INSIGHTS (AGL-2915): `POST /api/admin/ai-insights-digest`, twice\n * a day on the console's scheduler.\n *\n * ## Who asked for it\n *\n * A person turns weekly insights on for a workspace beside the answers\n * themselves (`users/{uid}.insightDigests.{orgId}`), and off there or in\n * Notifications. It is opt-in, because each digest is a generation the\n * workspace pays for. At the sweep, every rung is asked again rather than\n * trusted from the switch: the workspace's plan includes `aiGenerative`,\n * `release_ai_generative` is on for it, its AI is not paused, the site has AI\n * on, and the person still holds `ai.generate` on the site.\n *\n * ## Monday: one job per site\n *\n * On a Monday run, for each workspace with someone who asked, the sites those\n * people reach — the busiest `AI_INSIGHT_DIGEST_MAX_SITES` by yesterday's page\n * views — each get one `insight` job with the `digest` surface, created by the\n * first of them who may generate there. The job runs on the AI jobs beat like\n * any other: it reserves, meters and records its credits, and a workspace at\n * its band — a Free one that has used its credits — has its job parked by the\n * reservation like any other. `orgs/{orgId}/aiInsightDigests/{week}` records\n * the jobs; `aiInsightDigestQueue/{week}` lists the workspaces still owed a\n * delivery, so a run that delivers reads one document rather than every\n * workspace.\n *\n * ## Every run: deliver what is written\n *\n * A digest whose job is done and kept at least one insight is delivered once:\n * a `content.insightsDigest` notification (unless the person muted the\n * category) and an email through the platform's own sending path, to each\n * person who asked for the workspace's insights and reaches the site. A job\n * that failed, kept nothing, or parked for credits is SKIPPED SILENTLY: a\n * parked job is canceled rather than left to spend later, and nobody is told,\n * because nobody asked about that week in particular. A job still running\n * past `AI_INSIGHT_DIGEST_DEADLINE_MS` is canceled and skipped the same way.\n *\n * The email says only what the answer says, drawn to be run down rather than\n * read: the week's headline figures as tiles, then one section a topic, however\n * many insights cite it, each with its headline, the figures those insights\n * cite and a link to where they live. Every reader draws the same way, from its\n * table's own columns. It is sent by the platform to a person who asked for it,\n * never to a contact.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport const AI_INSIGHTS_DIGEST_CRON_ID = 'ai-insights-digest'\nexport const AI_INSIGHTS_DIGEST_PATH = 'admin/ai-insights-digest'\n\n/** Orgs one call reads; a chunk that times out never advances the cursor, so the safe size is one that finishes. */\nexport const AI_INSIGHT_DIGEST_ORG_CHUNK = 25\n\n/** Sites one workspace's digest covers a week. */\nexport const AI_INSIGHT_DIGEST_MAX_SITES = 5\n\n/** Sites a workspace's sweep reads before it ranks them. */\nexport const AI_INSIGHT_DIGEST_HOST_READ_LIMIT = 50\n\n/** Workspaces one run delivers to, per week. */\nexport const AI_INSIGHT_DIGEST_DELIVER_LIMIT = 100\n\n/** How long a digest's job may take before its week is given up. */\nexport const AI_INSIGHT_DIGEST_DEADLINE_MS = 48 * 60 * 60_000\n\n/**\n * The time one call works before it stops and leaves the rest to the next:\n * inside the plugin dispatcher's 60 s function ceiling, with room for the\n * reads before the first check and the reply after the last. A call killed\n * mid-send could send one person a site's digest twice, because a send is\n * stamped after it goes.\n */\nexport const AI_INSIGHT_DIGEST_RUN_BUDGET_MS = 45_000\n\nexport const AI_INSIGHT_DIGEST_MARKERS = 'aiInsightDigests'\nexport const AI_INSIGHT_DIGEST_QUEUE = 'aiInsightDigestQueue'\n\nexport type AiInsightDigestSiteState = 'pending' | 'delivered' | 'skipped'\n\nexport interface AiInsightDigestSite {\n jobId: string\n name: string\n state: AiInsightDigestSiteState\n /**\n * The people already sent this site's digest, so a run the send rate\n * stopped never sends one twice. Dropped when the site settles, so a\n * settled marker names no person.\n */\n sent?: Record<string, boolean>\n}\n\nexport interface AiInsightDigestMarker {\n week: string\n createdAtMs: number\n sites: Record<string, AiInsightDigestSite>\n}\n\n/** What a send answered: whether it went, and whether the platform's send rate refused it for now. */\nexport interface AiInsightDigestSendResult {\n sent: boolean\n rateLimited: boolean\n}\n\n/** Everything the sweep reaches beyond Firestore, so a spec can hold each one. */\nexport interface AiInsightDigestDeps {\n firestore: Firestore\n now: Date\n flagValue: ReleaseFlagValue\n listMembers: (orgId: string) => Promise<AglynOrgMember[]>\n mayGenerate: (orgId: string, hostId: string, member: AglynOrgMember) => Promise<boolean>\n paused: (orgId: string) => Promise<boolean>\n notify: (uid: string, payload: { title: string; body: string; link: string; orgId: string; hostId: string }) => Promise<void>\n send: (email: {\n to: string\n subject: string\n text: string\n fromName: string\n /** The site the digest is about, and the org whose brand it wears (AGL-3367). */\n siteName: string\n org: Record<string, unknown>\n /** The designed email's merge values, from {@link aiInsightDigestEmailParts}. */\n merge?: Record<string, string>\n }) => Promise<AiInsightDigestSendResult>\n /** The console's absolute origin for an email link, or `''` when none is configured. */\n consoleOrigin: string\n /** The org's email theme, as the digest's drawing needs it. */\n colors: (org: Record<string, unknown>) => WeeklySummaryColors\n /** The call's working time; `AI_INSIGHT_DIGEST_RUN_BUDGET_MS` unless a spec holds it. */\n budgetMs?: number\n}\n\nexport interface AiInsightDigestReport {\n week: string\n swept: number\n created: number\n delivered: number\n skipped: number\n /** The send rate refused or the call's time ran out; the run stops, and the next one delivers the rest. */\n deferred: boolean\n nextCursor: string | null\n done: boolean\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The week a Monday digest covers: the week the run falls in. */\nexport function aiInsightDigestWeek(now: Date): string {\n return aiInsightIsoWeek(now)\n}\n\n/** The week before, whose late digests a run still delivers. */\nfunction previousWeek(now: Date): string {\n return aiInsightIsoWeek(new Date(now.getTime() - 7 * 86_400_000))\n}\n\n/**\n * A digest email's words: the insights, the site's Analytics page, and where\n * to turn it off. The digest is an AI job metered against the workspace, so\n * it says what it drew, and it names the workspace a member of several asked\n * for it in.\n */\nexport function aiInsightDigestEmailText(input: {\n siteName: string\n productName: string\n insights: ReadonlyArray<{ text: string }>\n /** Absolute links, or `null` where no console origin is configured to build one from. */\n analyticsUrl: string | null\n settingsUrl: string | null\n /** The workspace the digest was asked for in; `''` falls back to \"this workspace\". */\n workspaceName?: string\n /** The AI credits the digest's job drew; 0 or absent says nothing. */\n creditsSpent?: number\n /** The week the figures cover, \"Oct 5 – Oct 11\"; absent says \"this week\". */\n periodLabel?: string\n}): string {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const drew = credits\n ? ` Writing it used ${credits.toLocaleString('en-US')} of ` +\n `${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n const forWhom = workspace || 'this workspace'\n return [\n input.periodLabel\n ? `Here is what ${input.siteName}'s figures showed last week, ${input.periodLabel}.${drew}`\n : `Here is what ${input.siteName}'s figures showed this week.${drew}`,\n '',\n ...input.insights.map((insight, index) => `${index + 1}. ${aiInsightDigestLine(insight)}`),\n '',\n input.analyticsUrl\n ? `Each of these is traced to the figures it cites. See them in ${input.productName}: ${input.analyticsUrl}`\n : `Each of these is traced to the figures it cites. See them on the site's Analytics page in ${input.productName}.`,\n '',\n input.settingsUrl\n ? `You asked for weekly insights for ${forWhom}. Turn them off in Notifications: ${input.settingsUrl}`\n : `You asked for weekly insights for ${forWhom}. Turn them off in your Notifications settings.`,\n ].join('\\n')\n}\n\n/** An insight in one line of plain text, its dates as a person says them. */\nfunction aiInsightDigestLine(insight: { text: string; headline?: string | null }): string {\n const text = weeklySummaryPlainDates(insight.text)\n return insight.headline ? `${insight.headline}: ${text}` : text\n}\n\n/** The most tiles the digest leads with: one row. */\nexport const AI_INSIGHT_DIGEST_MAX_TILES = 3\n\n/** The most rows a section lists. */\nexport const AI_INSIGHT_DIGEST_MAX_ROWS = 5\n\n/** The columns that hold a figure a row can show, as against a label or a change. */\nconst FIGURE_KINDS: ReadonlyArray<PluginFigureColumn['kind']> = ['count', 'money', 'percent', 'duration']\n\n/**\n * Each table the job read, as its reader's owner would headline it in the\n * weekly summary. Only a figure compared with the week before earns a tile: a\n * month's running count beside two weeks' does not read as the same kind of\n * thing.\n */\nfunction aiInsightDigestTiles(tables: readonly AiInsightTable[]): Array<{ ref: string; stats: readonly PluginFigureSummaryStat[] }> {\n return tables\n .flatMap((source) => {\n const summary = pluginFigureReader(source.reader)?.reader.weeklySummary\n const table = summary ? normalizePluginFigureTable(source) : null\n const stats = (table ? (summary?.summarize(table)?.stats ?? []) : []).filter((stat) => typeof stat.change === 'number')\n return stats.length ? [{ ref: source.ref, stats, order: summary?.order ?? 0 }] : []\n })\n .sort((a, b) => a.order - b.order)\n}\n\n/** The row numbers a set of insights cite in a table, each once, in the order they cite them. */\nfunction citedRows(insights: readonly AiInsight[], table: AiInsightTable): number[] {\n const rows = insights.flatMap((insight) =>\n insight.cites.filter((cite) => cite.table === table.ref).flatMap((cite) => cite.rows),\n )\n return [...new Set(rows)].filter((row) => Number.isInteger(row) && table.rows[row])\n}\n\n/**\n * A section's figures, from the table's own columns, so a reader added\n * tomorrow draws without a line here: a table of days is a chart of the week\n * with the cited days marked, and any other is its cited rows, each with its\n * change where the table has one, else with its second figure.\n */\nfunction aiInsightDigestFigures(\n table: AiInsightTable,\n cited: readonly number[],\n siteUrl: string | null,\n): Pick<WeeklySummarySection, 'rows' | 'bars'> {\n const label = table.columns.find((column) => column.kind === 'text' || column.kind === 'date')\n const figures = table.columns.filter((column) => FIGURE_KINDS.includes(column.kind))\n const change = table.columns.find((column) => column.kind === 'change')\n if (!label || !figures.length || !cited.length) return {}\n // A `figure` row names what it counts. Any other row's count takes its column's word.\n const counted = label.key !== 'figure'\n const text = (column: PluginFigureColumn, row: AiInsightTable['rows'][number]) => {\n const cell = pluginFigureCellText(table, column.key, row[column.key])\n return counted && column.kind === 'count' ? `${cell} ${column.label.toLowerCase()}` : cell\n }\n if (label.kind === 'date') {\n const [figure] = figures\n const bars: WeeklySummarySectionBar[] = table.rows.map((row, index) => ({\n label: weeklySummaryWeekday(String(row[label.key])),\n value: Number(row[figure.key]) || 0,\n display: pluginFigureCellText(table, figure.key, row[figure.key]),\n marked: cited.includes(index),\n }))\n return { bars }\n }\n const shown = figures.slice(0, change ? 1 : 2)\n return {\n rows: cited.slice(0, AI_INSIGHT_DIGEST_MAX_ROWS).map((index) => {\n const row = table.rows[index]\n const moved = change ? row[change.key] : null\n return {\n ...weeklySummaryRowLink(String(row[label.key] ?? ''), siteUrl),\n value: shown.map((column) => text(column, row)).join(' · '),\n change: typeof moved === 'number' ? moved : null,\n }\n }),\n }\n}\n\n/** The digest's topics: one a table, however many insights cite it, in the order they first come up. */\nfunction aiInsightDigestSections(\n insights: readonly AiInsight[],\n input: { tables: readonly AiInsightTable[]; siteUrl: string | null; sourceUrl: (table: AiInsightTable) => string | null },\n): WeeklySummarySection[] {\n const groups = new Map<string, { table: AiInsightTable | null; insights: AiInsight[] }>()\n for (const insight of insights) {\n const ref = insight.cites[0]?.table ?? ''\n const group = groups.get(ref) ?? { table: input.tables.find((table) => table.ref === ref) ?? null, insights: [] }\n group.insights.push(insight)\n groups.set(ref, group)\n }\n return [...groups.values()].map(({ table, insights: said }) => {\n const url = table ? input.sourceUrl(table) : null\n return {\n title: table?.title ?? 'What changed',\n link: table && url ? { label: table.source.label, url } : null,\n points: said.map((insight) => ({\n headline: insight.headline?.trim() || null,\n text: weeklySummaryPlainDates(insight.text),\n })),\n ...(table ? aiInsightDigestFigures(table, citedRows(said, table), input.siteUrl) : {}),\n }\n })\n}\n\n/**\n * The digest's drawn parts: the week's figures as tiles, one section a topic,\n * and the small print. An insight that only says what the first tiles already\n * show is left out, so the email never makes a person read the same figures\n * twice.\n */\nexport function aiInsightDigestEmailHtml(input: {\n insights: readonly AiInsight[]\n tables: readonly AiInsightTable[]\n colors: WeeklySummaryColors\n /** The site's own address, which a row naming a page links to. */\n siteUrl: string | null\n /** Where a table's figures live in the console, absolute. */\n sourceUrl: (table: AiInsightTable) => string | null\n /** The sentence that says what the digest cost. */\n why: string\n settingsUrl: string | null\n}): Record<'digest.html' | 'digest.footnote', string> {\n const tiles = aiInsightDigestTiles(input.tables)\n const restated = (insight: AiInsight) =>\n insight.cites.length > 0 && insight.cites.every((cite) => cite.table === tiles[0]?.ref)\n const fresh = input.insights.filter((insight) => !restated(insight))\n return {\n 'digest.html':\n weeklySummaryTilesHtml(tiles.flatMap((part) => part.stats).slice(0, AI_INSIGHT_DIGEST_MAX_TILES), input.colors) +\n weeklySummarySectionsHtml(aiInsightDigestSections(fresh.length ? fresh : input.insights, input), input.colors),\n 'digest.footnote': weeklySummaryFootnoteHtml(\n input.why,\n input.settingsUrl ? { label: 'Turn off weekly insights', url: input.settingsUrl } : null,\n input.colors,\n ),\n }\n}\n\n/**\n * The same digest as {@link aiInsightDigestEmailText}, cut into the parts the\n * `ai-insights-digest` system email draws: the workspace and week above the\n * heading, the figures and insights, a button to the site's Analytics page,\n * what it cost, and where to turn it off.\n */\nexport function aiInsightDigestEmailParts(\n input: Parameters<typeof aiInsightDigestEmailText>[0],\n): Record<\n 'digest.eyebrow' | 'digest.intro' | 'digest.insights' | 'digest.analyticsUrl' | 'digest.why',\n string\n> {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const spent = credits\n ? ` Writing these used ${credits.toLocaleString('en-US')} of ${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n return {\n 'digest.eyebrow': [workspace, input.periodLabel?.trim()].filter(Boolean).join(' · '),\n 'digest.intro':\n `What ${input.siteName}'s figures showed ${input.periodLabel ? 'last week' : 'this week'}. ` +\n 'Each one is traced to the figures it cites, so you can check it on the Analytics page.',\n 'digest.insights': input.insights\n .map((insight, index) => `${index + 1}. ${aiInsightDigestLine(insight)}`)\n .join('\\n\\n'),\n 'digest.analyticsUrl': input.analyticsUrl ?? '',\n 'digest.why': `Every number here is checked against ${input.siteName}'s own figures.${spent}`,\n }\n}\n\nasync function readUsers(firestore: Firestore, uids: readonly string[]) {\n if (!uids.length) return new Map<string, FirebaseFirestore.DocumentSnapshot>()\n const docs = await firestore.getAll(...uids.map((uid) => firestore.collection('users').doc(uid)))\n return new Map(docs.map((doc) => [doc.id, doc]))\n}\n\n/** Creates one workspace's digests for the week; answers how many jobs it created. */\nasync function createOrgDigest(\n deps: AiInsightDigestDeps,\n orgDoc: FirebaseFirestore.QueryDocumentSnapshot,\n week: string,\n): Promise<number> {\n const { firestore, now } = deps\n const orgId = orgDoc.id\n const org = (orgDoc.data() ?? {}) as Record<string, unknown>\n if (!checkEntitlement(org as never, 'aiGenerative')) return 0\n const flagOn = isReleaseFlagOnForOrg(\n 'release_ai_generative',\n deps.flagValue,\n orgId,\n parseOrgReleaseFlagOverrides(org['releaseFlags']),\n resolveEffectivePlan(org as never),\n )\n if (!flagOn || (await deps.paused(orgId))) return 0\n const markerRef = orgDoc.ref.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n if ((await markerRef.get()).exists) return 0\n\n const members = (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const users = await readUsers(firestore, members.map((member) => member.$id).sort())\n const subscribers = members\n .filter((member) => insightDigestSubscribed(users.get(member.$id)?.get(INSIGHT_DIGESTS_FIELD), orgId))\n .sort((a, b) => a.$id.localeCompare(b.$id))\n if (!subscribers.length) return 0\n\n const hosts = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .limit(AI_INSIGHT_DIGEST_HOST_READ_LIMIT)\n .get()\n const yesterday = new Date(now.getTime() - 86_400_000).toISOString().slice(0, 10)\n const candidates: Array<{ hostId: string; name: string; creator: string; views: number }> = []\n for (const host of hosts.docs) {\n const data = host.data() ?? {}\n if (!isAiOnForSite(org, data)) continue\n let creator: string | null = null\n for (const member of subscribers) {\n if (hostRoleFor(member, host.id) !== null && (await deps.mayGenerate(orgId, host.id, member))) {\n creator = member.$id\n break\n }\n }\n if (!creator) continue\n const day = await host.ref.collection('analytics').doc(yesterday).get()\n candidates.push({\n hostId: host.id,\n name: str(data['displayName']) || str(data['name']) || str(data['subdomain']) || host.id,\n creator,\n views: Number(day.get('total') ?? 0) || 0,\n })\n }\n const chosen = candidates\n .sort((a, b) => b.views - a.views || a.hostId.localeCompare(b.hostId))\n .slice(0, AI_INSIGHT_DIGEST_MAX_SITES)\n if (!chosen.length) return 0\n\n const sites: Record<string, AiInsightDigestSite> = {}\n for (const site of chosen) {\n const job = await createAiJob(\n firestore,\n {\n orgId,\n hostId: site.hostId,\n kind: 'insight',\n brief: `Weekly insights for ${site.name}`,\n inputs: { surface: 'digest', week, through: weeklySummaryPeriod(now).to },\n createdBy: site.creator,\n },\n now,\n )\n sites[site.hostId] = { jobId: job.$id, name: site.name, state: 'pending' }\n }\n const marker: AiInsightDigestMarker = { week, createdAtMs: now.getTime(), sites }\n await markerRef.set(marker)\n await firestore\n .collection(AI_INSIGHT_DIGEST_QUEUE)\n .doc(week)\n .set({ week, pending: { [orgId]: true } }, { merge: true })\n return chosen.length\n}\n\n/** Delivers or settles one workspace's digests for a week; `deferred` when the send rate refused. */\nasync function deliverOrgDigest(\n deps: AiInsightDigestDeps,\n orgId: string,\n week: string,\n overBudget: () => boolean,\n): Promise<{ delivered: number; skipped: number; settled: boolean; deferred: boolean }> {\n const { firestore, now } = deps\n const orgRef = firestore.collection('orgs').doc(orgId)\n const markerRef = orgRef.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n const markerSnapshot = await markerRef.get()\n const result = { delivered: 0, skipped: 0, settled: true, deferred: false }\n if (!markerSnapshot.exists) return result\n const marker = markerSnapshot.data() as AiInsightDigestMarker\n const org = ((await orgRef.get()).data() ?? {}) as Record<string, unknown>\n let members: AglynOrgMember[] | null = null\n const branding = resolveBrandingProfile(org as never)\n\n for (const [hostId, site] of Object.entries(marker.sites ?? {})) {\n if (site.state !== 'pending') continue\n const settle = async (state: AiInsightDigestSiteState) => {\n // Replaced whole rather than merged, which drops `sent`.\n const settled: AiInsightDigestSite = { jobId: site.jobId, name: site.name, state }\n await markerRef.update({ [`sites.${hostId}`]: settled })\n if (state === 'delivered') result.delivered += 1\n else result.skipped += 1\n }\n const job = await getAiJob(firestore, orgId, site.jobId)\n if (!job || job.status === 'failed' || job.status === 'canceled') {\n await settle('skipped')\n continue\n }\n if (job.status !== 'done') {\n const late = now.getTime() - Number(marker.createdAtMs ?? 0) > AI_INSIGHT_DIGEST_DEADLINE_MS\n // A job parked for credits — a Free workspace at its band — is given up\n // rather than left to spend on a week that is already over.\n if (job.status === 'needs_input' || late) {\n await cancelAiJob(firestore, orgId, site.jobId, now)\n await settle('skipped')\n } else {\n result.settled = false\n }\n continue\n }\n const answer = await orgRef.collection(AI_INSIGHTS_COLLECTION).doc(site.jobId).get()\n const record = answer.exists ? (answer.data() as AiInsightRecord) : null\n if (!record?.insights?.length) {\n await settle('skipped')\n continue\n }\n\n members ??= (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const reaching = members.filter((member) => hostRoleFor(member, hostId) !== null)\n const users = await readUsers(firestore, reaching.map((member) => member.$id).sort())\n const host = (await firestore.collection('hosts').doc(hostId).get()).data() ?? {}\n const orgSlug = str(org['slug'])\n const subdomain = str(host['subdomain'])\n const origin = deps.consoleOrigin\n const analyticsUrl = origin && orgSlug && subdomain ? `${origin}/${orgSlug}/hosts/${subdomain}/analytics` : null\n for (const member of reaching.sort((a, b) => a.$id.localeCompare(b.$id))) {\n const user = users.get(member.$id)\n if (!insightDigestSubscribed(user?.get(INSIGHT_DIGESTS_FIELD), orgId)) continue\n if (site.sent?.[member.$id]) continue\n if (overBudget()) {\n // Out of time: what was sent is stamped, and the next run sends the rest.\n result.deferred = true\n result.settled = false\n return result\n }\n const address = str(member.email ?? user?.get('email')).toLowerCase()\n if (address.includes('@')) {\n const emailInput = {\n siteName: site.name,\n productName: branding.productName,\n insights: record.insights,\n analyticsUrl,\n settingsUrl: origin ? `${origin}/manage/notifications` : null,\n workspaceName: str(org['name']),\n creditsSpent: job.creditsSpent,\n periodLabel: aiInsightDigestPeriod(job.inputs, new Date(Number(marker.createdAtMs) || now.getTime())).label,\n }\n const parts = aiInsightDigestEmailParts(emailInput)\n const domain = liveCustomDomain(host as never) ?? (subdomain ? `${subdomain}.${TENANT_APEX}` : '')\n const sent = await deps.send({\n to: address,\n subject: `Your weekly insights for ${site.name}`,\n text: aiInsightDigestEmailText(emailInput),\n fromName: branding.fromName,\n siteName: site.name,\n org,\n merge: {\n ...parts,\n ...aiInsightDigestEmailHtml({\n insights: record.insights,\n tables: record.tables ?? [],\n colors: deps.colors(org),\n siteUrl: domain ? `https://${domain}` : null,\n sourceUrl: (table) => {\n const href = origin ? aiInsightSourceHref(table, { orgSlug, host: subdomain || null }) : null\n return href ? `${origin}${href}` : null\n },\n why: parts['digest.why'],\n settingsUrl: emailInput.settingsUrl,\n }),\n },\n })\n if (sent.rateLimited) {\n // Nothing is marked, so the next run delivers this site whole.\n result.deferred = true\n result.settled = false\n return result\n }\n }\n if (!notificationMuted(user?.get('notificationPrefs'), 'content.insightsDigest')) {\n await deps.notify(member.$id, {\n title: `Weekly insights · ${site.name}`,\n body: aiInsightDigestLine(record.insights[0]),\n link: `/${hostId}/analytics`,\n orgId,\n hostId,\n })\n }\n await markerRef.set({ sites: { [hostId]: { sent: { [member.$id]: true } } } }, { merge: true })\n }\n await settle('delivered')\n }\n return result\n}\n\n/**\n * One call of the sweep: delivery for this week and the last on the first\n * call, then — on a Monday — one chunk of workspaces' creation, resumed by\n * `cursor`. The response shape is the console crons' (`nextCursor`, `done`),\n * so the scheduler's loop carries a platform of any size across calls.\n */\nexport async function runAiInsightDigestSweep(\n deps: AiInsightDigestDeps,\n options: { cursor: string | null },\n): Promise<AiInsightDigestReport> {\n const { firestore, now } = deps\n const startedAtMs = Date.now()\n const budgetMs = deps.budgetMs ?? AI_INSIGHT_DIGEST_RUN_BUDGET_MS\n const overBudget = () => Date.now() - startedAtMs > budgetMs\n const week = aiInsightDigestWeek(now)\n const report: AiInsightDigestReport = {\n week,\n swept: 0,\n created: 0,\n delivered: 0,\n skipped: 0,\n deferred: false,\n nextCursor: null,\n done: true,\n }\n\n if (!options.cursor) {\n for (const owed of [previousWeek(now), week]) {\n const queueRef = firestore.collection(AI_INSIGHT_DIGEST_QUEUE).doc(owed)\n const pending = Object.entries(((await queueRef.get()).get('pending') ?? {}) as Record<string, unknown>)\n .filter(([, owed]) => owed === true)\n .map(([orgId]) => orgId)\n .sort()\n .slice(0, AI_INSIGHT_DIGEST_DELIVER_LIMIT)\n for (const orgId of pending) {\n if (overBudget()) {\n report.deferred = true\n return report\n }\n try {\n const delivered = await deliverOrgDigest(deps, orgId, owed, overBudget)\n report.delivered += delivered.delivered\n report.skipped += delivered.skipped\n if (delivered.settled) {\n await queueRef.set({ pending: { [orgId]: false } }, { merge: true })\n }\n if (delivered.deferred) {\n report.deferred = true\n return report\n }\n } catch (error) {\n console.error('ai insight digest delivery failed', { orgId, week: owed, error })\n }\n }\n }\n }\n\n // Monday is the week's first day by ISO 8601, and the day a digest is made.\n if (now.getUTCDay() !== 1) return report\n\n let query = firestore.collection('orgs').orderBy(FieldPath.documentId()).limit(AI_INSIGHT_DIGEST_ORG_CHUNK + 1)\n if (options.cursor) query = query.startAfter(firestore.collection('orgs').doc(options.cursor))\n const page = await query.get()\n const orgs = page.docs.slice(0, AI_INSIGHT_DIGEST_ORG_CHUNK)\n for (const [index, orgDoc] of orgs.entries()) {\n if (overBudget()) {\n // Out of time: the next call resumes after the last workspace read. A\n // call that read none has no cursor to hand on, and the next scheduled\n // run starts the week's workspaces again, which the markers make safe.\n report.nextCursor = index ? orgs[index - 1].id : (options.cursor ?? null)\n report.done = report.nextCursor === null\n return report\n }\n report.swept += 1\n try {\n report.created += await createOrgDigest(deps, orgDoc, week)\n } catch (error) {\n console.error('ai insight digest creation failed', { orgId: orgDoc.id, week, error })\n }\n }\n const more = page.docs.length > AI_INSIGHT_DIGEST_ORG_CHUNK\n report.nextCursor = more ? (orgs[orgs.length - 1]?.id ?? null) : null\n report.done = !more\n return report\n}\n"],"names":["FieldPath","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","notificationMuted","liveCustomDomain","TENANT_APEX","hostRoleFor","checkEntitlement","resolveBrandingProfile","resolveEffectivePlan","isReleaseFlagOnForOrg","parseOrgReleaseFlagOverrides","weeklySummaryFootnoteHtml","weeklySummaryPeriod","weeklySummaryPlainDates","weeklySummarySectionsHtml","weeklySummaryTilesHtml","weeklySummaryRowLink","weeklySummaryWeekday","normalizePluginFigureTable","pluginFigureCellText","pluginFigureReader","aiInsightDigestPeriod","aiInsightSourceHref","AI_INSIGHTS_COLLECTION","aiInsightIsoWeek","isAiOnForSite","cancelAiJob","createAiJob","getAiJob","AI_INSIGHTS_DIGEST_CRON_ID","AI_INSIGHTS_DIGEST_PATH","AI_INSIGHT_DIGEST_ORG_CHUNK","AI_INSIGHT_DIGEST_MAX_SITES","AI_INSIGHT_DIGEST_HOST_READ_LIMIT","AI_INSIGHT_DIGEST_DELIVER_LIMIT","AI_INSIGHT_DIGEST_DEADLINE_MS","AI_INSIGHT_DIGEST_RUN_BUDGET_MS","AI_INSIGHT_DIGEST_MARKERS","AI_INSIGHT_DIGEST_QUEUE","str","value","trim","aiInsightDigestWeek","now","previousWeek","Date","getTime","aiInsightDigestEmailText","input","workspace","workspaceName","credits","Math","max","round","Number","creditsSpent","drew","toLocaleString","forWhom","periodLabel","siteName","insights","map","insight","index","aiInsightDigestLine","analyticsUrl","productName","settingsUrl","join","text","headline","AI_INSIGHT_DIGEST_MAX_TILES","AI_INSIGHT_DIGEST_MAX_ROWS","FIGURE_KINDS","aiInsightDigestTiles","tables","flatMap","source","summary","reader","weeklySummary","table","stats","summarize","filter","stat","change","length","ref","order","sort","a","b","citedRows","rows","cites","cite","Set","row","isInteger","aiInsightDigestFigures","cited","siteUrl","label","columns","find","column","kind","figures","includes","counted","key","cell","toLowerCase","figure","bars","String","display","marked","shown","slice","moved","aiInsightDigestSections","groups","Map","group","get","push","set","values","said","url","sourceUrl","title","link","points","aiInsightDigestEmailHtml","tiles","restated","every","fresh","part","colors","why","aiInsightDigestEmailParts","spent","Boolean","readUsers","firestore","uids","docs","getAll","uid","collection","doc","id","createOrgDigest","deps","orgDoc","week","orgId","org","data","flagOn","flagValue","paused","markerRef","exists","members","listMembers","member","orgSuspended","users","$id","subscribers","localeCompare","hosts","where","limit","yesterday","toISOString","candidates","host","day","creator","mayGenerate","hostId","name","views","chosen","sites","site","job","brief","inputs","surface","through","to","createdBy","jobId","state","marker","createdAtMs","pending","merge","deliverOrgDigest","overBudget","orgRef","markerSnapshot","result","delivered","skipped","settled","deferred","branding","Object","entries","record","settle","update","status","late","answer","reaching","orgSlug","subdomain","origin","consoleOrigin","user","sent","address","email","emailInput","parts","domain","send","subject","fromName","href","rateLimited","notify","body","runAiInsightDigestSweep","options","orgs","startedAtMs","budgetMs","report","swept","created","nextCursor","done","cursor","owed","queueRef","error","console","getUTCDay","query","orderBy","documentId","startAfter","page","more"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,2BAA0B;AACpD,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,iBAAiB,QAAQ,uCAAsC;AACxH,SAASC,gBAAgB,EAAEC,WAAW,QAAQ,qCAAoC;AAClF,SAASC,WAAW,QAAQ,uCAAsC;AAClE,SAASC,gBAAgB,EAAEC,sBAAsB,EAAEC,oBAAoB,QAAQ,2CAA0C;AACzH,SAASC,qBAAqB,EAAEC,4BAA4B,QAA+B,uCAAsC;AAEjI,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,uBAAuB,EACvBC,yBAAyB,EACzBC,sBAAsB,EACtBC,oBAAoB,EACpBC,oBAAoB,QAKf,wCAAuC;AAC9C,SACEC,0BAA0B,EAC1BC,oBAAoB,EACpBC,kBAAkB,QAGb,6CAA4C;AACnD,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,sBAAsB,EACtBC,gBAAgB,QAIX,yBAAqB;AAC5B,SAASC,aAAa,QAAQ,6BAAyB;AACvD,SAASC,WAAW,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,qBAAiB;AAkDpE,OAAO,MAAMC,6BAA6B,qBAAoB;AAC9D,OA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AM;IAC5F,MAAMU,OAAO,MAAMJ,MAAMpI,GAAG;IAC5B,MAAMsH,OAAOkB,KAAKhH,IAAI,CAAC9B,KAAK,CAAC,GAAG3F;IAChC,KAAK,MAAM,CAACkC,OAAO+F,OAAO,IAAIsF,KAAK5B,OAAO,GAAI;QAC5C,IAAIV,cAAc;gBAIkCqC;YAHlD,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvEI,OAAOG,UAAU,GAAG3L,QAAQqL,IAAI,CAACrL,QAAQ,EAAE,CAAC4F,EAAE,IAAIwF,kBAAAA,QAAQS,MAAM,YAAdT,kBAAkB;YACpEI,OAAOI,IAAI,GAAGJ,OAAOG,UAAU,KAAK;YACpC,OAAOH;QACT;QACAA,OAAOC,KAAK,IAAI;QAChB,IAAI;YACFD,OAAOE,OAAO,IAAI,MAAM7F,gBAAgBC,MAAMC,QAAQC;QACxD,EAAE,OAAOgG,OAAO;YACdC,QAAQD,KAAK,CAAC,qCAAqC;gBAAE/F,OAAOF,OAAOH,EAAE;gBAAEI;gBAAMgG;YAAM;QACrF;IACF;IACA,MAAMQ,OAAOD,KAAKhH,IAAI,CAAC/D,MAAM,GAAG1D;IAChC0N,OAAOG,UAAU,GAAGa,gBAAQnB,SAAAA,IAAI,CAACA,KAAK7J,MAAM,GAAG,EAAE,qBAArB6J,OAAuBzF,EAAE,mBAAI,OAAQ;IACjE4F,OAAOI,IAAI,GAAG,CAACY;IACf,OAAOhB;AACT"}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/ import { pluginFigureCellText, pluginFigureIsoWeek } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
16
|
+
*/ import { pluginFigureCellText, pluginFigureIsoWeek, pluginFigureSourceHref } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
17
17
|
import { weeklySummaryPeriod } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
18
18
|
import { AI_INSIGHT_DEFAULT_DAYS, AI_INSIGHT_WINDOWS } from "./ai-insight-ask.js";
|
|
19
19
|
export { AI_INSIGHT_DEFAULT_DAYS, AI_INSIGHT_QUESTION_MAX_CHARS, AI_INSIGHT_WINDOWS } from "./ai-insight-ask.js";
|
|
@@ -216,10 +216,7 @@ export const AI_INSIGHT_SURFACES = [
|
|
|
216
216
|
return null;
|
|
217
217
|
}
|
|
218
218
|
/** The console page a table's figures come from, or `null` when the table names none. */ export function aiInsightSourceHref(table, where) {
|
|
219
|
-
|
|
220
|
-
if (!path || !where.orgSlug) return null;
|
|
221
|
-
if (table.scope === 'org') return `/${where.orgSlug}/${path}`;
|
|
222
|
-
return where.host ? `/${where.orgSlug}/hosts/${where.host}/${path}` : null;
|
|
219
|
+
return pluginFigureSourceHref(table.source, table.scope === 'org' ? 'org' : 'site', where);
|
|
223
220
|
}
|
|
224
221
|
/** How a cell reads to a person, by its column's kind; `null` is "—". */ export function aiInsightCellText(table, key, value) {
|
|
225
222
|
return pluginFigureCellText(table, key, value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-insight.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 pluginFigureCellText,\n pluginFigureIsoWeek,\n type PluginFigureTable,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { weeklySummaryPeriod } from '@aglyn/aglyn/app-utils/weekly-summary'\nimport type { AiJob, AiJobOutput } from './ai-jobs.types'\nimport { AI_INSIGHT_DEFAULT_DAYS, AI_INSIGHT_WINDOWS } from './ai-insight-ask'\n\nexport {\n AI_INSIGHT_DEFAULT_DAYS,\n AI_INSIGHT_QUESTION_MAX_CHARS,\n AI_INSIGHT_WINDOWS,\n} from './ai-insight-ask'\n\n/**\n * Insights (AGL-2915): what an `insight` job answers, in the shape the step\n * writes and the console reads. Pure data — no server import — so the answer\n * card and the digest email type what they render from the module the step\n * writes it with.\n *\n * ## A number is read, never written\n *\n * The model never runs a query and never sees a record. Code reads figures —\n * traffic, orders, bookings, forms, campaigns, datasets, experiments — through\n * fixed, typed readers, each answering with one compact table that says where\n * its figures come from. The model picks the readers and phrases what their\n * tables say, and every insight it writes cites the rows its figures come from.\n * An insight whose numbers cannot be found in the rows it cites is left out\n * (`runtime/ai-insight-check.ts`), so each one a person reads can be traced to\n * a number they can open in the console.\n *\n * ## Read-only, and kept apart from the job\n *\n * An insight job writes one document besides its own record: the answer, at\n * `orgs/{orgId}/aiInsights/{jobId}`, which no rule lets a client read. The\n * job's output names it and carries no figure, because a job document is\n * readable by every member of the workspace and the figures are not: a\n * collaborator on one site may not see another site's revenue. The answer is\n * served by `GET /api/ai/insights/{jobId}` to the member who asked and, for a\n * weekly digest, to the members who reach its site.\n */\n\n/**\n * Where an insight was asked: the console page whose Assist panel — or\n * whose \"Ask AI about these numbers\" card — asked it, or the weekly digest,\n * which no person asked. A site's Marketing, Automation and Bookings pages\n * and the workspace's own pages joined at AGL-3603.\n */\nexport type AiInsightSurface =\n | 'analytics'\n | 'datasets'\n | 'crm-reports'\n | 'marketing'\n | 'automations'\n | 'bookings'\n | 'workspace'\n | 'digest'\n\nexport const AI_INSIGHT_SURFACES: readonly AiInsightSurface[] = [\n 'analytics',\n 'datasets',\n 'crm-reports',\n 'marketing',\n 'automations',\n 'bookings',\n 'workspace',\n 'digest',\n]\n\n/** The surfaces a person asks from. */\nexport const AI_INSIGHT_ASK_SURFACES: readonly AiInsightSurface[] = [\n 'analytics',\n 'datasets',\n 'crm-reports',\n 'marketing',\n 'automations',\n 'bookings',\n 'workspace',\n]\n\n/** The surface an insight job's inputs name, or `null` for one no insight job is asked from. */\nexport function aiInsightSurface(inputs: Readonly<Record<string, unknown>> | null | undefined): AiInsightSurface | null {\n const surface = inputs?.['surface']\n return typeof surface === 'string' && (AI_INSIGHT_SURFACES as readonly string[]).includes(surface)\n ? (surface as AiInsightSurface)\n : null\n}\n\n/**\n * The readers a surface may offer, by the first word of a reader's id. The\n * Analytics page — and a site's dashboard — answers about the site's traffic,\n * what it sold, took and collected, its automations' runs and its CRM\n * pipeline; a Data page about its datasets; CRM Reports about where people\n * came from, what they did and the pipeline; the Marketing page about what\n * its campaigns, overlays and tests caused and earned, beside the traffic and\n * the forms they drove; the Automation page about its runs; the Bookings page\n * about its bookings; and the workspace's own pages about its pipeline and\n * its datasets.\n */\nexport const AI_INSIGHT_SURFACE_READERS: Readonly<Record<AiInsightSurface, readonly string[]>> = {\n // `funnels` (AGL-3605): a site's funnels, step by step, beside its traffic.\n analytics: ['automations', 'bookings', 'commerce', 'crm', 'forms', 'funnels', 'marketing', 'traffic'],\n datasets: ['datasets'],\n 'crm-reports': ['bookings', 'commerce', 'crm', 'forms', 'marketing', 'traffic'],\n marketing: ['commerce', 'forms', 'marketing', 'traffic'],\n automations: ['automations'],\n bookings: ['bookings'],\n workspace: ['crm', 'datasets'],\n digest: ['bookings', 'commerce', 'forms', 'marketing', 'traffic'],\n}\n\n/** Whether a surface answers about one site; the Data page and the workspace's pages may answer about the whole workspace. */\nexport function aiInsightSurfaceNeedsSite(surface: AiInsightSurface): boolean {\n return surface !== 'datasets' && surface !== 'workspace'\n}\n\n/**\n * The readers a weekly digest reads, in the order the digest names them:\n * the traffic change, the top page, the days that stood out, the forms, the\n * campaigns, and what the site sold and took. Code reads these; no model\n * picks them.\n */\nexport const AI_INSIGHT_DIGEST_READERS: readonly string[] = [\n 'traffic.summary',\n 'traffic.pages',\n 'traffic.daily',\n 'forms.performance',\n 'marketing.campaigns',\n 'commerce.sales',\n 'bookings.services',\n]\n\n/** The window a weekly digest reads. */\nexport const AI_INSIGHT_DIGEST_DAYS = 7\n\n/**\n * The week a digest reads (AGL-3867): Monday to Sunday before the Monday it\n * was made, the same week the free Weekly summary reports, so the two emails\n * a person gets that morning quote the same figures. The sweep stamps the\n * week's last day as `through`; a job made before it did reads the week\n * before `now`.\n */\nexport function aiInsightDigestPeriod(\n inputs: Record<string, unknown> | null | undefined,\n now: Date,\n): ReturnType<typeof weeklySummaryPeriod> {\n const through = typeof inputs?.['through'] === 'string' ? inputs['through'] : ''\n const day = /^\\d{4}-\\d{2}-\\d{2}$/.test(through) ? Date.parse(`${through}T00:00:00Z`) : Number.NaN\n return weeklySummaryPeriod(Number.isFinite(day) ? new Date(day + 86_400_000) : now)\n}\n\n/** A window an insight's inputs or a read names, held to the readers' own ranges. */\nexport function aiInsightDays(value: unknown): number {\n const days = typeof value === 'number' ? value : Number(value)\n return AI_INSIGHT_WINDOWS.includes(days) ? days : AI_INSIGHT_DEFAULT_DAYS\n}\n\n/** The most insights one answer carries: a person reads them at a glance. */\nexport const AI_INSIGHT_MAX_INSIGHTS = 5\n\n/** The longest one insight may run, in characters. */\nexport const AI_INSIGHT_MAX_CHARS = 280\n\n/** How long an insight's headline may run. */\nexport const AI_INSIGHT_HEADLINE_MAX_CHARS = 60\n\n/** The longest the sentence about what the figures could not answer may run. */\nexport const AI_INSIGHT_GAP_MAX_CHARS = 200\n\n/** The most tables one citation list names. */\nexport const AI_INSIGHT_MAX_CITES = 3\n\n/** The most rows one citation names. */\nexport const AI_INSIGHT_MAX_CITED_ROWS = 10\n\n/** The most readers one answer reads. */\nexport const AI_INSIGHT_MAX_READS = 4\n\n/**\n * A table as an insight job keeps it: the figures a reader returned, the\n * handle the model cites them by, and the reader they came from.\n */\nexport interface AiInsightTable extends PluginFigureTable {\n /** `t1`, `t2`, …, in the order the job read them. */\n ref: string\n /** The reader's id (`commerce.sales`). */\n reader: string\n /** The window the reader was asked for, in days; 0 for a reader of current counts. */\n days: number\n /** Whether the table is about one site (its path under that site) or the workspace. */\n scope: 'site' | 'org'\n}\n\n/** The rows of one table an insight's figures come from, by index. */\nexport interface AiInsightCitation {\n table: string\n rows: number[]\n}\n\nexport interface AiInsight {\n /** What happened, in a few words: what the eye lands on. Absent on an answer from before it was asked for. */\n headline?: string\n /** One or two plain sentences. */\n text: string\n cites: AiInsightCitation[]\n}\n\n/** What the model answers with. */\nexport interface AiInsightAnswer {\n insights: AiInsight[]\n /** What the figures could not answer, in one sentence without numbers; `null` when nothing. */\n gap: string | null\n}\n\n/** The answer collection under the org: server-written, and read through the insights door alone. */\nexport const AI_INSIGHTS_COLLECTION = 'aiInsights'\n\n/** An insight job's answer, as the step stores it. */\nexport interface AiInsightRecord {\n jobId: string\n orgId: string\n hostId: string | null\n surface: AiInsightSurface\n /** The member whose question it answers; for a digest, the member it was made for. */\n createdBy: string\n /** The question, verbatim; a digest's is the digest's own title. */\n question: string\n /** The window the answer was asked about, in days. */\n days: number\n /** The insights that trace to the rows they cite; every other one was left out. */\n insights: AiInsight[]\n gap: string | null\n /** Every table the job read, so each citation opens the figures it names. */\n tables: AiInsightTable[]\n /** How many insights the answer carried that were left out as not traceable. */\n left: number\n /** The ISO week a digest covers (`2026-W38`); `null` on a question. */\n week: string | null\n createdAtMs: number\n}\n\n/** The output id an answer is named by. */\nexport const AI_INSIGHT_OUTPUT_LABEL = 'Answer'\n\n/**\n * The output an insight job records: the answer's address and how many\n * insights it holds, and no figure. The count is a statement about the\n * answer rather than about the site, so every member may read it.\n */\nexport function aiInsightOutput(\n job: Pick<AiJob, '$id' | 'hostId'>,\n record: Pick<AiInsightRecord, 'insights' | 'surface'>,\n hostSubdomain: string | null,\n): AiJobOutput {\n const count = record.insights.length\n return {\n resource: 'insight',\n id: job.$id,\n versionId: null,\n hostId: job.hostId ?? null,\n hostSubdomain,\n label: record.surface === 'digest' ? 'Weekly insights' : AI_INSIGHT_OUTPUT_LABEL,\n note: count\n ? `${count} ${count === 1 ? 'insight' : 'insights'}, each traced to the figures it cites.`\n : 'The figures did not answer this question.',\n }\n}\n\n/** The answer on the wire: the stored record, with nothing a client does not render. */\nexport type AiInsightAnswerWire = AiInsightRecord\n\n/**\n * The Assist panel's insight surface for a console path, or `null` off one:\n * a site's dashboard, Analytics, Data, CRM Reports, Marketing, Automation and\n * Bookings pages; the workspace's Data page; and the workspace's sites page\n * and CRM Reports, which read the workspace's pipeline and datasets. The\n * organization's Marketing page reads site figures, so it is not one — it\n * asks about the site it is showing, through its own in-page entry.\n */\nexport function aiInsightSurfaceForPath(\n pathname: string | null | undefined,\n): { surface: Exclude<AiInsightSurface, 'digest'>; host: string | null } | null {\n const segments = String(pathname ?? '')\n .split('?')[0]\n .split('/')\n .filter(Boolean)\n // `/{org}/hosts/{host}/…` on a site, `/{org}/…` on the workspace.\n if (segments[1] === 'hosts' && segments.length >= 4) {\n const host = segments[2]\n const rest = segments.slice(3)\n if (rest[0] === 'analytics') return { surface: 'analytics', host }\n if (rest[0] === 'data') return { surface: 'datasets', host }\n if (rest[0] === 'crm' && rest[1] === 'reports') return { surface: 'crm-reports', host }\n if (rest[0] === 'marketing') return { surface: 'marketing', host }\n if (rest[0] === 'automation') return { surface: 'automations', host }\n if (rest[0] === 'bookings') return { surface: 'bookings', host }\n return null\n }\n // The site's dashboard is `/{org}/hosts/{host}`.\n if (segments[1] === 'hosts' && segments.length === 3) return { surface: 'analytics', host: segments[2] }\n if (segments.length >= 2 && segments[1] === 'data') return { surface: 'datasets', host: null }\n // The workspace's sites page, `/{org}/hosts`, which carries its dashboard row.\n if (segments.length === 2 && segments[1] === 'hosts') return { surface: 'workspace', host: null }\n if (segments[1] === 'crm' && segments[2] === 'reports') return { surface: 'workspace', host: null }\n return null\n}\n\n/** The console page a table's figures come from, or `null` when the table names none. */\nexport function aiInsightSourceHref(\n table: Pick<AiInsightTable, 'source' | 'scope'>,\n where: { orgSlug: string; host: string | null },\n): string | null {\n const path = table.source.path\n if (!path || !where.orgSlug) return null\n if (table.scope === 'org') return `/${where.orgSlug}/${path}`\n return where.host ? `/${where.orgSlug}/hosts/${where.host}/${path}` : null\n}\n\n/** How a cell reads to a person, by its column's kind; `null` is \"—\". */\nexport function aiInsightCellText(\n table: Pick<AiInsightTable, 'columns'>,\n key: string,\n value: string | number | null | undefined,\n): string {\n return pluginFigureCellText(table, key, value)\n}\n\n/** One cited row as a line a person reads: every column, labeled. */\nexport function aiInsightRowText(table: Pick<AiInsightTable, 'columns' | 'rows'>, index: number): string {\n const row = table.rows[index]\n if (!row) return ''\n return table.columns\n .map((column) => `${column.label}: ${aiInsightCellText(table, column.key, row[column.key])}`)\n .join(' · ')\n}\n\n/** The ISO 8601 week an instant falls in, in UTC (`2026-W38`). */\nexport function aiInsightIsoWeek(at: Date): string {\n return pluginFigureIsoWeek(at)\n}\n"],"names":["pluginFigureCellText","pluginFigureIsoWeek","weeklySummaryPeriod","AI_INSIGHT_DEFAULT_DAYS","AI_INSIGHT_WINDOWS","AI_INSIGHT_QUESTION_MAX_CHARS","AI_INSIGHT_SURFACES","AI_INSIGHT_ASK_SURFACES","aiInsightSurface","inputs","surface","includes","AI_INSIGHT_SURFACE_READERS","analytics","datasets","marketing","automations","bookings","workspace","digest","aiInsightSurfaceNeedsSite","AI_INSIGHT_DIGEST_READERS","AI_INSIGHT_DIGEST_DAYS","aiInsightDigestPeriod","now","through","day","test","Date","parse","Number","NaN","isFinite","aiInsightDays","value","days","AI_INSIGHT_MAX_INSIGHTS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_READS","AI_INSIGHTS_COLLECTION","AI_INSIGHT_OUTPUT_LABEL","aiInsightOutput","job","record","hostSubdomain","count","insights","length","resource","id","$id","versionId","hostId","label","note","aiInsightSurfaceForPath","pathname","segments","String","split","filter","Boolean","host","rest","slice","aiInsightSourceHref","table","where","path","source","orgSlug","scope","aiInsightCellText","key","aiInsightRowText","index","row","rows","columns","map","column","join","aiInsightIsoWeek","at"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EACpBC,mBAAmB,QAEd,6CAA4C;AACnD,SAASC,mBAAmB,QAAQ,wCAAuC;AAE3E,SAASC,uBAAuB,EAAEC,kBAAkB,QAAQ,sBAAkB;AAE9E,SACED,uBAAuB,EACvBE,6BAA6B,EAC7BD,kBAAkB,QACb,sBAAkB;AA8CzB,OAAO,MAAME,sBAAmD;IAC9D;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,qCAAqC,GACrC,OAAO,MAAMC,0BAAuD;IAClE;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,8FAA8F,GAC9F,OAAO,SAASC,iBAAiBC,MAA4D;IAC3F,MAAMC,UAAUD,0BAAAA,MAAQ,CAAC,UAAU;IACnC,OAAO,OAAOC,YAAY,YAAY,AAACJ,oBAA0CK,QAAQ,CAACD,WACrFA,UACD;AACN;AAEA;;;;;;;;;;CAUC,GACD,OAAO,MAAME,6BAAoF;IAC/F,4EAA4E;IAC5EC,WAAW;QAAC;QAAe;QAAY;QAAY;QAAO;QAAS;QAAW;QAAa;KAAU;IACrGC,UAAU;QAAC;KAAW;IACtB,eAAe;QAAC;QAAY;QAAY;QAAO;QAAS;QAAa;KAAU;IAC/EC,WAAW;QAAC;QAAY;QAAS;QAAa;KAAU;IACxDC,aAAa;QAAC;KAAc;IAC5BC,UAAU;QAAC;KAAW;IACtBC,WAAW;QAAC;QAAO;KAAW;IAC9BC,QAAQ;QAAC;QAAY;QAAY;QAAS;QAAa;KAAU;AACnE,EAAC;AAED,4HAA4H,GAC5H,OAAO,SAASC,0BAA0BV,OAAyB;IACjE,OAAOA,YAAY,cAAcA,YAAY;AAC/C;AA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AAG,CAAC,GAAG,EAC3FQ,IAAI,CAAC;AACV;AAEA,gEAAgE,GAChE,OAAO,SAASC,iBAAiBC,EAAQ;IACvC,OAAOtF,oBAAoBsF;AAC7B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-insight.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 pluginFigureCellText,\n pluginFigureIsoWeek,\n pluginFigureSourceHref,\n type PluginFigureTable,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { weeklySummaryPeriod } from '@aglyn/aglyn/app-utils/weekly-summary'\nimport type { AiJob, AiJobOutput } from './ai-jobs.types'\nimport { AI_INSIGHT_DEFAULT_DAYS, AI_INSIGHT_WINDOWS } from './ai-insight-ask'\n\nexport {\n AI_INSIGHT_DEFAULT_DAYS,\n AI_INSIGHT_QUESTION_MAX_CHARS,\n AI_INSIGHT_WINDOWS,\n} from './ai-insight-ask'\n\n/**\n * Insights (AGL-2915): what an `insight` job answers, in the shape the step\n * writes and the console reads. Pure data — no server import — so the answer\n * card and the digest email type what they render from the module the step\n * writes it with.\n *\n * ## A number is read, never written\n *\n * The model never runs a query and never sees a record. Code reads figures —\n * traffic, orders, bookings, forms, campaigns, datasets, experiments — through\n * fixed, typed readers, each answering with one compact table that says where\n * its figures come from. The model picks the readers and phrases what their\n * tables say, and every insight it writes cites the rows its figures come from.\n * An insight whose numbers cannot be found in the rows it cites is left out\n * (`runtime/ai-insight-check.ts`), so each one a person reads can be traced to\n * a number they can open in the console.\n *\n * ## Read-only, and kept apart from the job\n *\n * An insight job writes one document besides its own record: the answer, at\n * `orgs/{orgId}/aiInsights/{jobId}`, which no rule lets a client read. The\n * job's output names it and carries no figure, because a job document is\n * readable by every member of the workspace and the figures are not: a\n * collaborator on one site may not see another site's revenue. The answer is\n * served by `GET /api/ai/insights/{jobId}` to the member who asked and, for a\n * weekly digest, to the members who reach its site.\n */\n\n/**\n * Where an insight was asked: the console page whose Assist panel — or\n * whose \"Ask AI about these numbers\" card — asked it, or the weekly digest,\n * which no person asked. A site's Marketing, Automation and Bookings pages\n * and the workspace's own pages joined at AGL-3603.\n */\nexport type AiInsightSurface =\n | 'analytics'\n | 'datasets'\n | 'crm-reports'\n | 'marketing'\n | 'automations'\n | 'bookings'\n | 'workspace'\n | 'digest'\n\nexport const AI_INSIGHT_SURFACES: readonly AiInsightSurface[] = [\n 'analytics',\n 'datasets',\n 'crm-reports',\n 'marketing',\n 'automations',\n 'bookings',\n 'workspace',\n 'digest',\n]\n\n/** The surfaces a person asks from. */\nexport const AI_INSIGHT_ASK_SURFACES: readonly AiInsightSurface[] = [\n 'analytics',\n 'datasets',\n 'crm-reports',\n 'marketing',\n 'automations',\n 'bookings',\n 'workspace',\n]\n\n/** The surface an insight job's inputs name, or `null` for one no insight job is asked from. */\nexport function aiInsightSurface(inputs: Readonly<Record<string, unknown>> | null | undefined): AiInsightSurface | null {\n const surface = inputs?.['surface']\n return typeof surface === 'string' && (AI_INSIGHT_SURFACES as readonly string[]).includes(surface)\n ? (surface as AiInsightSurface)\n : null\n}\n\n/**\n * The readers a surface may offer, by the first word of a reader's id. The\n * Analytics page — and a site's dashboard — answers about the site's traffic,\n * what it sold, took and collected, its automations' runs and its CRM\n * pipeline; a Data page about its datasets; CRM Reports about where people\n * came from, what they did and the pipeline; the Marketing page about what\n * its campaigns, overlays and tests caused and earned, beside the traffic and\n * the forms they drove; the Automation page about its runs; the Bookings page\n * about its bookings; and the workspace's own pages about its pipeline and\n * its datasets.\n */\nexport const AI_INSIGHT_SURFACE_READERS: Readonly<Record<AiInsightSurface, readonly string[]>> = {\n // `funnels` (AGL-3605): a site's funnels, step by step, beside its traffic.\n analytics: ['automations', 'bookings', 'commerce', 'crm', 'forms', 'funnels', 'marketing', 'traffic'],\n datasets: ['datasets'],\n 'crm-reports': ['bookings', 'commerce', 'crm', 'forms', 'marketing', 'traffic'],\n marketing: ['commerce', 'forms', 'marketing', 'traffic'],\n automations: ['automations'],\n bookings: ['bookings'],\n workspace: ['crm', 'datasets'],\n digest: ['bookings', 'commerce', 'forms', 'marketing', 'traffic'],\n}\n\n/** Whether a surface answers about one site; the Data page and the workspace's pages may answer about the whole workspace. */\nexport function aiInsightSurfaceNeedsSite(surface: AiInsightSurface): boolean {\n return surface !== 'datasets' && surface !== 'workspace'\n}\n\n/**\n * The readers a weekly digest reads, in the order the digest names them:\n * the traffic change, the top page, the days that stood out, the forms, the\n * campaigns, and what the site sold and took. Code reads these; no model\n * picks them.\n */\nexport const AI_INSIGHT_DIGEST_READERS: readonly string[] = [\n 'traffic.summary',\n 'traffic.pages',\n 'traffic.daily',\n 'forms.performance',\n 'marketing.campaigns',\n 'commerce.sales',\n 'bookings.services',\n]\n\n/** The window a weekly digest reads. */\nexport const AI_INSIGHT_DIGEST_DAYS = 7\n\n/**\n * The week a digest reads (AGL-3867): Monday to Sunday before the Monday it\n * was made, the same week the free Weekly summary reports, so the two emails\n * a person gets that morning quote the same figures. The sweep stamps the\n * week's last day as `through`; a job made before it did reads the week\n * before `now`.\n */\nexport function aiInsightDigestPeriod(\n inputs: Record<string, unknown> | null | undefined,\n now: Date,\n): ReturnType<typeof weeklySummaryPeriod> {\n const through = typeof inputs?.['through'] === 'string' ? inputs['through'] : ''\n const day = /^\\d{4}-\\d{2}-\\d{2}$/.test(through) ? Date.parse(`${through}T00:00:00Z`) : Number.NaN\n return weeklySummaryPeriod(Number.isFinite(day) ? new Date(day + 86_400_000) : now)\n}\n\n/** A window an insight's inputs or a read names, held to the readers' own ranges. */\nexport function aiInsightDays(value: unknown): number {\n const days = typeof value === 'number' ? value : Number(value)\n return AI_INSIGHT_WINDOWS.includes(days) ? days : AI_INSIGHT_DEFAULT_DAYS\n}\n\n/** The most insights one answer carries: a person reads them at a glance. */\nexport const AI_INSIGHT_MAX_INSIGHTS = 5\n\n/** The longest one insight may run, in characters. */\nexport const AI_INSIGHT_MAX_CHARS = 280\n\n/** How long an insight's headline may run. */\nexport const AI_INSIGHT_HEADLINE_MAX_CHARS = 60\n\n/** The longest the sentence about what the figures could not answer may run. */\nexport const AI_INSIGHT_GAP_MAX_CHARS = 200\n\n/** The most tables one citation list names. */\nexport const AI_INSIGHT_MAX_CITES = 3\n\n/** The most rows one citation names. */\nexport const AI_INSIGHT_MAX_CITED_ROWS = 10\n\n/** The most readers one answer reads. */\nexport const AI_INSIGHT_MAX_READS = 4\n\n/**\n * A table as an insight job keeps it: the figures a reader returned, the\n * handle the model cites them by, and the reader they came from.\n */\nexport interface AiInsightTable extends PluginFigureTable {\n /** `t1`, `t2`, …, in the order the job read them. */\n ref: string\n /** The reader's id (`commerce.sales`). */\n reader: string\n /** The window the reader was asked for, in days; 0 for a reader of current counts. */\n days: number\n /** Whether the table is about one site (its path under that site) or the workspace. */\n scope: 'site' | 'org'\n}\n\n/** The rows of one table an insight's figures come from, by index. */\nexport interface AiInsightCitation {\n table: string\n rows: number[]\n}\n\nexport interface AiInsight {\n /** What happened, in a few words: what the eye lands on. Absent on an answer from before it was asked for. */\n headline?: string\n /** One or two plain sentences. */\n text: string\n cites: AiInsightCitation[]\n}\n\n/** What the model answers with. */\nexport interface AiInsightAnswer {\n insights: AiInsight[]\n /** What the figures could not answer, in one sentence without numbers; `null` when nothing. */\n gap: string | null\n}\n\n/** The answer collection under the org: server-written, and read through the insights door alone. */\nexport const AI_INSIGHTS_COLLECTION = 'aiInsights'\n\n/** An insight job's answer, as the step stores it. */\nexport interface AiInsightRecord {\n jobId: string\n orgId: string\n hostId: string | null\n surface: AiInsightSurface\n /** The member whose question it answers; for a digest, the member it was made for. */\n createdBy: string\n /** The question, verbatim; a digest's is the digest's own title. */\n question: string\n /** The window the answer was asked about, in days. */\n days: number\n /** The insights that trace to the rows they cite; every other one was left out. */\n insights: AiInsight[]\n gap: string | null\n /** Every table the job read, so each citation opens the figures it names. */\n tables: AiInsightTable[]\n /** How many insights the answer carried that were left out as not traceable. */\n left: number\n /** The ISO week a digest covers (`2026-W38`); `null` on a question. */\n week: string | null\n createdAtMs: number\n}\n\n/** The output id an answer is named by. */\nexport const AI_INSIGHT_OUTPUT_LABEL = 'Answer'\n\n/**\n * The output an insight job records: the answer's address and how many\n * insights it holds, and no figure. The count is a statement about the\n * answer rather than about the site, so every member may read it.\n */\nexport function aiInsightOutput(\n job: Pick<AiJob, '$id' | 'hostId'>,\n record: Pick<AiInsightRecord, 'insights' | 'surface'>,\n hostSubdomain: string | null,\n): AiJobOutput {\n const count = record.insights.length\n return {\n resource: 'insight',\n id: job.$id,\n versionId: null,\n hostId: job.hostId ?? null,\n hostSubdomain,\n label: record.surface === 'digest' ? 'Weekly insights' : AI_INSIGHT_OUTPUT_LABEL,\n note: count\n ? `${count} ${count === 1 ? 'insight' : 'insights'}, each traced to the figures it cites.`\n : 'The figures did not answer this question.',\n }\n}\n\n/** The answer on the wire: the stored record, with nothing a client does not render. */\nexport type AiInsightAnswerWire = AiInsightRecord\n\n/**\n * The Assist panel's insight surface for a console path, or `null` off one:\n * a site's dashboard, Analytics, Data, CRM Reports, Marketing, Automation and\n * Bookings pages; the workspace's Data page; and the workspace's sites page\n * and CRM Reports, which read the workspace's pipeline and datasets. The\n * organization's Marketing page reads site figures, so it is not one — it\n * asks about the site it is showing, through its own in-page entry.\n */\nexport function aiInsightSurfaceForPath(\n pathname: string | null | undefined,\n): { surface: Exclude<AiInsightSurface, 'digest'>; host: string | null } | null {\n const segments = String(pathname ?? '')\n .split('?')[0]\n .split('/')\n .filter(Boolean)\n // `/{org}/hosts/{host}/…` on a site, `/{org}/…` on the workspace.\n if (segments[1] === 'hosts' && segments.length >= 4) {\n const host = segments[2]\n const rest = segments.slice(3)\n if (rest[0] === 'analytics') return { surface: 'analytics', host }\n if (rest[0] === 'data') return { surface: 'datasets', host }\n if (rest[0] === 'crm' && rest[1] === 'reports') return { surface: 'crm-reports', host }\n if (rest[0] === 'marketing') return { surface: 'marketing', host }\n if (rest[0] === 'automation') return { surface: 'automations', host }\n if (rest[0] === 'bookings') return { surface: 'bookings', host }\n return null\n }\n // The site's dashboard is `/{org}/hosts/{host}`.\n if (segments[1] === 'hosts' && segments.length === 3) return { surface: 'analytics', host: segments[2] }\n if (segments.length >= 2 && segments[1] === 'data') return { surface: 'datasets', host: null }\n // The workspace's sites page, `/{org}/hosts`, which carries its dashboard row.\n if (segments.length === 2 && segments[1] === 'hosts') return { surface: 'workspace', host: null }\n if (segments[1] === 'crm' && segments[2] === 'reports') return { surface: 'workspace', host: null }\n return null\n}\n\n/** The console page a table's figures come from, or `null` when the table names none. */\nexport function aiInsightSourceHref(\n table: Pick<AiInsightTable, 'source' | 'scope'>,\n where: { orgSlug: string; host: string | null },\n): string | null {\n return pluginFigureSourceHref(table.source, table.scope === 'org' ? 'org' : 'site', where)\n}\n\n/** How a cell reads to a person, by its column's kind; `null` is \"—\". */\nexport function aiInsightCellText(\n table: Pick<AiInsightTable, 'columns'>,\n key: string,\n value: string | number | null | undefined,\n): string {\n return pluginFigureCellText(table, key, value)\n}\n\n/** One cited row as a line a person reads: every column, labeled. */\nexport function aiInsightRowText(table: Pick<AiInsightTable, 'columns' | 'rows'>, index: number): string {\n const row = table.rows[index]\n if (!row) return ''\n return table.columns\n .map((column) => `${column.label}: ${aiInsightCellText(table, column.key, row[column.key])}`)\n .join(' · ')\n}\n\n/** The ISO 8601 week an instant falls in, in UTC (`2026-W38`). */\nexport function aiInsightIsoWeek(at: Date): string {\n return pluginFigureIsoWeek(at)\n}\n"],"names":["pluginFigureCellText","pluginFigureIsoWeek","pluginFigureSourceHref","weeklySummaryPeriod","AI_INSIGHT_DEFAULT_DAYS","AI_INSIGHT_WINDOWS","AI_INSIGHT_QUESTION_MAX_CHARS","AI_INSIGHT_SURFACES","AI_INSIGHT_ASK_SURFACES","aiInsightSurface","inputs","surface","includes","AI_INSIGHT_SURFACE_READERS","analytics","datasets","marketing","automations","bookings","workspace","digest","aiInsightSurfaceNeedsSite","AI_INSIGHT_DIGEST_READERS","AI_INSIGHT_DIGEST_DAYS","aiInsightDigestPeriod","now","through","day","test","Date","parse","Number","NaN","isFinite","aiInsightDays","value","days","AI_INSIGHT_MAX_INSIGHTS","AI_INSIGHT_MAX_CHARS","AI_INSIGHT_HEADLINE_MAX_CHARS","AI_INSIGHT_GAP_MAX_CHARS","AI_INSIGHT_MAX_CITES","AI_INSIGHT_MAX_CITED_ROWS","AI_INSIGHT_MAX_READS","AI_INSIGHTS_COLLECTION","AI_INSIGHT_OUTPUT_LABEL","aiInsightOutput","job","record","hostSubdomain","count","insights","length","resource","id","$id","versionId","hostId","label","note","aiInsightSurfaceForPath","pathname","segments","String","split","filter","Boolean","host","rest","slice","aiInsightSourceHref","table","where","source","scope","aiInsightCellText","key","aiInsightRowText","index","row","rows","columns","map","column","join","aiInsightIsoWeek","at"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EACpBC,mBAAmB,EACnBC,sBAAsB,QAEjB,6CAA4C;AACnD,SAASC,mBAAmB,QAAQ,wCAAuC;AAE3E,SAASC,uBAAuB,EAAEC,kBAAkB,QAAQ,sBAAkB;AAE9E,SACED,uBAAuB,EACvBE,6BAA6B,EAC7BD,kBAAkB,QACb,sBAAkB;AA8CzB,OAAO,MAAME,sBAAmD;IAC9D;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,qCAAqC,GACrC,OAAO,MAAMC,0BAAuD;IAClE;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,8FAA8F,GAC9F,OAAO,SAASC,iBAAiBC,MAA4D;IAC3F,MAAMC,UA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