@zeruxjs/reports 0.0.0-stage → 0.0.1

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/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,9 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 ZeruxJS.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # @zeruxjs/reports — authenticated report studio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A structured report/page/chart designer over **internal @zeruxjs/analytics events**. Routes: `/_reports` (studio), `/_reports/api` (versioned definition CRUD), `/_reports/query` (chart data). All routes require the host application's `authorize(request)` callback; missing auth disables the service.
4
+
5
+ ```ts
6
+ export default {
7
+ analytics: {analytics:'reporting',enabled:true},
8
+ reports: {
9
+ enabled:true,
10
+ prefix:'/_reports',
11
+ dashboardHost:'reports.example.com', // optional; proxy this domain to Zerux
12
+ authorize: async request => await sessionHasRole(request,'reports_editor')
13
+ }
14
+ }
15
+ ```
16
+
17
+ Reports contain pages; pages contain charts. Chart types: `bar`, `horizontal-bar`, `line`, `area`, `pie`, `doughnut`, `scatter`, `stacked-bar`, `table`, and `kpi`. Grouping supports event name, UTC day, source, site, pathname, or `property:<name>`; metrics include count, sum, average, minimum, maximum, distinct. Data is only internal analytics, never arbitrary SQL or JavaScript. The studio has page/chart controls and an advanced JSON editor; data and layouts are escaped in the browser and pages are not exposed anonymously. PUT requires same-origin request and optimistic versioning. Host access control decides which users may read, publish or both.
18
+
19
+ **Important scope:** The built-in `analytics.events()` connector currently returns **at most 500 source rows**; charts report `sampledRows` and `truncated` when hitting their limit. Those charts must not be represented as global totals. For production-scale reporting, supply `source.events()` backed by your analytics warehouse/materialized aggregation, or extend the core analytics query layer with DB-native aggregate queries. The report document store is persisted in `analytics_report_documents` when the analytics connection implements conditional update and affectedCount; memory-only mode is for development. Cross-replica changes need a shared DB or atomic `store` adapter. Charts currently render client-side using Canvas (table/KPI use DOM) with a single value series; more advanced multi-series, sharing, scheduled exports and rich data-source connectors are future capabilities.
20
+
21
+ Admin sessions must be protected by your own secure cookies/session middleware; this package intentionally provides no default password, OAuth identity provider or anonymous editor. Never put raw analytics database credentials in a chart definition.
22
+
23
+ ## Section 48: Exact native count aggregates
24
+
25
+ For `metric:'count'` grouped by `event`, `source`, `site`, or `pathname`, Reports automatically calls the optional `source.aggregate()` / `analytics.aggregate()` endpoint rather than loading only 500 raw events. UTC `day` grouping also uses exact native counts when the chart specifies both `since` and `until` within a 366-day range. The backend returns exact `total` and bounded chart groups; the dashboard marks hidden groups distinctly from sampled events. Other metrics and `property:` dimensions still use the bounded sample fallback with explicit `queryMode:'sampled'`. A custom AnalyticsReportSource may implement `aggregate(query)` to cover other backends.
26
+
27
+ `ReportsOptions.site` and ZeruxJS `reports.site` enforce an application-selected site filter that chart authors cannot override. Supply site from your authenticated tenant context, *not* a user-supplied query string. Protect reports with application auth and tenant authorization.
28
+
29
+ ## Section 49: Indexed numerical metrics
30
+
31
+ When `@zeruxjs/analytics` is configured with `numericFields:['value',...]` and a chart uses `metric:'sum'|'average'|'min'|'max'` with a matching `valueField`, Reports uses `analytics.aggregateNumeric()` on the DB-backed numeric fact table for supported built-in dimensions. Report responses include `queryMode:'materialized'`, `matchedFacts`, and `numericCoverage:'indexed-only'`. **The dashboard always warns** that historical/failed numeric facts may be absent. Other fields retain the 500-row sampled fallback. These are not guaranteed complete historical or transactionally consistent financial totals; see `SECTION_49_MATERIALIZED_NUMERIC_ANALYTICS.md`.
32
+
33
+ ## Section 73: saved dashboards, scoped exports and campaign views
34
+
35
+ The studio now includes optional **UTC date-range filtering** (without mutating the saved chart), read-only CSV/JSON export and an opt-in marketing campaign panel. The package also exposes a paginated report catalog and separates viewer, editor, export, sensitive-property and campaign permissions. Each exporter must be explicitly authorized by the host session. Saved report documents continue to use a versioned CAS store; a report shown to a viewer is always freshly queried, not an immutable historical snapshot.
36
+
37
+ ### Single-tenant reporting configuration
38
+
39
+ ```ts
40
+ const reports = createReports({
41
+ analytics,
42
+ store: analytics.createDocumentStore('analytics_report_documents','shop',{version:1,reports:[]}),
43
+ site:'shop',
44
+ authorize: async (request,action,resourceId) => {
45
+ const session = await getSession(request); // implement in the host application
46
+ if (!session?.sites?.includes('shop')) return false;
47
+ if (action==='edit') return session.roles.includes('reports_editor');
48
+ if (action==='export') return session.roles.includes('reports_exporter');
49
+ if (action==='sensitive') return session.roles.includes('reports_sensitive_reader');
50
+ if (action==='campaign') return session.roles.includes('campaign_reporting');
51
+ return session.roles.includes('reports_reader');
52
+ }
53
+ });
54
+ ```
55
+
56
+ **Tenant scope must come from trusted application authorization**, never from a `?site=` query parameter. For multi-tenant hosts, supply `resolveScope(request)` returning `{site,store,source?}` where the store is **dedicated to that verified tenant**. In this mode, the direct `reports.query()` function is disabled because it lacks a request identity; use the authenticated HTTP routes instead. A single global store with only `site`-based query filtering is **not** enough to isolate saved reports between tenants. Per-report sharing/invites are not implemented; share viewer access only through host-managed tenant roles or separate approved tenant scopes. Do not expose a multi-tenant report studio with blanket `authorize:()=>true`.
57
+
58
+ ### HTTP endpoints
59
+
60
+ - `GET /_reports` — authenticated studio; static CSP hashes (no unsafe-inline).
61
+ - `GET /_reports/api` — versioned report definition document; `PUT /_reports/api` — editor-only same-origin JSON write (256 KiB cap) with CAS conflict `409`.
62
+ - `GET /_reports/catalog?limit=20&cursor=version:offset` — stable, bounded 1–50 report metadata page; stale version cursor returns `409`.
63
+ - `GET /_reports/query?report=...&page=...&chart=...&since=...&until=...` — role-checked one-chart request; both optional epoch-millisecond UTC times must be present and span no more than 366 days. The request filter overrides **only that query**, not the saved chart definition.
64
+ - `GET /_reports/export?report=...&page=...&format=json|csv[&chart=...]` — separate export permission; a `property:` dimension additionally requires `sensitive` permission. CSV formula cells are escaped as text, exports are capped at 256 KiB, 12 charts and a 500-unit estimated database query budget. JSON contains each chart's `queryMode`, `truncated`, `coverage` and numeric-fact coverage where relevant.
65
+ - `GET /_reports/campaign?code=...&kind=delivery|performance|daily|activity[&from=YYYY-MM-DD&to=YYYY-MM-DD]` — requires independent `campaign` permission **and** an opt-in `campaigns` adapter. `delivery` supports an encoded `cursor` and 1–200 records per page; `daily` and `activity` require a bounded UTC date window. Missing report providers return `404`, not fictional zero counts.
66
+
67
+ The optional `campaigns` adapter has `report(code,{cursor,limit,site})` and optional `performance(code,site)`, `dailyTrends(code,from,to,site)` and `activity(code,from,to,site)` methods. Use the existing `@zeruxjs/email` marketing `report` method for the delivery-page callback; wrap it with your own authorization and tenant checks. The others should return the documented reports/campaign snapshot types. **Reports never makes itself a source of truth for SMTP or provider notifications.** Campaign delivery bars distinguish `smtpAccepted` (transport accepted, not inbox confirmed), provider events are **reported notifications, not unique deliveries**, and activity bars report **observed tracking events**, not unique users. Archived campaigns can be queried only as long as the underlying authorized archive/reporting data is retained. Consent and tracking setup remain independent.
68
+
69
+ ### Query provenance and scale
70
+
71
+ Native COUNT on supported columns is exact for persisted matching events; supported indexed numeric metrics cover **only materialized numeric facts**, not necessarily historical rows that missed indexing. Unsupported dimensions and metrics query **up to 500 raw rows** and are labeled bounded samples; a sampled average uses only valid numeric values. Non-native samples cannot be interpreted as all-time totals. Date grouping is limited to 366 days, while the multi-chart export has a stricter overall query budget. Per-report export is built from individual chart queries and is **not a transactionally consistent multi-query snapshot**. Explicit external rate limits, host authentication/CSRF-session hardening, database migrations, real-engine parity tests, and a production egress perimeter remain deployer responsibilities.
72
+
73
+ After building the DB/Analytics/Reports packages, run `node --test tests/integration/reports-sqlite.test.mjs`. This covers two SQLite connections, tenant report-document isolation, exact counts above the raw sampling cap, and optimistic-CAS conflicts. Real PostgreSQL/MySQL/MongoDB concurrency, long-running load and the clean npm registry installation are not certified by this test.
@@ -0,0 +1,89 @@
1
+ import type { ChartData } from './types.js';
2
+ /** Minimal, PII-free interface produced by @zeruxjs/queue's campaign reporter. */
3
+ export interface CampaignDeliverySnapshot {
4
+ campaignId: string;
5
+ complete: boolean;
6
+ scanned: number;
7
+ counts: Record<'pending' | 'claimed' | 'sending' | 'sent' | 'suppressed' | 'uncertain' | 'rejected', number>;
8
+ days: Array<{
9
+ day: string;
10
+ sent: number;
11
+ suppressed: number;
12
+ uncertain: number;
13
+ other: number;
14
+ }>;
15
+ }
16
+ /**
17
+ * Project durable delivery statuses into existing Reports chart data.
18
+ * Never confuse SMTP sent state with inbox delivery, or an incomplete scan with a total.
19
+ * Requires application-level tenant authorization before obtaining a snapshot.
20
+ */
21
+ export declare function campaignDeliveryCharts(report: CampaignDeliverySnapshot): {
22
+ statuses: ChartData;
23
+ sentByDay: ChartData;
24
+ };
25
+ /** Exact SQL/Mongo grouped state totals. Provider outcomes are event counts only. */
26
+ export interface CampaignPerformanceSnapshot {
27
+ campaignId: string;
28
+ mode: 'database';
29
+ complete: true;
30
+ total: number;
31
+ counts: CampaignDeliverySnapshot['counts'];
32
+ dailyCoverage: 'not-computed';
33
+ activityCoverage: 'not-computed';
34
+ smtpAcceptedPercent: number | null;
35
+ provider: null | {
36
+ events: number;
37
+ coverage: 'reported-events-only';
38
+ counts: Record<'delivered' | 'deferred' | 'hard-bounce' | 'soft-bounce' | 'complaint', number>;
39
+ };
40
+ }
41
+ /** No false timeline or engagement graphs are fabricated from unavailable source data. */
42
+ export declare function campaignPerformanceCharts(report: CampaignPerformanceSnapshot): {
43
+ statuses: ChartData;
44
+ providerOutcomes: ChartData | null;
45
+ };
46
+ /** Database-native daily trends. Counts reflect the last durable state update,
47
+ * not an immutable event log or inbox delivery. Provider results are notifications,
48
+ * which can include multiple events for a single message. */
49
+ export interface CampaignDailyTrendsSnapshot {
50
+ campaignId: string;
51
+ from: string;
52
+ to: string;
53
+ mode: 'database';
54
+ complete: true;
55
+ deliveryCoverage: 'last-state-update-day';
56
+ providerCoverage: 'reported-events-only' | 'not-configured';
57
+ snapshotConsistent: false;
58
+ total: number;
59
+ providerEvents: number | null;
60
+ days: Array<{
61
+ day: string;
62
+ counts: CampaignDeliverySnapshot['counts'];
63
+ total: number;
64
+ provider: Record<'delivered' | 'deferred' | 'hard-bounce' | 'soft-bounce' | 'complaint', number> | null;
65
+ providerEvents: number | null;
66
+ }>;
67
+ }
68
+ export declare function campaignDailyTrendsCharts(report: CampaignDailyTrendsSnapshot): {
69
+ smtpSentByDay: ChartData;
70
+ providerDeliveredByDay: ChartData | null;
71
+ };
72
+ /** Section 60 immutable transition history (as observed and journaled).
73
+ * Counts are transitions into a state, not current delivery states or unique recipients. */
74
+ export interface CampaignTransitionHistorySnapshot {
75
+ campaignId: string;
76
+ from: string;
77
+ to: string;
78
+ coverage: 'recorded-transitions-only';
79
+ snapshotConsistent: false;
80
+ days: Array<{
81
+ day: string;
82
+ counts: CampaignDeliverySnapshot['counts'];
83
+ total: number;
84
+ }>;
85
+ }
86
+ export declare function campaignTransitionHistoryCharts(report: CampaignTransitionHistorySnapshot): {
87
+ sentTransitions: ChartData;
88
+ uncertainTransitions: ChartData;
89
+ };
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Project durable delivery statuses into existing Reports chart data.
3
+ * Never confuse SMTP sent state with inbox delivery, or an incomplete scan with a total.
4
+ * Requires application-level tenant authorization before obtaining a snapshot.
5
+ */
6
+ export function campaignDeliveryCharts(report) {
7
+ const labels = ['pending', 'claimed', 'sending', 'sent', 'suppressed', 'uncertain', 'rejected'];
8
+ if (!report || !Number.isSafeInteger(report.scanned) || report.scanned < 0 || typeof report.complete !== 'boolean' ||
9
+ labels.some(key => !Number.isSafeInteger(report.counts?.[key]) || report.counts[key] < 0) ||
10
+ labels.reduce((total, key) => total + report.counts[key], 0) !== report.scanned || !Array.isArray(report.days) || report.days.length > 5000)
11
+ throw new TypeError('Invalid campaign snapshot');
12
+ const ordered = [...report.days].sort((a, b) => a.day.localeCompare(b.day));
13
+ if (ordered.some((d, i) => !/^\d{4}-\d{2}-\d{2}$/.test(d.day) ||
14
+ (i > 0 && d.day === ordered[i - 1].day) || !['sent', 'suppressed', 'uncertain', 'other'].every(key => Number.isSafeInteger(d[key]) && Number(d[key]) >= 0)))
15
+ throw new TypeError('Invalid delivery timeline');
16
+ if (ordered.reduce((sum, d) => sum + d.sent + d.suppressed + d.uncertain + d.other, 0) !== report.scanned)
17
+ throw new TypeError('Delivery report timeline mismatch');
18
+ const shared = { sampledRows: report.scanned, truncated: !report.complete };
19
+ return {
20
+ statuses: { ...shared, id: 'campaign_delivery_status', title: 'Durable SMTP delivery states', type: 'bar', labels: [...labels], values: labels.map(key => report.counts[key]), total: report.scanned },
21
+ sentByDay: { ...shared, id: 'campaign_sent_by_day', title: 'SMTP accepted by UTC day', type: 'line', labels: ordered.map(d => d.day), values: ordered.map(d => d.sent), total: report.counts.sent }
22
+ };
23
+ }
24
+ /** No false timeline or engagement graphs are fabricated from unavailable source data. */
25
+ export function campaignPerformanceCharts(report) {
26
+ const labels = ['pending', 'claimed', 'sending', 'sent', 'suppressed', 'uncertain', 'rejected'];
27
+ if (!report || report.mode !== 'database' || report.complete !== true || report.dailyCoverage !== 'not-computed' || report.activityCoverage !== 'not-computed' ||
28
+ !Number.isSafeInteger(report.total) || report.total < 0 || labels.some(label => !Number.isSafeInteger(report.counts?.[label]) || report.counts[label] < 0) ||
29
+ labels.reduce((sum, k) => sum + report.counts[k], 0) !== report.total ||
30
+ (report.smtpAcceptedPercent !== null && (!Number.isFinite(report.smtpAcceptedPercent) || report.smtpAcceptedPercent < 0 || report.smtpAcceptedPercent > 100)))
31
+ throw new TypeError('Invalid native campaign performance');
32
+ const statuses = { id: 'campaign_all_time_statuses', title: 'All-time durable SMTP delivery states', type: 'bar',
33
+ labels: [...labels], values: labels.map(label => report.counts[label]), total: report.total, sampledRows: report.total, truncated: false, queryMode: 'database' };
34
+ if (report.provider === null)
35
+ return { statuses, providerOutcomes: null };
36
+ const providerLabels = ['delivered', 'deferred', 'hard-bounce', 'soft-bounce', 'complaint'];
37
+ const provider = report.provider;
38
+ if (provider.coverage !== 'reported-events-only' || !Number.isSafeInteger(provider.events) || provider.events < 0 ||
39
+ providerLabels.some(label => !Number.isSafeInteger(provider.counts?.[label]) || provider.counts[label] < 0) ||
40
+ providerLabels.reduce((sum, k) => sum + provider.counts[k], 0) !== provider.events)
41
+ throw new TypeError('Invalid provider event summary');
42
+ return { statuses, providerOutcomes: { id: 'campaign_provider_reported', title: 'Authenticated provider notifications (reported events only)', type: 'bar',
43
+ labels: [...providerLabels], values: providerLabels.map(label => provider.counts[label]), total: provider.events,
44
+ sampledRows: provider.events, truncated: false, queryMode: 'database' } };
45
+ }
46
+ export function campaignDailyTrendsCharts(report) {
47
+ if (!report || report.mode !== 'database' || report.complete !== true || report.snapshotConsistent !== false ||
48
+ report.deliveryCoverage !== 'last-state-update-day' || !['reported-events-only', 'not-configured'].includes(report.providerCoverage) ||
49
+ !/^\d{4}-\d\d-\d\d$/.test(report.from) || !/^\d{4}-\d\d-\d\d$/.test(report.to) ||
50
+ !Array.isArray(report.days) || report.days.length > 366 || !Number.isSafeInteger(report.total) || report.total < 0)
51
+ throw new TypeError('Invalid campaign daily trends');
52
+ const states = ['pending', 'claimed', 'sending', 'sent', 'suppressed', 'uncertain', 'rejected'];
53
+ const kinds = ['delivered', 'deferred', 'hard-bounce', 'soft-bounce', 'complaint'];
54
+ const sum = (values) => values.reduce((n, v) => n + v, 0);
55
+ let previous = '';
56
+ for (const day of report.days) {
57
+ if (!day || !/^\d{4}-\d\d-\d\d$/.test(day.day) || day.day <= previous || day.day < report.from || day.day > report.to ||
58
+ !Number.isSafeInteger(day.total) || day.total < 0 || states.some(key => !Number.isSafeInteger(day.counts?.[key]) || day.counts[key] < 0) ||
59
+ sum(states.map(k => day.counts[k])) !== day.total)
60
+ throw new TypeError('Invalid campaign daily state counts');
61
+ previous = day.day;
62
+ if (report.providerCoverage === 'reported-events-only') {
63
+ if (!day.provider || kinds.some(k => !Number.isSafeInteger(day.provider?.[k]) || day.provider[k] < 0) ||
64
+ !Number.isSafeInteger(day.providerEvents) || sum(kinds.map(k => day.provider[k])) !== day.providerEvents)
65
+ throw new TypeError('Invalid daily provider notifications');
66
+ }
67
+ else if (day.provider !== null || day.providerEvents !== null)
68
+ throw new TypeError('Unexpected provider trend data');
69
+ }
70
+ if (sum(report.days.map(d => d.total)) !== report.total ||
71
+ (report.providerCoverage === 'reported-events-only' ? sum(report.days.map(d => d.providerEvents)) !== report.providerEvents : report.providerEvents !== null))
72
+ throw new TypeError('Inconsistent daily campaign trend totals');
73
+ const common = { labels: report.days.map(d => d.day), truncated: false, queryMode: 'database' };
74
+ const smtpSentByDay = { ...common, id: 'campaign_daily_last_update_sent', title: 'Current SMTP-sent state by last update UTC day', type: 'line',
75
+ values: report.days.map(d => d.counts.sent), total: sum(report.days.map(d => d.counts.sent)), sampledRows: report.total };
76
+ const providerDeliveredByDay = report.providerCoverage === 'reported-events-only' ? {
77
+ ...common, id: 'campaign_daily_provider_delivered', title: 'Provider-reported delivery notifications by UTC day', type: 'line',
78
+ values: report.days.map(d => d.provider.delivered), total: sum(report.days.map(d => d.provider.delivered)), sampledRows: report.providerEvents
79
+ } : null;
80
+ return { smtpSentByDay, providerDeliveredByDay };
81
+ }
82
+ export function campaignTransitionHistoryCharts(report) {
83
+ if (!report || report.coverage !== 'recorded-transitions-only' || report.snapshotConsistent !== false ||
84
+ !/^\d{4}-\d{2}-\d{2}$/.test(report.from) || !/^\d{4}-\d{2}-\d{2}$/.test(report.to) ||
85
+ !Array.isArray(report.days) || report.days.length > 366)
86
+ throw new TypeError('Invalid campaign transition history');
87
+ const statuses = ['pending', 'claimed', 'sending', 'sent', 'suppressed', 'uncertain', 'rejected'];
88
+ let previous = '';
89
+ let total = 0;
90
+ for (const day of report.days) {
91
+ if (!day || !/\d{4}-\d{2}-\d{2}/.test(day.day) || day.day <= previous || day.day < report.from || day.day > report.to ||
92
+ !Number.isSafeInteger(day.total) || day.total < 0 || statuses.some(key => !Number.isSafeInteger(day.counts?.[key]) || day.counts[key] < 0) ||
93
+ statuses.reduce((sum, key) => sum + day.counts[key], 0) !== day.total)
94
+ throw new TypeError('Invalid historical transition day');
95
+ total += day.total;
96
+ previous = day.day;
97
+ }
98
+ if (!Number.isSafeInteger(total))
99
+ throw new TypeError('Transition count overflow');
100
+ const shared = { labels: report.days.map(d => d.day), queryMode: 'database', sampledRows: total, truncated: false };
101
+ const chart = (key, name) => ({ ...shared, id: `campaign_history_${key}`, title: name, type: 'line',
102
+ values: report.days.map(d => d.counts[key]), total: report.days.reduce((sum, day) => sum + day.counts[key], 0) });
103
+ return { sentTransitions: chart('sent', 'Observed transitions into SMTP-sent state'),
104
+ uncertainTransitions: chart('uncertain', 'Observed uncertain SMTP transitions') };
105
+ }
@@ -0,0 +1,30 @@
1
+ import type { ChartData, MarketingReportPage } from './types.js';
2
+ /** Page-scoped state reporting for the function-based marketing service.
3
+ * The service authorizes the read and MUST bind it to its own tenant. */
4
+ export declare function marketingDeliveryPageCharts(page: MarketingReportPage): {
5
+ statuses: ChartData;
6
+ coverage: {
7
+ scope: 'complete' | 'page';
8
+ scanned: number;
9
+ nextCursor: string | null;
10
+ done: boolean;
11
+ disclaimer: string;
12
+ };
13
+ };
14
+ export interface CampaignActivitySnapshot {
15
+ campaignCode: string;
16
+ from: string;
17
+ to: string;
18
+ coverage: 'observed-tracking-events-only';
19
+ /** Event totals are not unique recipients or confirmed views; mail clients and blockers affect opens. */
20
+ opens: number;
21
+ clicks: number;
22
+ downloadClicks: number;
23
+ downloads: number;
24
+ /** Unique verified recipients must not be asserted by this interface. */
25
+ uniqueRecipients: null;
26
+ }
27
+ export declare function campaignActivityCharts(input: CampaignActivitySnapshot): {
28
+ activity: ChartData;
29
+ disclaimer: string;
30
+ };
@@ -0,0 +1,30 @@
1
+ const deliveryLabels = ['notQueued', 'pending', 'claimed', 'sending', 'smtpAccepted', 'suppressed', 'uncertain', 'rejected', 'missing'];
2
+ const num = (n) => Number.isSafeInteger(n) && Number(n) >= 0;
3
+ /** Page-scoped state reporting for the function-based marketing service.
4
+ * The service authorizes the read and MUST bind it to its own tenant. */
5
+ export function marketingDeliveryPageCharts(page) {
6
+ if (!page || typeof page.campaignCode !== 'string' || !num(page.scanned) || !['complete', 'page'].includes(page.scope) ||
7
+ typeof page.done !== 'boolean' || page.nextCursor !== null && typeof page.nextCursor !== 'string' ||
8
+ (page.done && page.nextCursor !== null) || (!page.done && (!page.nextCursor || page.nextCursor.length > 1024)) ||
9
+ typeof page.disclaimer !== 'string' || !page.disclaimer.includes('not confirmed') ||
10
+ deliveryLabels.some(k => !num(page.states?.[k])) || deliveryLabels.reduce((n, k) => n + page.states[k], 0) !== page.scanned ||
11
+ (page.scope === 'complete' && (!page.done || page.nextCursor !== null)))
12
+ throw new TypeError('Invalid marketing delivery page');
13
+ const coverage = { scope: page.scope, scanned: page.scanned, nextCursor: page.nextCursor, done: page.done,
14
+ disclaimer: 'SMTP accepted is not proof of inbox delivery; this is a recipient page unless scope is complete.' };
15
+ return { statuses: { id: 'marketing_delivery_states', title: 'Recipient states (SMTP acceptance only)', type: 'bar',
16
+ labels: [...deliveryLabels], values: deliveryLabels.map(k => page.states[k]), total: page.scanned,
17
+ sampledRows: page.scanned, truncated: !page.done, queryMode: page.scope === 'complete' ? 'database' : 'sampled',
18
+ coverage: page.scope === 'complete' ? 'complete-recipient-scan' : 'page-of-recipient-states' }, coverage };
19
+ }
20
+ export function campaignActivityCharts(input) {
21
+ if (!input || typeof input.campaignCode !== 'string' || input.coverage !== 'observed-tracking-events-only' ||
22
+ !/^\d{4}-\d\d-\d\d$/.test(input.from) || !/^\d{4}-\d\d-\d\d$/.test(input.to) || input.from > input.to ||
23
+ input.uniqueRecipients !== null || !['opens', 'clicks', 'downloadClicks', 'downloads'].every(k => num(input[k])))
24
+ throw new TypeError('Invalid campaign activity snapshot');
25
+ const keys = ['opens', 'clicks', 'downloadClicks', 'downloads'];
26
+ const values = keys.map(k => input[k]);
27
+ return { activity: { id: 'marketing_activity', title: 'Observed tracking events (not unique people)', type: 'bar', labels: [...keys], values,
28
+ total: values.reduce((a, b) => a + b, 0), sampledRows: 0, truncated: false, coverage: 'observed-tracking-events-only' },
29
+ disclaimer: 'Open pixels can be blocked or prefetched; clicks are observed events, not unique users or confirmed deliveries. Tracking must be explicitly enabled and permitted.' };
30
+ }
@@ -0,0 +1 @@
1
+ export declare function reportDashboard(prefix: string): string;