@aglyn/plugins-ai 1.6.0 → 1.8.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/README.md +2 -2
- package/package.json +17 -17
- package/src/lib/components/ai-insight-dialog.component.js +14 -0
- package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
- package/src/lib/insights/ai-figure-readers.d.ts +13 -0
- package/src/lib/insights/ai-figure-readers.js +158 -11
- package/src/lib/insights/ai-figure-readers.js.map +1 -1
- package/src/lib/insights/ai-figure-summaries.js +4 -2
- package/src/lib/insights/ai-figure-summaries.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +27 -17
- package/src/lib/insights/ai-insight-digest.js +96 -107
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-job-import-step.d.ts +28 -2
- package/src/lib/jobs/ai-job-import-step.js +170 -14
- package/src/lib/jobs/ai-job-import-step.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-budget.d.ts +19 -3
- package/src/lib/jobs/ai-job-insight-budget.js +18 -4
- package/src/lib/jobs/ai-job-insight-budget.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +2 -2
- package/src/lib/jobs/ai-job-insight-step.js +17 -7
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-language.js +2 -0
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.js +6 -2
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-site-import-compile.d.ts +13 -3
- package/src/lib/jobs/ai-site-import-compile.js +336 -27
- package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
- package/src/lib/jobs/ai-site-import-document.d.ts +3 -1
- package/src/lib/jobs/ai-site-import-document.js +36 -0
- package/src/lib/jobs/ai-site-import-document.js.map +1 -1
- package/src/lib/jobs/ai-site-import-look.d.ts +9 -0
- package/src/lib/jobs/ai-site-import-look.js +89 -6
- package/src/lib/jobs/ai-site-import-look.js.map +1 -1
- package/src/lib/layout-language/ai-layout-compiler.d.ts +16 -0
- package/src/lib/layout-language/ai-layout-compiler.js +351 -54
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame-source.d.ts +88 -2
- package/src/lib/layout-language/ai-layout-frame-source.js +591 -30
- package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame.js +30 -18
- package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
- package/src/lib/layout-language/ai-layout-language.d.ts +72 -3
- package/src/lib/layout-language/ai-layout-language.js +5 -3
- package/src/lib/layout-language/ai-layout-language.js.map +1 -1
- package/src/lib/layout-language/ai-layout-store.d.ts +8 -0
- package/src/lib/layout-language/ai-layout-store.js +32 -6
- package/src/lib/layout-language/ai-layout-store.js.map +1 -1
- package/src/lib/model/ai-insight.d.ts +23 -3
- package/src/lib/model/ai-insight.js +17 -3
- package/src/lib/model/ai-insight.js.map +1 -1
- package/src/lib/model/ai-site-import-fidelity.d.ts +31 -1
- package/src/lib/model/ai-site-import-fidelity.js +347 -25
- package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
- package/src/lib/model/ai-site-import.d.ts +203 -6
- package/src/lib/model/ai-site-import.js +161 -5
- package/src/lib/model/ai-site-import.js.map +1 -1
- package/src/lib/model/ai-site-look.d.ts +8 -1
- package/src/lib/model/ai-site-look.js +8 -5
- package/src/lib/model/ai-site-look.js.map +1 -1
- package/src/lib/providers/routing.js +3 -1
- package/src/lib/providers/routing.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +7 -1
- package/src/lib/runtime/ai-doctrine-validators.js +25 -2
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-insight-check.d.ts +7 -0
- package/src/lib/runtime/ai-insight-check.js +111 -27
- package/src/lib/runtime/ai-insight-check.js.map +1 -1
- package/src/lib/runtime/ai-node-tree.js +19 -2
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/runtime/ai-page-links.d.ts +15 -0
- package/src/lib/runtime/ai-page-links.js +48 -0
- package/src/lib/runtime/ai-page-links.js.map +1 -1
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +30 -5
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
- package/src/lib/site-import/fixtures/site-layout-recordings.d.ts +9 -0
- package/src/lib/site-import/fixtures/site-layout-recordings.js +24 -5
- package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
- package/src/lib/site-import/site-import-crawl.d.ts +3 -1
- package/src/lib/site-import/site-import-crawl.js +8 -3
- package/src/lib/site-import/site-import-crawl.js.map +1 -1
- package/src/lib/site-import/site-import-css.d.ts +20 -0
- package/src/lib/site-import/site-import-css.js +106 -0
- package/src/lib/site-import/site-import-css.js.map +1 -1
- package/src/lib/site-import/site-import-html.d.ts +39 -0
- package/src/lib/site-import/site-import-html.js +515 -5
- package/src/lib/site-import/site-import-html.js.map +1 -1
- package/src/lib/site-import/site-import-layout.d.ts +16 -6
- package/src/lib/site-import/site-import-layout.js +524 -52
- package/src/lib/site-import/site-import-layout.js.map +1 -1
- package/src/lib/site-import/site-import-nav.js +286 -24
- package/src/lib/site-import/site-import-nav.js.map +1 -1
- package/src/lib/site-import/site-import-page.js +3 -0
- package/src/lib/site-import/site-import-page.js.map +1 -1
- package/src/lib/tools/ai-insight-tool.js +45 -2
- package/src/lib/tools/ai-insight-tool.js.map +1 -1
|
@@ -20,9 +20,9 @@ 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,
|
|
24
|
-
import {
|
|
25
|
-
import { aiInsightDigestPeriod, aiInsightSourceHref, AI_INSIGHTS_COLLECTION, aiInsightIsoWeek } from "../model/ai-insight.js";
|
|
23
|
+
import { weeklySummaryFootnoteHtml, weeklySummaryLeadHtml, weeklySummaryNoteHtml, weeklySummaryPeriod, weeklySummaryPlainDates, weeklySummaryRowLink, weeklySummarySectionsHtml } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
24
|
+
import { pluginFigureCellText, pluginFigureDay } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
25
|
+
import { AI_INSIGHT_DIGEST_DAYS, aiInsightDigestPeriod, aiInsightSourceHref, AI_INSIGHTS_COLLECTION, aiInsightIsoWeek } from "../model/ai-insight.js";
|
|
26
26
|
import { isAiOnForSite } from "../model/ai-site-switch.js";
|
|
27
27
|
import { cancelAiJob, createAiJob, getAiJob } from "../jobs/ai-jobs.js";
|
|
28
28
|
export const AI_INSIGHTS_DIGEST_CRON_ID = 'ai-insights-digest';
|
|
@@ -30,6 +30,11 @@ export const AI_INSIGHTS_DIGEST_PATH = 'admin/ai-insights-digest';
|
|
|
30
30
|
/** Orgs one call reads; a chunk that times out never advances the cursor, so the safe size is one that finishes. */ export const AI_INSIGHT_DIGEST_ORG_CHUNK = 25;
|
|
31
31
|
/** Sites one workspace's digest covers a week. */ export const AI_INSIGHT_DIGEST_MAX_SITES = 5;
|
|
32
32
|
/** Sites a workspace's sweep reads before it ranks them. */ export const AI_INSIGHT_DIGEST_HOST_READ_LIMIT = 50;
|
|
33
|
+
/**
|
|
34
|
+
* The page views a week needs to be worth explaining. Under this, a reading
|
|
35
|
+
* rests on a handful of visits and would spend credits saying nothing, so the
|
|
36
|
+
* site gets no job and the free Weekly summary stands alone.
|
|
37
|
+
*/ export const AI_INSIGHT_DIGEST_MIN_VIEWS = 50;
|
|
33
38
|
/** Workspaces one run delivers to, per week. */ export const AI_INSIGHT_DIGEST_DELIVER_LIMIT = 100;
|
|
34
39
|
/** How long a digest's job may take before its week is given up. */ export const AI_INSIGHT_DIGEST_DEADLINE_MS = 48 * 60 * 60000;
|
|
35
40
|
/**
|
|
@@ -62,6 +67,10 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
62
67
|
return [
|
|
63
68
|
input.periodLabel ? `Here is what ${input.siteName}'s figures showed last week, ${input.periodLabel}.${drew}` : `Here is what ${input.siteName}'s figures showed this week.${drew}`,
|
|
64
69
|
'',
|
|
70
|
+
...input.overview ? [
|
|
71
|
+
`The week in short: ${weeklySummaryPlainDates(input.overview)}`,
|
|
72
|
+
''
|
|
73
|
+
] : [],
|
|
65
74
|
...input.insights.map((insight, index)=>`${index + 1}. ${aiInsightDigestLine(insight)}`),
|
|
66
75
|
'',
|
|
67
76
|
input.analyticsUrl ? `Each of these is traced to the figures it cites. See them in ${input.productName}: ${input.analyticsUrl}` : `Each of these is traced to the figures it cites. See them on the site's Analytics page in ${input.productName}.`,
|
|
@@ -69,134 +78,94 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
69
78
|
input.settingsUrl ? `You asked for weekly insights for ${forWhom}. Turn them off in Notifications: ${input.settingsUrl}` : `You asked for weekly insights for ${forWhom}. Turn them off in your Notifications settings.`
|
|
70
79
|
].join('\n');
|
|
71
80
|
}
|
|
72
|
-
/** An insight in
|
|
81
|
+
/** An insight in plain text, its dates as a person says them, its reason and next step on their own lines. */ function aiInsightDigestLine(insight) {
|
|
73
82
|
const text = weeklySummaryPlainDates(insight.text);
|
|
74
|
-
return
|
|
83
|
+
return [
|
|
84
|
+
insight.headline ? `${insight.headline}: ${text}` : text,
|
|
85
|
+
...insight.why ? [
|
|
86
|
+
`Likely why: ${weeklySummaryPlainDates(insight.why)}`
|
|
87
|
+
] : [],
|
|
88
|
+
...insight.next ? [
|
|
89
|
+
`Try this: ${weeklySummaryPlainDates(insight.next)}`
|
|
90
|
+
] : []
|
|
91
|
+
].join('\n');
|
|
75
92
|
}
|
|
76
|
-
/** The most
|
|
77
|
-
/** The most rows a section lists. */ export const AI_INSIGHT_DIGEST_MAX_ROWS = 5;
|
|
93
|
+
/** The most rows an insight lists under it: support for what it says, not a report. */ export const AI_INSIGHT_DIGEST_MAX_ROWS = 3;
|
|
78
94
|
/** The columns that hold a figure a row can show, as against a label or a change. */ const FIGURE_KINDS = [
|
|
79
95
|
'count',
|
|
80
96
|
'money',
|
|
81
97
|
'percent',
|
|
82
98
|
'duration'
|
|
83
99
|
];
|
|
84
|
-
/**
|
|
85
|
-
|
|
86
|
-
* weekly summary. Only a figure compared with the week before earns a tile: a
|
|
87
|
-
* month's running count beside two weeks' does not read as the same kind of
|
|
88
|
-
* thing.
|
|
89
|
-
*/ function aiInsightDigestTiles(tables) {
|
|
90
|
-
return tables.flatMap((source)=>{
|
|
91
|
-
var _ref, _ref1;
|
|
92
|
-
var _pluginFigureReader, _summary_summarize;
|
|
93
|
-
const summary = (_pluginFigureReader = pluginFigureReader(source.reader)) == null ? void 0 : _pluginFigureReader.reader.weeklySummary;
|
|
94
|
-
const table = summary ? normalizePluginFigureTable(source) : null;
|
|
95
|
-
const stats = (table ? (_ref = summary == null ? void 0 : (_summary_summarize = summary.summarize(table)) == null ? void 0 : _summary_summarize.stats) != null ? _ref : [] : []).filter((stat)=>typeof stat.change === 'number');
|
|
96
|
-
return stats.length ? [
|
|
97
|
-
{
|
|
98
|
-
ref: source.ref,
|
|
99
|
-
stats,
|
|
100
|
-
order: (_ref1 = summary == null ? void 0 : summary.order) != null ? _ref1 : 0
|
|
101
|
-
}
|
|
102
|
-
] : [];
|
|
103
|
-
}).sort((a, b)=>a.order - b.order);
|
|
104
|
-
}
|
|
105
|
-
/** The row numbers a set of insights cite in a table, each once, in the order they cite them. */ function citedRows(insights, table) {
|
|
106
|
-
const rows = insights.flatMap((insight)=>insight.cites.filter((cite)=>cite.table === table.ref).flatMap((cite)=>cite.rows));
|
|
100
|
+
/** The rows an insight cites in a table, each once, in the order it cites them. */ function citedRows(insight, table) {
|
|
101
|
+
const rows = insight.cites.filter((cite)=>cite.table === table.ref).flatMap((cite)=>cite.rows);
|
|
107
102
|
return [
|
|
108
103
|
...new Set(rows)
|
|
109
104
|
].filter((row)=>Number.isInteger(row) && table.rows[row]);
|
|
110
105
|
}
|
|
111
106
|
/**
|
|
112
|
-
*
|
|
113
|
-
* tomorrow draws without a line here:
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*/ function
|
|
107
|
+
* The rows under an insight, from the table's own columns, so a reader added
|
|
108
|
+
* tomorrow draws without a line here: each with its change where the table
|
|
109
|
+
* has one, else with its second figure. A table of days, or one with no
|
|
110
|
+
* figures, draws nothing: the free email carries the week, this one the reading.
|
|
111
|
+
*/ function aiInsightDigestRows(table, cited, siteUrl) {
|
|
117
112
|
const label = table.columns.find((column)=>column.kind === 'text' || column.kind === 'date');
|
|
118
113
|
const figures = table.columns.filter((column)=>FIGURE_KINDS.includes(column.kind));
|
|
119
114
|
const change = table.columns.find((column)=>column.kind === 'change');
|
|
120
|
-
if (!label ||
|
|
115
|
+
if (!label || label.kind === 'date' || !figures.length) return [];
|
|
121
116
|
// A `figure` row names what it counts. Any other row's count takes its column's word.
|
|
122
117
|
const counted = label.key !== 'figure';
|
|
123
118
|
const text = (column, row)=>{
|
|
124
119
|
const cell = pluginFigureCellText(table, column.key, row[column.key]);
|
|
125
120
|
return counted && column.kind === 'count' ? `${cell} ${column.label.toLowerCase()}` : cell;
|
|
126
121
|
};
|
|
127
|
-
if (label.kind === 'date') {
|
|
128
|
-
const [figure] = figures;
|
|
129
|
-
const bars = table.rows.map((row, index)=>({
|
|
130
|
-
label: weeklySummaryWeekday(String(row[label.key])),
|
|
131
|
-
value: Number(row[figure.key]) || 0,
|
|
132
|
-
display: pluginFigureCellText(table, figure.key, row[figure.key]),
|
|
133
|
-
marked: cited.includes(index)
|
|
134
|
-
}));
|
|
135
|
-
return {
|
|
136
|
-
bars
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
122
|
const shown = figures.slice(0, change ? 1 : 2);
|
|
140
|
-
return {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
})
|
|
150
|
-
};
|
|
123
|
+
return cited.slice(0, AI_INSIGHT_DIGEST_MAX_ROWS).map((index)=>{
|
|
124
|
+
var _row_label_key;
|
|
125
|
+
const row = table.rows[index];
|
|
126
|
+
const moved = change ? row[change.key] : null;
|
|
127
|
+
return _extends({}, weeklySummaryRowLink(String((_row_label_key = row[label.key]) != null ? _row_label_key : ''), siteUrl), {
|
|
128
|
+
value: shown.map((column)=>text(column, row)).join(' · '),
|
|
129
|
+
change: typeof moved === 'number' ? moved : null
|
|
130
|
+
});
|
|
131
|
+
});
|
|
151
132
|
}
|
|
152
|
-
/** The
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
group.insights.push(insight);
|
|
163
|
-
groups.set(ref, group);
|
|
164
|
-
}
|
|
165
|
-
return [
|
|
166
|
-
...groups.values()
|
|
167
|
-
].map(({ table, insights: said })=>{
|
|
168
|
-
var _ref;
|
|
169
|
-
const url = table ? input.sourceUrl(table) : null;
|
|
133
|
+
/** The note's blocks: one an insight, in the order written, with what it rests on and where to act on it. */ function aiInsightDigestSections(insights, input) {
|
|
134
|
+
return insights.map((insight)=>{
|
|
135
|
+
var _insight_headline;
|
|
136
|
+
const cited = insight.cites.flatMap((cite)=>{
|
|
137
|
+
var _input_tables_find;
|
|
138
|
+
return (_input_tables_find = input.tables.find((table)=>table.ref === cite.table)) != null ? _input_tables_find : [];
|
|
139
|
+
});
|
|
140
|
+
const report = cited.find((table)=>input.sourceUrl(table));
|
|
141
|
+
const url = report ? input.sourceUrl(report) : null;
|
|
142
|
+
const rows = cited.map((table)=>aiInsightDigestRows(table, citedRows(insight, table), input.siteUrl)).find((list)=>list.length);
|
|
170
143
|
return _extends({
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
label: table.source.label,
|
|
174
|
-
url
|
|
175
|
-
} : null,
|
|
176
|
-
points: said.map((insight)=>{
|
|
177
|
-
var _insight_headline;
|
|
178
|
-
return {
|
|
144
|
+
points: [
|
|
145
|
+
{
|
|
179
146
|
headline: ((_insight_headline = insight.headline) == null ? void 0 : _insight_headline.trim()) || null,
|
|
180
|
-
text: weeklySummaryPlainDates(insight.text)
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
147
|
+
text: weeklySummaryPlainDates(insight.text),
|
|
148
|
+
why: insight.why ? weeklySummaryPlainDates(insight.why) : null,
|
|
149
|
+
next: insight.next ? weeklySummaryPlainDates(insight.next) : null,
|
|
150
|
+
nextLink: report && url ? {
|
|
151
|
+
label: report.source.label,
|
|
152
|
+
url
|
|
153
|
+
} : null
|
|
154
|
+
}
|
|
155
|
+
]
|
|
156
|
+
}, rows ? {
|
|
157
|
+
rows
|
|
158
|
+
} : {});
|
|
184
159
|
});
|
|
185
160
|
}
|
|
186
161
|
/**
|
|
187
|
-
* The
|
|
188
|
-
* and the small print.
|
|
189
|
-
*
|
|
190
|
-
*
|
|
162
|
+
* The note's drawn parts: the week in short, one block an insight, what the
|
|
163
|
+
* figures could not answer, and the small print. It carries no tiles and no
|
|
164
|
+
* chart: the free Weekly summary lists the figures, and this says what they
|
|
165
|
+
* meant, why they moved and what to do.
|
|
191
166
|
*/ export function aiInsightDigestEmailHtml(input) {
|
|
192
|
-
const tiles = aiInsightDigestTiles(input.tables);
|
|
193
|
-
const restated = (insight)=>insight.cites.length > 0 && insight.cites.every((cite)=>{
|
|
194
|
-
var _tiles_;
|
|
195
|
-
return cite.table === ((_tiles_ = tiles[0]) == null ? void 0 : _tiles_.ref);
|
|
196
|
-
});
|
|
197
|
-
const fresh = input.insights.filter((insight)=>!restated(insight));
|
|
198
167
|
return {
|
|
199
|
-
'digest.html':
|
|
168
|
+
'digest.html': (input.overview ? weeklySummaryLeadHtml('The week in short', weeklySummaryPlainDates(input.overview), input.colors) : '') + weeklySummarySectionsHtml(aiInsightDigestSections(input.insights, input), input.colors) + (input.gap ? weeklySummaryNoteHtml(input.gap, input.colors) : ''),
|
|
200
169
|
'digest.footnote': weeklySummaryFootnoteHtml(input.why, input.settingsUrl ? {
|
|
201
170
|
label: 'Turn off weekly insights',
|
|
202
171
|
url: input.settingsUrl
|
|
@@ -222,7 +191,7 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
222
191
|
'digest.intro': `What ${input.siteName}'s figures showed ${input.periodLabel ? 'last week' : 'this week'}. ` + 'Each one is traced to the figures it cites, so you can check it on the Analytics page.',
|
|
223
192
|
'digest.insights': input.insights.map((insight, index)=>`${index + 1}. ${aiInsightDigestLine(insight)}`).join('\n\n'),
|
|
224
193
|
'digest.analyticsUrl': (_input_analyticsUrl = input.analyticsUrl) != null ? _input_analyticsUrl : '',
|
|
225
|
-
'digest.why': `Every number here is checked against ${input.siteName}'s own figures.${spent}`
|
|
194
|
+
'digest.why': `Every number here is checked against ${input.siteName}'s own figures. The reasons and suggestions are the AI's reading of them.${spent}`
|
|
226
195
|
};
|
|
227
196
|
}
|
|
228
197
|
async function readUsers(firestore, uids) {
|
|
@@ -251,10 +220,13 @@ async function readUsers(firestore, uids) {
|
|
|
251
220
|
}).sort((a, b)=>a.$id.localeCompare(b.$id));
|
|
252
221
|
if (!subscribers.length) return 0;
|
|
253
222
|
const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).limit(AI_INSIGHT_DIGEST_HOST_READ_LIMIT).get();
|
|
254
|
-
const
|
|
223
|
+
const { from } = weeklySummaryPeriod(now);
|
|
224
|
+
const dayIds = Array.from({
|
|
225
|
+
length: AI_INSIGHT_DIGEST_DAYS
|
|
226
|
+
}, (_, index)=>pluginFigureDay(new Date(Date.parse(`${from}T00:00:00Z`) + index * 86400000)));
|
|
255
227
|
const candidates = [];
|
|
256
228
|
for (const host of hosts.docs){
|
|
257
|
-
var _host_data
|
|
229
|
+
var _host_data;
|
|
258
230
|
const data = (_host_data = host.data()) != null ? _host_data : {};
|
|
259
231
|
if (!isAiOnForSite(org, data)) continue;
|
|
260
232
|
let creator = null;
|
|
@@ -265,18 +237,29 @@ async function readUsers(firestore, uids) {
|
|
|
265
237
|
}
|
|
266
238
|
}
|
|
267
239
|
if (!creator) continue;
|
|
268
|
-
const
|
|
240
|
+
const days = await firestore.getAll(...dayIds.map((day)=>host.ref.collection('analytics').doc(day)));
|
|
269
241
|
candidates.push({
|
|
270
242
|
hostId: host.id,
|
|
271
243
|
name: str(data['displayName']) || str(data['name']) || str(data['subdomain']) || host.id,
|
|
272
244
|
creator,
|
|
273
|
-
views:
|
|
245
|
+
views: days.reduce((sum, day)=>{
|
|
246
|
+
var _day_get;
|
|
247
|
+
return sum + (Number((_day_get = day.get('total')) != null ? _day_get : 0) || 0);
|
|
248
|
+
}, 0)
|
|
274
249
|
});
|
|
275
250
|
}
|
|
276
251
|
const chosen = candidates.sort((a, b)=>b.views - a.views || a.hostId.localeCompare(b.hostId)).slice(0, AI_INSIGHT_DIGEST_MAX_SITES);
|
|
277
252
|
if (!chosen.length) return 0;
|
|
278
253
|
const sites = {};
|
|
254
|
+
const active = chosen.filter((site)=>site.views >= AI_INSIGHT_DIGEST_MIN_VIEWS);
|
|
279
255
|
for (const site of chosen){
|
|
256
|
+
if (site.views < AI_INSIGHT_DIGEST_MIN_VIEWS) sites[site.hostId] = {
|
|
257
|
+
jobId: '',
|
|
258
|
+
name: site.name,
|
|
259
|
+
state: 'quiet'
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
for (const site of active){
|
|
280
263
|
const job = await createAiJob(firestore, {
|
|
281
264
|
orgId,
|
|
282
265
|
hostId: site.hostId,
|
|
@@ -295,12 +278,15 @@ async function readUsers(firestore, uids) {
|
|
|
295
278
|
state: 'pending'
|
|
296
279
|
};
|
|
297
280
|
}
|
|
281
|
+
// Stamped even when every site was quiet, so the next run of the week does
|
|
282
|
+
// not read them all again, and a quiet site is on record as quiet.
|
|
298
283
|
const marker = {
|
|
299
284
|
week,
|
|
300
285
|
createdAtMs: now.getTime(),
|
|
301
286
|
sites
|
|
302
287
|
};
|
|
303
288
|
await markerRef.set(marker);
|
|
289
|
+
if (!active.length) return 0;
|
|
304
290
|
await firestore.collection(AI_INSIGHT_DIGEST_QUEUE).doc(week).set({
|
|
305
291
|
week,
|
|
306
292
|
pending: {
|
|
@@ -309,7 +295,7 @@ async function readUsers(firestore, uids) {
|
|
|
309
295
|
}, {
|
|
310
296
|
merge: true
|
|
311
297
|
});
|
|
312
|
-
return
|
|
298
|
+
return active.length;
|
|
313
299
|
}
|
|
314
300
|
/** Delivers or settles one workspace's digests for a week; `deferred` when the send rate refused. */ async function deliverOrgDigest(deps, orgId, week, overBudget) {
|
|
315
301
|
var _data, _marker_sites;
|
|
@@ -391,10 +377,11 @@ async function readUsers(firestore, uids) {
|
|
|
391
377
|
}
|
|
392
378
|
const address = str((_member_email = member.email) != null ? _member_email : user == null ? void 0 : user.get('email')).toLowerCase();
|
|
393
379
|
if (address.includes('@')) {
|
|
394
|
-
var _liveCustomDomain, _record_tables;
|
|
380
|
+
var _record_overview, _liveCustomDomain, _record_overview1, _record_tables, _record_gap;
|
|
395
381
|
const emailInput = {
|
|
396
382
|
siteName: site.name,
|
|
397
383
|
productName: branding.productName,
|
|
384
|
+
overview: (_record_overview = record.overview) != null ? _record_overview : null,
|
|
398
385
|
insights: record.insights,
|
|
399
386
|
analyticsUrl,
|
|
400
387
|
settingsUrl: origin ? `${origin}/manage/notifications` : null,
|
|
@@ -412,8 +399,10 @@ async function readUsers(firestore, uids) {
|
|
|
412
399
|
siteName: site.name,
|
|
413
400
|
org,
|
|
414
401
|
merge: _extends({}, parts, aiInsightDigestEmailHtml({
|
|
402
|
+
overview: (_record_overview1 = record.overview) != null ? _record_overview1 : null,
|
|
415
403
|
insights: record.insights,
|
|
416
404
|
tables: (_record_tables = record.tables) != null ? _record_tables : [],
|
|
405
|
+
gap: (_record_gap = record.gap) != null ? _record_gap : null,
|
|
417
406
|
colors: deps.colors(org),
|
|
418
407
|
siteUrl: domain ? `https://${domain}` : null,
|
|
419
408
|
sourceUrl: (table)=>{
|
|
@@ -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 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,6CAA4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 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 weeklySummaryLeadHtml,\n weeklySummaryNoteHtml,\n weeklySummaryPeriod,\n weeklySummaryPlainDates,\n weeklySummaryRowLink,\n weeklySummarySectionsHtml,\n type WeeklySummaryColors,\n type WeeklySummarySection,\n type WeeklySummarySectionRow,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\nimport { pluginFigureCellText, pluginFigureDay, type PluginFigureColumn } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_DIGEST_DAYS,\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 AI's reading of the week, then a block for each insight with what\n * most likely drove it, one thing to do next and the rows it rests on. The free\n * Weekly summary lists the figures; this says what they meant (AGL-4131). Every\n * reader draws the same way, from its table's own columns. It is sent by the\n * platform to a person who asked for it, 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/**\n * The page views a week needs to be worth explaining. Under this, a reading\n * rests on a handful of visits and would spend credits saying nothing, so the\n * site gets no job and the free Weekly summary stands alone.\n */\nexport const AI_INSIGHT_DIGEST_MIN_VIEWS = 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\n/** `quiet`: too little traffic to explain, so no job was made and no credits were drawn. */\nexport type AiInsightDigestSiteState = 'pending' | 'delivered' | 'skipped' | 'quiet'\n\nexport interface AiInsightDigestSite {\n /** `''` for a quiet site, which has no job. */\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 /** The AI's read of the week, when it wrote one. */\n overview?: string | null\n insights: ReadonlyArray<Pick<AiInsight, 'text' | 'headline' | 'why' | 'next'>>\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.overview ? [`The week in short: ${weeklySummaryPlainDates(input.overview)}`, ''] : []),\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 plain text, its dates as a person says them, its reason and next step on their own lines. */\nfunction aiInsightDigestLine(insight: Pick<AiInsight, 'text' | 'headline' | 'why' | 'next'>): string {\n const text = weeklySummaryPlainDates(insight.text)\n return [\n insight.headline ? `${insight.headline}: ${text}` : text,\n ...(insight.why ? [`Likely why: ${weeklySummaryPlainDates(insight.why)}`] : []),\n ...(insight.next ? [`Try this: ${weeklySummaryPlainDates(insight.next)}`] : []),\n ].join('\\n')\n}\n\n/** The most rows an insight lists under it: support for what it says, not a report. */\nexport const AI_INSIGHT_DIGEST_MAX_ROWS = 3\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/** The rows an insight cites in a table, each once, in the order it cites them. */\nfunction citedRows(insight: AiInsight, table: AiInsightTable): number[] {\n const rows = insight.cites.filter((cite) => cite.table === table.ref).flatMap((cite) => cite.rows)\n return [...new Set(rows)].filter((row) => Number.isInteger(row) && table.rows[row])\n}\n\n/**\n * The rows under an insight, from the table's own columns, so a reader added\n * tomorrow draws without a line here: each with its change where the table\n * has one, else with its second figure. A table of days, or one with no\n * figures, draws nothing: the free email carries the week, this one the reading.\n */\nfunction aiInsightDigestRows(\n table: AiInsightTable,\n cited: readonly number[],\n siteUrl: string | null,\n): WeeklySummarySectionRow[] {\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 || label.kind === 'date' || !figures.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 const shown = figures.slice(0, change ? 1 : 2)\n return 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/** The note's blocks: one an insight, in the order written, with what it rests on and where to act on it. */\nfunction aiInsightDigestSections(\n insights: readonly AiInsight[],\n input: { tables: readonly AiInsightTable[]; siteUrl: string | null; sourceUrl: (table: AiInsightTable) => string | null },\n): WeeklySummarySection[] {\n return insights.map((insight) => {\n const cited = insight.cites.flatMap((cite) => input.tables.find((table) => table.ref === cite.table) ?? [])\n const report = cited.find((table) => input.sourceUrl(table))\n const url = report ? input.sourceUrl(report) : null\n const rows = cited.map((table) => aiInsightDigestRows(table, citedRows(insight, table), input.siteUrl)).find((list) => list.length)\n return {\n points: [\n {\n headline: insight.headline?.trim() || null,\n text: weeklySummaryPlainDates(insight.text),\n why: insight.why ? weeklySummaryPlainDates(insight.why) : null,\n next: insight.next ? weeklySummaryPlainDates(insight.next) : null,\n nextLink: report && url ? { label: report.source.label, url } : null,\n },\n ],\n ...(rows ? { rows } : {}),\n }\n })\n}\n\n/**\n * The note's drawn parts: the week in short, one block an insight, what the\n * figures could not answer, and the small print. It carries no tiles and no\n * chart: the free Weekly summary lists the figures, and this says what they\n * meant, why they moved and what to do.\n */\nexport function aiInsightDigestEmailHtml(input: {\n /** The AI's read of the week; absent on an answer from before it was asked for. */\n overview?: string | null\n insights: readonly AiInsight[]\n tables: readonly AiInsightTable[]\n /** What the figures could not answer. */\n gap?: string | null\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 return {\n 'digest.html':\n (input.overview ? weeklySummaryLeadHtml('The week in short', weeklySummaryPlainDates(input.overview), input.colors) : '') +\n weeklySummarySectionsHtml(aiInsightDigestSections(input.insights, input), input.colors) +\n (input.gap ? weeklySummaryNoteHtml(input.gap, 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. The reasons and suggestions are the AI's reading of them.${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 { from } = weeklySummaryPeriod(now)\n const dayIds = Array.from({ length: AI_INSIGHT_DIGEST_DAYS }, (_, index) =>\n pluginFigureDay(new Date(Date.parse(`${from}T00:00:00Z`) + index * 86_400_000)),\n )\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 days = await firestore.getAll(...dayIds.map((day) => host.ref.collection('analytics').doc(day)))\n candidates.push({\n hostId: host.id,\n name: str(data['displayName']) || str(data['name']) || str(data['subdomain']) || host.id,\n creator,\n views: days.reduce((sum, day) => sum + (Number(day.get('total') ?? 0) || 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 const active = chosen.filter((site) => site.views >= AI_INSIGHT_DIGEST_MIN_VIEWS)\n for (const site of chosen) {\n if (site.views < AI_INSIGHT_DIGEST_MIN_VIEWS) sites[site.hostId] = { jobId: '', name: site.name, state: 'quiet' }\n }\n for (const site of active) {\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 // Stamped even when every site was quiet, so the next run of the week does\n // not read them all again, and a quiet site is on record as quiet.\n const marker: AiInsightDigestMarker = { week, createdAtMs: now.getTime(), sites }\n await markerRef.set(marker)\n if (!active.length) return 0\n await firestore\n .collection(AI_INSIGHT_DIGEST_QUEUE)\n .doc(week)\n .set({ week, pending: { [orgId]: true } }, { merge: true })\n return active.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 overview: record.overview ?? null,\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 overview: record.overview ?? null,\n insights: record.insights,\n tables: record.tables ?? [],\n gap: record.gap ?? null,\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","weeklySummaryLeadHtml","weeklySummaryNoteHtml","weeklySummaryPeriod","weeklySummaryPlainDates","weeklySummaryRowLink","weeklySummarySectionsHtml","pluginFigureCellText","pluginFigureDay","AI_INSIGHT_DIGEST_DAYS","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_MIN_VIEWS","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","overview","insights","map","insight","index","aiInsightDigestLine","analyticsUrl","productName","settingsUrl","join","text","headline","why","next","AI_INSIGHT_DIGEST_MAX_ROWS","FIGURE_KINDS","citedRows","table","rows","cites","filter","cite","ref","flatMap","Set","row","isInteger","aiInsightDigestRows","cited","siteUrl","label","columns","find","column","kind","figures","includes","change","length","counted","key","cell","toLowerCase","shown","slice","moved","String","aiInsightDigestSections","tables","report","sourceUrl","url","list","points","nextLink","source","aiInsightDigestEmailHtml","colors","gap","aiInsightDigestEmailParts","spent","Boolean","readUsers","firestore","uids","Map","docs","getAll","uid","collection","doc","id","createOrgDigest","deps","orgDoc","week","orgId","org","data","flagOn","flagValue","paused","markerRef","get","exists","members","listMembers","member","orgSuspended","users","$id","sort","subscribers","a","b","localeCompare","hosts","where","limit","from","dayIds","Array","_","parse","candidates","host","creator","mayGenerate","days","day","push","hostId","name","views","reduce","sum","chosen","sites","active","site","jobId","state","job","brief","inputs","surface","through","to","createdBy","marker","createdAtMs","set","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","title","body","link","runAiInsightDigestSweep","options","orgs","startedAtMs","budgetMs","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,qBAAqB,EACrBC,qBAAqB,EACrBC,mBAAmB,EACnBC,uBAAuB,EACvBC,oBAAoB,EACpBC,yBAAyB,QAIpB,wCAAuC;AAC9C,SAASC,oBAAoB,EAAEC,eAAe,QAAiC,6CAA4C;AAC3H,SACEC,sBAAsB,EACtBC,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,O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