@burdenoff/microfe-healthybowl 2026.902.35 → 2026.902.37
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/dist/healthybowl/context/HealthyBowlContext.js +7 -7
- package/dist/healthybowl/context/HealthyBowlContext.js.map +1 -1
- package/dist/healthybowl/hooks/useAnalyticsReports.js +166 -0
- package/dist/healthybowl/hooks/useAnalyticsReports.js.map +1 -0
- package/dist/healthybowl/hooks/useHealthyBowlData.js.map +1 -1
- package/dist/healthybowl/pages/analytics/InsightsPage.js +2 -2
- package/dist/healthybowl/pages/analytics/InsightsPage.js.map +1 -1
- package/dist/healthybowl/pages/analytics/ReportsPage.js +133 -100
- package/dist/healthybowl/pages/analytics/ReportsPage.js.map +1 -1
- package/dist/healthybowl/pages/financial/FinancialReportsPage.js +88 -107
- package/dist/healthybowl/pages/financial/FinancialReportsPage.js.map +1 -1
- package/package.json +1 -1
|
@@ -5,13 +5,13 @@ import { createContext as n, useCallback as r, useContext as i, useRef as a } fr
|
|
|
5
5
|
import { MemoryRouter as o } from "react-router";
|
|
6
6
|
import { jsx as s } from "react/jsx-runtime";
|
|
7
7
|
//#region src/healthybowl/context/HealthyBowlContext.tsx
|
|
8
|
-
var c = n(null);
|
|
9
|
-
function
|
|
10
|
-
let e = i(
|
|
8
|
+
var c = "00000000-0000-0000-0000-000000000001", l = n(null);
|
|
9
|
+
function u() {
|
|
10
|
+
let e = i(l);
|
|
11
11
|
if (!e) throw Error("useHealthyBowl must be used within a HealthyBowlProvider");
|
|
12
12
|
return e;
|
|
13
13
|
}
|
|
14
|
-
var
|
|
14
|
+
var d = ({ children: n, basePath: i = "/", navigate: c = () => {}, currentUser: u, workspaceId: d = "", apiGatewayUrl: f = "", globalGatewayUrl: p = "", authToken: m = "", googleMapsApiKey: h, ttsEndpoint: g }) => {
|
|
15
15
|
e({ googleMapsApiKey: h });
|
|
16
16
|
let _ = a(m);
|
|
17
17
|
_.current = m, t({
|
|
@@ -20,19 +20,19 @@ var u = ({ children: n, basePath: i = "/", navigate: l = () => {}, currentUser:
|
|
|
20
20
|
});
|
|
21
21
|
let v = {
|
|
22
22
|
basePath: i,
|
|
23
|
-
navigate:
|
|
23
|
+
navigate: c,
|
|
24
24
|
currentUser: u,
|
|
25
25
|
workspaceId: d,
|
|
26
26
|
apiGatewayUrl: f,
|
|
27
27
|
globalGatewayUrl: p,
|
|
28
28
|
authToken: m
|
|
29
|
-
}, y = /* @__PURE__ */ s(
|
|
29
|
+
}, y = /* @__PURE__ */ s(l.Provider, {
|
|
30
30
|
value: v,
|
|
31
31
|
children: n
|
|
32
32
|
});
|
|
33
33
|
return i && i !== "/" ? y : /* @__PURE__ */ s(o, { children: y });
|
|
34
34
|
};
|
|
35
35
|
//#endregion
|
|
36
|
-
export {
|
|
36
|
+
export { c as HEALTHYBOWL_FALLBACK_WORKSPACE_ID, d as HealthyBowlProvider, u as useHealthyBowl };
|
|
37
37
|
|
|
38
38
|
//# sourceMappingURL=HealthyBowlContext.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HealthyBowlContext.js","names":[],"sources":["../../../src/healthybowl/context/HealthyBowlContext.tsx"],"sourcesContent":["/**\n * HealthyBowl Context Provider\n * @module healthybowl\n */\n\nimport { createContext, useCallback, useContext, useRef, type FC, type PropsWithChildren } from 'react';\nimport { MemoryRouter } from 'react-router';\nimport type { HealthyBowlRootProps } from '../types';\nimport { configureGeocoder } from '../utils/geocode';\nimport { configureSpeechEngine } from '../../services/speech';\n\ninterface HealthyBowlContextValue {\n basePath: string;\n navigate: (path: string) => void;\n currentUser: HealthyBowlRootProps['currentUser'];\n workspaceId: string;\n apiGatewayUrl: string;\n globalGatewayUrl: string;\n authToken: string;\n}\n\nconst HealthyBowlContext = createContext<HealthyBowlContextValue | null>(null);\n\nexport function useHealthyBowl(): HealthyBowlContextValue {\n const context = useContext(HealthyBowlContext);\n if (!context) {\n throw new Error('useHealthyBowl must be used within a HealthyBowlProvider');\n }\n return context;\n}\n\nexport const HealthyBowlProvider: FC<PropsWithChildren<HealthyBowlRootProps>> = ({\n children,\n basePath = '/',\n navigate = () => {},\n currentUser,\n workspaceId = '',\n apiGatewayUrl = '',\n globalGatewayUrl = '',\n authToken = '',\n googleMapsApiKey,\n ttsEndpoint,\n}) => {\n // Inject the host app's Google Maps key into the (non-React) geocoder. Done\n // synchronously in render (not useEffect) so it's set before child map effects\n // run — child effects fire before parent effects. Idempotent module assignment.\n configureGeocoder({ googleMapsApiKey });\n\n /**\n * Point the assistant's speech stack at the hosted TTS proxy.\n *\n * Wiring it HERE, rather than exporting `configureSpeechEngine` for the host\n * to call, is what makes the feature exist at all: nothing outside this graph\n * imported it, so the published bundle had the function tree-shaken away and\n * the module-level endpoint/header slots could never be assigned. The only\n * reachable switch was `window.__HB_TTS_ENDPOINT__`, which carries no headers\n * — i.e. hosted TTS could previously only have been enabled ANONYMOUSLY,\n * against a proxy that bills per character.\n *\n * The token is read through a ref rather than captured. `configureSpeechEngine`\n * is deliberately idempotent (resetting the memoised engine every render would\n * cancel playback mid-reply), so it keeps the FIRST `getHeaders` it is given —\n * and a captured token would work right up until it refreshed, then fail in\n * the hardest place to notice. A stable identity also means this call is a\n * no-op on every render after the first.\n */\n const authTokenRef = useRef(authToken);\n authTokenRef.current = authToken;\n const getHeaders = useCallback(\n (): Record<string, string> => (authTokenRef.current ? { authorization: `Bearer ${authTokenRef.current}` } : {}),\n []\n );\n configureSpeechEngine({ ttsEndpoint, getHeaders });\n\n const contextValue: HealthyBowlContextValue = {\n basePath,\n navigate,\n currentUser,\n workspaceId,\n apiGatewayUrl,\n globalGatewayUrl,\n authToken,\n };\n\n const content = <HealthyBowlContext.Provider value={contextValue}>{children}</HealthyBowlContext.Provider>;\n\n // If basePath is provided, we're running inside the host shell (which has BrowserRouter)\n if (basePath && basePath !== '/') return content;\n\n // Standalone mode: wrap in MemoryRouter\n return <MemoryRouter>{content}</MemoryRouter>;\n};\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"HealthyBowlContext.js","names":[],"sources":["../../../src/healthybowl/context/HealthyBowlContext.tsx"],"sourcesContent":["/**\n * HealthyBowl Context Provider\n * @module healthybowl\n */\n\nimport { createContext, useCallback, useContext, useRef, type FC, type PropsWithChildren } from 'react';\nimport { MemoryRouter } from 'react-router';\nimport type { HealthyBowlRootProps } from '../types';\nimport { configureGeocoder } from '../utils/geocode';\nimport { configureSpeechEngine } from '../../services/speech';\n\ninterface HealthyBowlContextValue {\n basePath: string;\n navigate: (path: string) => void;\n currentUser: HealthyBowlRootProps['currentUser'];\n workspaceId: string;\n apiGatewayUrl: string;\n globalGatewayUrl: string;\n authToken: string;\n}\n\n/** Keeps standalone/default-prop data reads and mutations in the same demo workspace. */\nexport const HEALTHYBOWL_FALLBACK_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001';\n\nconst HealthyBowlContext = createContext<HealthyBowlContextValue | null>(null);\n\nexport function useHealthyBowl(): HealthyBowlContextValue {\n const context = useContext(HealthyBowlContext);\n if (!context) {\n throw new Error('useHealthyBowl must be used within a HealthyBowlProvider');\n }\n return context;\n}\n\nexport const HealthyBowlProvider: FC<PropsWithChildren<HealthyBowlRootProps>> = ({\n children,\n basePath = '/',\n navigate = () => {},\n currentUser,\n workspaceId = '',\n apiGatewayUrl = '',\n globalGatewayUrl = '',\n authToken = '',\n googleMapsApiKey,\n ttsEndpoint,\n}) => {\n // Inject the host app's Google Maps key into the (non-React) geocoder. Done\n // synchronously in render (not useEffect) so it's set before child map effects\n // run — child effects fire before parent effects. Idempotent module assignment.\n configureGeocoder({ googleMapsApiKey });\n\n /**\n * Point the assistant's speech stack at the hosted TTS proxy.\n *\n * Wiring it HERE, rather than exporting `configureSpeechEngine` for the host\n * to call, is what makes the feature exist at all: nothing outside this graph\n * imported it, so the published bundle had the function tree-shaken away and\n * the module-level endpoint/header slots could never be assigned. The only\n * reachable switch was `window.__HB_TTS_ENDPOINT__`, which carries no headers\n * — i.e. hosted TTS could previously only have been enabled ANONYMOUSLY,\n * against a proxy that bills per character.\n *\n * The token is read through a ref rather than captured. `configureSpeechEngine`\n * is deliberately idempotent (resetting the memoised engine every render would\n * cancel playback mid-reply), so it keeps the FIRST `getHeaders` it is given —\n * and a captured token would work right up until it refreshed, then fail in\n * the hardest place to notice. A stable identity also means this call is a\n * no-op on every render after the first.\n */\n const authTokenRef = useRef(authToken);\n authTokenRef.current = authToken;\n const getHeaders = useCallback(\n (): Record<string, string> => (authTokenRef.current ? { authorization: `Bearer ${authTokenRef.current}` } : {}),\n []\n );\n configureSpeechEngine({ ttsEndpoint, getHeaders });\n\n const contextValue: HealthyBowlContextValue = {\n basePath,\n navigate,\n currentUser,\n workspaceId,\n apiGatewayUrl,\n globalGatewayUrl,\n authToken,\n };\n\n const content = <HealthyBowlContext.Provider value={contextValue}>{children}</HealthyBowlContext.Provider>;\n\n // If basePath is provided, we're running inside the host shell (which has BrowserRouter)\n if (basePath && basePath !== '/') return content;\n\n // Standalone mode: wrap in MemoryRouter\n return <MemoryRouter>{content}</MemoryRouter>;\n};\n"],"mappings":";;;;;;;AAsBA,IAAa,IAAoC,wCAE3C,IAAqB,EAA8C,IAAI;AAE7E,SAAgB,IAA0C;CACxD,IAAM,IAAU,EAAW,CAAkB;CAC7C,IAAI,CAAC,GACH,MAAU,MAAM,0DAA0D;CAE5E,OAAO;AACT;AAEA,IAAa,KAAoE,EAC/E,aACA,cAAW,KACX,oBAAiB,CAAC,GAClB,gBACA,iBAAc,IACd,mBAAgB,IAChB,sBAAmB,IACnB,eAAY,IACZ,qBACA,qBACI;CAIJ,EAAkB,EAAE,oBAAiB,CAAC;CAoBtC,IAAM,IAAe,EAAO,CAAS;CAMrC,AALA,EAAa,UAAU,GAKvB,EAAsB;EAAE;EAAa,YAJlB,QACc,EAAa,UAAU,EAAE,eAAe,UAAU,EAAa,UAAU,IAAI,CAAC,GAC7G,CAAC,CAEkC;CAAW,CAAC;CAEjD,IAAM,IAAwC;EAC5C;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GAEM,IAAU,kBAAC,EAAmB,UAApB;EAA6B,OAAO;EAAe;CAAsC,CAAA;CAMzG,OAHI,KAAY,MAAa,MAAY,IAGlC,kBAAC,GAAD,EAAA,UAAe,EAAsB,CAAA;AAC9C"}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
|
|
2
|
+
import { useCallback as t, useRef as n, useState as r } from "react";
|
|
3
|
+
import { gql as i } from "@apollo/client";
|
|
4
|
+
import { useApolloClient as a, useMutation as o } from "@apollo/client/react";
|
|
5
|
+
//#region src/healthybowl/hooks/useAnalyticsReports.ts
|
|
6
|
+
var s = i`
|
|
7
|
+
mutation GenerateHealthyBowlAnalyticsReport(
|
|
8
|
+
$context: ContextInput!
|
|
9
|
+
$title: String
|
|
10
|
+
$type: String!
|
|
11
|
+
$startDate: String!
|
|
12
|
+
$endDate: String!
|
|
13
|
+
) {
|
|
14
|
+
generateHealthyBowlAnalyticsReport(
|
|
15
|
+
context: $context
|
|
16
|
+
title: $title
|
|
17
|
+
type: $type
|
|
18
|
+
startDate: $startDate
|
|
19
|
+
endDate: $endDate
|
|
20
|
+
) {
|
|
21
|
+
id
|
|
22
|
+
title
|
|
23
|
+
type
|
|
24
|
+
status
|
|
25
|
+
period
|
|
26
|
+
createdAt
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
`, c = i`
|
|
30
|
+
query GetHealthyBowlAnalyticsReportExport($context: ContextInput!, $reportId: ID!) {
|
|
31
|
+
getHealthyBowlAnalyticsReportExport(context: $context, reportId: $reportId) {
|
|
32
|
+
format
|
|
33
|
+
filename
|
|
34
|
+
mimeType
|
|
35
|
+
contentBase64
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
`, l = [{
|
|
39
|
+
value: "FINANCIAL",
|
|
40
|
+
labelKey: "healthybowl.analytics.reports.type.financial",
|
|
41
|
+
labelFallback: "Financial"
|
|
42
|
+
}, {
|
|
43
|
+
value: "CROP",
|
|
44
|
+
labelKey: "healthybowl.analytics.reports.type.crop",
|
|
45
|
+
labelFallback: "Crop"
|
|
46
|
+
}];
|
|
47
|
+
function u(e) {
|
|
48
|
+
return l.some((t) => t.value === e);
|
|
49
|
+
}
|
|
50
|
+
function d(e, t) {
|
|
51
|
+
if (typeof e == "object" && e) {
|
|
52
|
+
let t = e;
|
|
53
|
+
if (Array.isArray(t.errors) && t.errors.length > 0) {
|
|
54
|
+
let e = t.errors[0], n = e?.extensions?.userMessage;
|
|
55
|
+
if (typeof n == "string" && n.length > 0) return n;
|
|
56
|
+
if (typeof e?.message == "string" && e.message.length > 0) return e.message;
|
|
57
|
+
}
|
|
58
|
+
if (typeof t.message == "string" && t.message.length > 0) return t.message;
|
|
59
|
+
}
|
|
60
|
+
return t;
|
|
61
|
+
}
|
|
62
|
+
function f(e) {
|
|
63
|
+
let t = (e) => String(e).padStart(2, "0");
|
|
64
|
+
return `${e.getFullYear()}-${t(e.getMonth() + 1)}-${t(e.getDate())}`;
|
|
65
|
+
}
|
|
66
|
+
function p(e) {
|
|
67
|
+
return {
|
|
68
|
+
startDate: f(new Date(e.getFullYear(), 0, 1)),
|
|
69
|
+
endDate: f(e)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function m(e) {
|
|
73
|
+
let t = e.getFullYear(), n = Math.floor(e.getMonth() / 3), r = new Date(t, n * 3, 1), i = new Date(t, (n - 1) * 3, 1), a = new Date(t, n * 3, 0);
|
|
74
|
+
return [
|
|
75
|
+
{
|
|
76
|
+
value: "ytd",
|
|
77
|
+
labelKey: "healthybowl.financial.reports.generate.periods.ytd",
|
|
78
|
+
labelFallback: "Year to date",
|
|
79
|
+
startDate: f(new Date(t, 0, 1)),
|
|
80
|
+
endDate: f(e)
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
value: "this-quarter",
|
|
84
|
+
labelKey: "healthybowl.financial.reports.generate.periods.thisQuarter",
|
|
85
|
+
labelFallback: "This quarter",
|
|
86
|
+
startDate: f(r),
|
|
87
|
+
endDate: f(e)
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
value: "last-quarter",
|
|
91
|
+
labelKey: "healthybowl.financial.reports.generate.periods.lastQuarter",
|
|
92
|
+
labelFallback: "Last quarter",
|
|
93
|
+
startDate: f(i),
|
|
94
|
+
endDate: f(a)
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
value: "last-year",
|
|
98
|
+
labelKey: "healthybowl.financial.reports.generate.periods.lastYear",
|
|
99
|
+
labelFallback: "Last year",
|
|
100
|
+
startDate: f(new Date(t - 1, 0, 1)),
|
|
101
|
+
endDate: f(new Date(t - 1, 11, 31))
|
|
102
|
+
}
|
|
103
|
+
];
|
|
104
|
+
}
|
|
105
|
+
function h() {
|
|
106
|
+
let { workspaceId: i } = e(), l = i || "00000000-0000-0000-0000-000000000001", u = a(), [f] = o(s), [m, h] = r(!1), [g, _] = r(() => /* @__PURE__ */ new Set()), v = n(/* @__PURE__ */ new Set());
|
|
107
|
+
return {
|
|
108
|
+
generate: t(async (e) => {
|
|
109
|
+
h(!0);
|
|
110
|
+
try {
|
|
111
|
+
let t = p(/* @__PURE__ */ new Date());
|
|
112
|
+
return await f({ variables: {
|
|
113
|
+
context: { workspaceId: l },
|
|
114
|
+
title: e.title,
|
|
115
|
+
type: e.type,
|
|
116
|
+
startDate: e.startDate ?? t.startDate,
|
|
117
|
+
endDate: e.endDate ?? t.endDate
|
|
118
|
+
} }), { ok: !0 };
|
|
119
|
+
} catch (e) {
|
|
120
|
+
return {
|
|
121
|
+
ok: !1,
|
|
122
|
+
message: d(e, "The report could not be generated.")
|
|
123
|
+
};
|
|
124
|
+
} finally {
|
|
125
|
+
h(!1);
|
|
126
|
+
}
|
|
127
|
+
}, [f, l]),
|
|
128
|
+
download: t(async (e) => {
|
|
129
|
+
if (v.current.has(e)) return {
|
|
130
|
+
ok: !1,
|
|
131
|
+
message: "This report is already being prepared."
|
|
132
|
+
};
|
|
133
|
+
v.current.add(e), _(new Set(v.current));
|
|
134
|
+
try {
|
|
135
|
+
let { data: t } = await u.query({
|
|
136
|
+
query: c,
|
|
137
|
+
variables: {
|
|
138
|
+
context: { workspaceId: l },
|
|
139
|
+
reportId: e
|
|
140
|
+
},
|
|
141
|
+
fetchPolicy: "network-only"
|
|
142
|
+
}), n = t?.getHealthyBowlAnalyticsReportExport;
|
|
143
|
+
return n?.contentBase64 ? {
|
|
144
|
+
ok: !0,
|
|
145
|
+
payload: n
|
|
146
|
+
} : {
|
|
147
|
+
ok: !1,
|
|
148
|
+
message: "The report file could not be produced."
|
|
149
|
+
};
|
|
150
|
+
} catch (e) {
|
|
151
|
+
return {
|
|
152
|
+
ok: !1,
|
|
153
|
+
message: d(e, "The report could not be downloaded.")
|
|
154
|
+
};
|
|
155
|
+
} finally {
|
|
156
|
+
v.current.delete(e), _(new Set(v.current));
|
|
157
|
+
}
|
|
158
|
+
}, [u, l]),
|
|
159
|
+
generating: m,
|
|
160
|
+
downloadingIds: g
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
//#endregion
|
|
164
|
+
export { l as GENERATABLE_REPORT_TYPES, u as isGeneratableReportType, m as reportPeriodOptions, h as useAnalyticsReports };
|
|
165
|
+
|
|
166
|
+
//# sourceMappingURL=useAnalyticsReports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAnalyticsReports.js","names":[],"sources":["../../../src/healthybowl/hooks/useAnalyticsReports.ts"],"sourcesContent":["/**\n * Generate and download analytics reports (BOFF-6022).\n *\n * Declared as inline `gql` documents rather than entries under `src/operations/`: these ops are\n * newer than the committed `graphql/wspace.graphql` snapshot that codegen validates against, and\n * this is the escape hatch the repo uses for exactly that case.\n *\n * @module healthybowl\n */\nimport { useCallback, useRef, useState } from 'react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient, useMutation } from '@apollo/client/react';\nimport { HEALTHYBOWL_FALLBACK_WORKSPACE_ID, useHealthyBowl } from '../context/HealthyBowlContext';\n\nconst GENERATE_ANALYTICS_REPORT = gql`\n mutation GenerateHealthyBowlAnalyticsReport(\n $context: ContextInput!\n $title: String\n $type: String!\n $startDate: String!\n $endDate: String!\n ) {\n generateHealthyBowlAnalyticsReport(\n context: $context\n title: $title\n type: $type\n startDate: $startDate\n endDate: $endDate\n ) {\n id\n title\n type\n status\n period\n createdAt\n }\n }\n`;\n\nconst ANALYTICS_REPORT_EXPORT = gql`\n query GetHealthyBowlAnalyticsReportExport($context: ContextInput!, $reportId: ID!) {\n getHealthyBowlAnalyticsReportExport(context: $context, reportId: $reportId) {\n format\n filename\n mimeType\n contentBase64\n }\n }\n`;\n\n/** The report types the server can actually build today. */\nexport const GENERATABLE_REPORT_TYPES = [\n { value: 'FINANCIAL', labelKey: 'healthybowl.analytics.reports.type.financial', labelFallback: 'Financial' },\n { value: 'CROP', labelKey: 'healthybowl.analytics.reports.type.crop', labelFallback: 'Crop' },\n] as const;\n\nexport type GeneratableReportType = (typeof GENERATABLE_REPORT_TYPES)[number]['value'];\n\nexport function isGeneratableReportType(value: string): value is GeneratableReportType {\n return GENERATABLE_REPORT_TYPES.some((type) => type.value === value);\n}\n\n/**\n * Read the operator-facing message off a rejected operation.\n *\n * Apollo Client v4 rejects with `CombinedGraphQLErrors`, which has no v3 `graphQLErrors` property,\n * and the server puts the readable text in `extensions.userMessage` — for these ops that is the\n * sentence naming which report types CAN be generated. `err.message` alone would render Apollo's\n * aggregate wording and throw that away.\n */\nexport function readOperationError(err: unknown, fallback: string): string {\n if (err !== null && typeof err === 'object') {\n const shaped = err as { errors?: unknown; message?: unknown };\n if (Array.isArray(shaped.errors) && shaped.errors.length > 0) {\n const first = shaped.errors[0] as { message?: unknown; extensions?: { userMessage?: unknown } | null };\n const userMessage = first?.extensions?.userMessage;\n if (typeof userMessage === 'string' && userMessage.length > 0) return userMessage;\n if (typeof first?.message === 'string' && first.message.length > 0) return first.message;\n }\n if (typeof shaped.message === 'string' && shaped.message.length > 0) return shaped.message;\n }\n return fallback;\n}\n\n/**\n * `YYYY-MM-DD` in the farmer's OWN timezone.\n *\n * `toISOString().slice(0, 10)` would convert to UTC. For a farm in IST (UTC+5:30), any time between\n * midnight and 05:30 local yields the PREVIOUS day — so a report generated before dawn, which is\n * exactly when farm work happens, would silently end a day early. On 1 January it would compute\n * last year's 1 January as the start.\n */\nexport function toLocalDateString(date: Date): string {\n const pad = (n: number) => String(n).padStart(2, '0');\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n}\n\n/**\n * A sensible default period for a newly requested report.\n *\n * Year to date rather than \"this month\": a farmer generating a report usually wants the season so\n * far, and an empty January report would be the first thing a new user sees.\n */\nexport function defaultReportPeriod(now: Date): { startDate: string; endDate: string } {\n return { startDate: toLocalDateString(new Date(now.getFullYear(), 0, 1)), endDate: toLocalDateString(now) };\n}\n\n/**\n * Real period choices, computed from today rather than hard-coded.\n *\n * The financial page shipped a picker offering \"Q1 2025\" / \"Q4 2024\" — fixed strings that were\n * already stale and would only get staler. Generating a \"Q1 2025\" report in 2026 is worse than\n * defaulting to year-to-date, so the options are derived.\n */\nexport interface ReportPeriodOption {\n value: string;\n labelKey: string;\n labelFallback: string;\n startDate: string;\n endDate: string;\n}\n\nexport function reportPeriodOptions(now: Date): ReportPeriodOption[] {\n const year = now.getFullYear();\n const quarter = Math.floor(now.getMonth() / 3);\n const quarterStart = new Date(year, quarter * 3, 1);\n const prevQuarterStart = new Date(year, (quarter - 1) * 3, 1);\n // Day 0 of the following month is the last day of this one — no month-length table, no leap-year\n // special case.\n const prevQuarterEnd = new Date(year, quarter * 3, 0);\n\n return [\n {\n value: 'ytd',\n labelKey: 'healthybowl.financial.reports.generate.periods.ytd',\n labelFallback: 'Year to date',\n startDate: toLocalDateString(new Date(year, 0, 1)),\n endDate: toLocalDateString(now),\n },\n {\n value: 'this-quarter',\n labelKey: 'healthybowl.financial.reports.generate.periods.thisQuarter',\n labelFallback: 'This quarter',\n startDate: toLocalDateString(quarterStart),\n endDate: toLocalDateString(now),\n },\n {\n value: 'last-quarter',\n labelKey: 'healthybowl.financial.reports.generate.periods.lastQuarter',\n labelFallback: 'Last quarter',\n startDate: toLocalDateString(prevQuarterStart),\n endDate: toLocalDateString(prevQuarterEnd),\n },\n {\n value: 'last-year',\n labelKey: 'healthybowl.financial.reports.generate.periods.lastYear',\n labelFallback: 'Last year',\n startDate: toLocalDateString(new Date(year - 1, 0, 1)),\n endDate: toLocalDateString(new Date(year - 1, 11, 31)),\n },\n ];\n}\n\ninterface GenerateInput {\n title: string;\n type: GeneratableReportType;\n startDate?: string;\n endDate?: string;\n}\n\nexport interface ExportPayload {\n format: string;\n filename: string;\n mimeType: string;\n contentBase64: string;\n}\n\nexport type GenerateResult = { ok: true } | { ok: false; message: string };\nexport type DownloadResult = { ok: true; payload: ExportPayload } | { ok: false; message: string };\n\nexport function useAnalyticsReports(): {\n generate: (input: GenerateInput) => Promise<GenerateResult>;\n download: (reportId: string) => Promise<DownloadResult>;\n generating: boolean;\n downloadingIds: ReadonlySet<string>;\n} {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || HEALTHYBOWL_FALLBACK_WORKSPACE_ID;\n const client = useApolloClient();\n const [mutate] = useMutation(GENERATE_ANALYTICS_REPORT);\n const [generating, setGenerating] = useState(false);\n const [downloadingIds, setDownloadingIds] = useState<ReadonlySet<string>>(() => new Set());\n // State updates render the pending status; the ref also rejects two same-tick clicks before React\n // has rendered that disabled state.\n const downloadingIdsRef = useRef(new Set<string>());\n\n const generate = useCallback(\n async (input: GenerateInput) => {\n setGenerating(true);\n try {\n const period = defaultReportPeriod(new Date());\n await mutate({\n variables: {\n context: { workspaceId: effectiveWorkspaceId },\n title: input.title,\n type: input.type,\n startDate: input.startDate ?? period.startDate,\n endDate: input.endDate ?? period.endDate,\n },\n });\n return { ok: true } as const;\n } catch (err) {\n return { ok: false, message: readOperationError(err, 'The report could not be generated.') } as const;\n } finally {\n setGenerating(false);\n }\n },\n [mutate, effectiveWorkspaceId]\n );\n\n const download = useCallback(\n async (reportId: string) => {\n if (downloadingIdsRef.current.has(reportId)) {\n return { ok: false, message: 'This report is already being prepared.' } as const;\n }\n downloadingIdsRef.current.add(reportId);\n setDownloadingIds(new Set(downloadingIdsRef.current));\n try {\n const { data } = await client.query({\n query: ANALYTICS_REPORT_EXPORT,\n variables: { context: { workspaceId: effectiveWorkspaceId }, reportId },\n // Always refetched: a cached copy would hand back the previous report's bytes when the\n // farmer downloads a second one in the same session.\n fetchPolicy: 'network-only',\n });\n const payload = (data as { getHealthyBowlAnalyticsReportExport?: ExportPayload } | null)\n ?.getHealthyBowlAnalyticsReportExport;\n if (!payload?.contentBase64) {\n return { ok: false, message: 'The report file could not be produced.' } as const;\n }\n return { ok: true, payload } as const;\n } catch (err) {\n return { ok: false, message: readOperationError(err, 'The report could not be downloaded.') } as const;\n } finally {\n downloadingIdsRef.current.delete(reportId);\n setDownloadingIds(new Set(downloadingIdsRef.current));\n }\n },\n [client, effectiveWorkspaceId]\n );\n\n return { generate, download, generating, downloadingIds };\n}\n"],"mappings":";;;;;AAcA,IAAM,IAA4B,CAAG;;;;;;;;;;;;;;;;;;;;;;;GAyB/B,IAA0B,CAAG;;;;;;;;;GAYtB,IAA2B,CACtC;CAAE,OAAO;CAAa,UAAU;CAAgD,eAAe;AAAY,GAC3G;CAAE,OAAO;CAAQ,UAAU;CAA2C,eAAe;AAAO,CAC9F;AAIA,SAAgB,EAAwB,GAA+C;CACrF,OAAO,EAAyB,MAAM,MAAS,EAAK,UAAU,CAAK;AACrE;AAUA,SAAgB,EAAmB,GAAc,GAA0B;CACzE,IAAoB,OAAO,KAAQ,YAA/B,GAAyC;EAC3C,IAAM,IAAS;EACf,IAAI,MAAM,QAAQ,EAAO,MAAM,KAAK,EAAO,OAAO,SAAS,GAAG;GAC5D,IAAM,IAAQ,EAAO,OAAO,IACtB,IAAc,GAAO,YAAY;GACvC,IAAI,O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