@burdenoff/microfe-healthybowl 2026.902.37 → 2026.903.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/dist/healthybowl/hooks/useAnalyticsReports.js +16 -9
- package/dist/healthybowl/hooks/useAnalyticsReports.js.map +1 -1
- package/dist/healthybowl/pages/analytics/ReportsPage.js +31 -27
- package/dist/healthybowl/pages/analytics/ReportsPage.js.map +1 -1
- package/dist/healthybowl/pages/financial/FinancialReportsPage.js +30 -26
- package/dist/healthybowl/pages/financial/FinancialReportsPage.js.map +1 -1
- package/package.json +1 -1
|
@@ -103,10 +103,14 @@ function m(e) {
|
|
|
103
103
|
];
|
|
104
104
|
}
|
|
105
105
|
function h() {
|
|
106
|
-
let { workspaceId: i } = e(), l = i || "00000000-0000-0000-0000-000000000001", u = a(), [f] = o(s), [m, h] = r(
|
|
106
|
+
let { workspaceId: i } = e(), l = i || "00000000-0000-0000-0000-000000000001", u = a(), [f] = o(s), [m, h] = r(() => /* @__PURE__ */ new Set()), g = n(!1), _ = n(/* @__PURE__ */ new Set());
|
|
107
107
|
return {
|
|
108
108
|
generate: t(async (e) => {
|
|
109
|
-
|
|
109
|
+
if (g.current) return {
|
|
110
|
+
ok: !0,
|
|
111
|
+
started: !1
|
|
112
|
+
};
|
|
113
|
+
g.current = !0;
|
|
110
114
|
try {
|
|
111
115
|
let t = p(/* @__PURE__ */ new Date());
|
|
112
116
|
return await f({ variables: {
|
|
@@ -115,22 +119,26 @@ function h() {
|
|
|
115
119
|
type: e.type,
|
|
116
120
|
startDate: e.startDate ?? t.startDate,
|
|
117
121
|
endDate: e.endDate ?? t.endDate
|
|
118
|
-
} }), {
|
|
122
|
+
} }), {
|
|
123
|
+
ok: !0,
|
|
124
|
+
started: !0
|
|
125
|
+
};
|
|
119
126
|
} catch (e) {
|
|
120
127
|
return {
|
|
121
128
|
ok: !1,
|
|
129
|
+
started: !0,
|
|
122
130
|
message: d(e, "The report could not be generated.")
|
|
123
131
|
};
|
|
124
132
|
} finally {
|
|
125
|
-
|
|
133
|
+
g.current = !1;
|
|
126
134
|
}
|
|
127
135
|
}, [f, l]),
|
|
128
136
|
download: t(async (e) => {
|
|
129
|
-
if (
|
|
137
|
+
if (_.current.has(e)) return {
|
|
130
138
|
ok: !1,
|
|
131
139
|
message: "This report is already being prepared."
|
|
132
140
|
};
|
|
133
|
-
|
|
141
|
+
_.current.add(e), h(new Set(_.current));
|
|
134
142
|
try {
|
|
135
143
|
let { data: t } = await u.query({
|
|
136
144
|
query: c,
|
|
@@ -153,11 +161,10 @@ function h() {
|
|
|
153
161
|
message: d(e, "The report could not be downloaded.")
|
|
154
162
|
};
|
|
155
163
|
} finally {
|
|
156
|
-
|
|
164
|
+
_.current.delete(e), h(new Set(_.current));
|
|
157
165
|
}
|
|
158
166
|
}, [u, l]),
|
|
159
|
-
|
|
160
|
-
downloadingIds: g
|
|
167
|
+
downloadingIds: m
|
|
161
168
|
};
|
|
162
169
|
}
|
|
163
170
|
//#endregion
|
|
@@ -1 +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,OAAO,KAAgB,YAAY,EAAY,SAAS,GAAG,OAAO;GACtE,IAAI,OAAO,GAAO,WAAY,YAAY,EAAM,QAAQ,SAAS,GAAG,OAAO,EAAM;EACnF;EACA,IAAI,OAAO,EAAO,WAAY,YAAY,EAAO,QAAQ,SAAS,GAAG,OAAO,EAAO;CACrF;C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,EAAkB,OAAO,CAAC;GACtD;EACF,GACA,CAAC,GAAQ,CAAoB,CAGZ;EAAU;EAAY;CAAe;AAC1D"}
|
|
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 =\n { ok: true; started: true } | { ok: true; started: false } | { ok: false; started: true; 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 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 [downloadingIds, setDownloadingIds] = useState<ReadonlySet<string>>(() => new Set());\n // Both operations use refs to reject duplicate same-tick clicks before React has rendered the\n // consuming page's disabled button state.\n const generatingRef = useRef(false);\n const downloadingIdsRef = useRef(new Set<string>());\n\n const generate = useCallback(\n async (input: GenerateInput) => {\n if (generatingRef.current) return { ok: true, started: false } as const;\n generatingRef.current = 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, started: true } as const;\n } catch (err) {\n return {\n ok: false,\n started: true,\n message: readOperationError(err, 'The report could not be generated.'),\n } as const;\n } finally {\n generatingRef.current = 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, downloadingIds };\n}\n"],"m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E,IAAI;KAAM,SAAS;IAAK;GACnC,SAAS,GAAK;IACZ,OAAO;KACL,IAAI;KACJ,SAAS;KACT,SAAS,EAAmB,GAAK,oCAAoC;IACvE;GACF,UAAU;IACR,EAAc,UAAU;GAC1B;EACF,GACA,CAAC,GAAQ,CAAoB,CAkCtB;EAAU,UA/BF,EACf,OAAO,MAAqB;GAC1B,IAAI,EAAkB,QAAQ,IAAI,CAAQ,GACxC,OAAO;IAAE,IAAI;IAAO,SAAS;GAAyC;GAGxE,AADA,EAAkB,QAAQ,IAAI,CAAQ,GACtC,EAAkB,IAAI,IAAI,EAAkB,OAAO,CAAC;GACpD,IAAI;IACF,IAAM,EAAE,YAAS,MAAM,EAAO,MAAM;KAClC,OAAO;KACP,WAAW;MAAE,SAAS,EAAE,aAAa,EAAqB;MAAG;KAAS;KAGtE,aAAa;IACf,CAAC,GACK,IAAW,GACb;IAIJ,OAHK,GAAS,gBAGP;KAAE,IAAI;KAAM;IAAQ,IAFlB;KAAE,IAAI;KAAO,SAAS;IAAyC;GAG1E,SAAS,GAAK;IACZ,OAAO;KAAE,IAAI;KAAO,SAAS,EAAmB,GAAK,qCAAqC;IAAE;GAC9F,UAAU;IAER,AADA,EAAkB,QAAQ,OAAO,CAAQ,GACzC,EAAkB,IAAI,IAAI,EAAkB,OAAO,CAAC;GACtD;EACF,GACA,CAAC,GAAQ,CAAoB,CAGZ;EAAU;CAAe;AAC9C"}
|
|
@@ -34,37 +34,41 @@ function M() {
|
|
|
34
34
|
let { t: M } = _(), { analyticsReports: N, loading: P, errors: F, refetch: I } = d(), { generate: L, download: ee, downloadingIds: R } = m(), [z, B] = g(!1), [V, H] = g(""), [U, W] = g(!1), [G, K] = g(""), [q, J] = g("FINANCIAL"), { toasts: Y, toast: X, dismiss: Z } = u(), Q = (e) => {
|
|
35
35
|
p(e) && J(e);
|
|
36
36
|
}, $ = async () => {
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
37
|
+
if (z) return;
|
|
38
|
+
if (!G.trim()) {
|
|
39
|
+
X({
|
|
40
|
+
title: M("healthybowl.analytics.reports.toast.missingTitle.title", "Missing Title"),
|
|
41
|
+
description: M("healthybowl.analytics.reports.toast.missingTitle.description", "Please enter a report title"),
|
|
42
|
+
variant: "warning"
|
|
43
|
+
});
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
B(!0);
|
|
47
|
+
let e = !0;
|
|
48
|
+
try {
|
|
49
|
+
let t = await L({
|
|
50
|
+
title: G.trim(),
|
|
51
|
+
type: q
|
|
52
|
+
});
|
|
53
|
+
if (!t.started) {
|
|
54
|
+
e = !1;
|
|
44
55
|
return;
|
|
45
56
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
57
|
+
if (!t.ok) {
|
|
58
|
+
X({
|
|
59
|
+
title: M("healthybowl.analytics.reports.toast.failed.title", "Could not generate the report"),
|
|
60
|
+
description: t.message,
|
|
61
|
+
variant: "error"
|
|
51
62
|
});
|
|
52
|
-
|
|
53
|
-
X({
|
|
54
|
-
title: M("healthybowl.analytics.reports.toast.failed.title", "Could not generate the report"),
|
|
55
|
-
description: e.message,
|
|
56
|
-
variant: "error"
|
|
57
|
-
});
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
await I().catch(() => void 0), X({
|
|
61
|
-
title: M("healthybowl.analytics.reports.toast.generated.title", "Report ready"),
|
|
62
|
-
description: M("healthybowl.analytics.reports.toast.generated.description", "\"{{title}}\" is ready to download.", { title: G.trim() }),
|
|
63
|
-
variant: "success"
|
|
64
|
-
}), W(!1), K(""), J("FINANCIAL");
|
|
65
|
-
} finally {
|
|
66
|
-
B(!1);
|
|
63
|
+
return;
|
|
67
64
|
}
|
|
65
|
+
await I().catch(() => void 0), X({
|
|
66
|
+
title: M("healthybowl.analytics.reports.toast.generated.title", "Report ready"),
|
|
67
|
+
description: M("healthybowl.analytics.reports.toast.generated.description", "\"{{title}}\" is ready to download.", { title: G.trim() }),
|
|
68
|
+
variant: "success"
|
|
69
|
+
}), W(!1), K(""), J("FINANCIAL");
|
|
70
|
+
} finally {
|
|
71
|
+
e && B(!1);
|
|
68
72
|
}
|
|
69
73
|
}, te = async (e, t) => {
|
|
70
74
|
let n = await ee(e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ReportsPage.js","names":[],"sources":["../../../../src/healthybowl/pages/analytics/ReportsPage.tsx"],"sourcesContent":["import { useState } from 'react';\nimport { Download, FileText, Plus } from 'lucide-react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { Button, Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@burdenoff/fe-libs/ui';\nimport {\n PageLayout,\n DataTable,\n StatusBadge,\n FilterBar,\n Modal,\n LoadingSkeleton,\n EmptyState,\n ErrorState,\n} from '../../components';\nimport { ToastContainer } from '../../components/Toast';\nimport { useToast } from '../../hooks/useToast';\nimport { useHealthyBowlData } from '../../hooks/useHealthyBowlData';\nimport {\n GENERATABLE_REPORT_TYPES,\n isGeneratableReportType,\n type GeneratableReportType,\n useAnalyticsReports,\n} from '../../hooks/useAnalyticsReports';\nimport { formatDate } from '../../utils/helpers';\nimport { downloadBase64 } from '../../utils/download';\n\nconst typeVariantMap: Record<string, 'info' | 'success' | 'warning' | 'default' | 'muted'> = {\n financial: 'success',\n crop: 'info',\n livestock: 'warning',\n weather: 'default',\n marketplace: 'muted',\n};\n\nconst statusVariantMap: Record<string, 'success' | 'warning' | 'info'> = {\n ready: 'success',\n generating: 'warning',\n scheduled: 'info',\n};\n\nexport function ReportsPage() {\n const { t } = useI18n();\n const { analyticsReports, loading, errors, refetch } = useHealthyBowlData();\n const { generate, download, downloadingIds } = useAnalyticsReports();\n // Covers the WHOLE flow — generate, refetch, close. The hook's own `generating` clears as soon\n // as the mutation resolves, which left the button live during the refetch: long enough on a farm\n // connection for a second click to lodge a duplicate report.\n const [submitting, setSubmitting] = useState(false);\n\n const [search, setSearch] = useState('');\n const [showGenerateModal, setShowGenerateModal] = useState(false);\n const [reportTitle, setReportTitle] = useState('');\n // Defaults to the type most farms have data for; CROP needs recorded harvests.\n const [reportType, setReportType] = useState<GeneratableReportType>('FINANCIAL');\n const { toasts, toast, dismiss } = useToast();\n\n const handleReportTypeChange = (value: string): void => {\n if (isGeneratableReportType(value)) setReportType(value);\n };\n\n const handleGenerateReport = async () => {\n if (submitting) return;\n if (!reportTitle.trim()) {\n toast({\n title: t('healthybowl.analytics.reports.toast.missingTitle.title', 'Missing Title'),\n description: t('healthybowl.analytics.reports.toast.missingTitle.description', 'Please enter a report title'),\n variant: 'warning',\n });\n return;\n }\n // BOFF-6022 — a real generator replaces the \"not part of this release\" toast.\n setSubmitting(true);\n try {\n const result = await generate({ title: reportTitle.trim(), type: reportType });\n if (!result.ok) {\n // Surfaces the server's own sentence, which for an unsupported type names the ones that DO\n // work — more use than a generic failure.\n toast({\n title: t('healthybowl.analytics.reports.toast.failed.title', 'Could not generate the report'),\n description: result.message,\n variant: 'error',\n });\n return;\n }\n // The report was already persisted. A failed read must not turn that success into an unhandled\n // rejection or leave the dialog open ready to create a duplicate; navigation retries the list.\n await refetch().catch(() => undefined);\n toast({\n title: t('healthybowl.analytics.reports.toast.generated.title', 'Report ready'),\n description: t(\n 'healthybowl.analytics.reports.toast.generated.description',\n '\"{{title}}\" is ready to download.',\n {\n title: reportTitle.trim(),\n }\n ),\n variant: 'success',\n });\n setShowGenerateModal(false);\n setReportTitle('');\n setReportType('FINANCIAL');\n } finally {\n setSubmitting(false);\n }\n };\n\n const handleDownload = async (reportId: string, reportTitleForToast: string) => {\n const result = await download(reportId);\n if (!result.ok) {\n toast({\n title: t('healthybowl.analytics.reports.toast.downloadFailed.title', 'Could not download the report'),\n description: result.message,\n variant: 'error',\n });\n return;\n }\n downloadBase64(result.payload.contentBase64, result.payload.filename, result.payload.mimeType);\n toast({\n title: t('healthybowl.analytics.reports.toast.downloaded.title', 'Downloaded'),\n description: reportTitleForToast,\n variant: 'success',\n });\n };\n\n const filtered = analyticsReports.filter(\n (r) =>\n (r.title ?? '').toLowerCase().includes(search.toLowerCase()) ||\n (r.type ?? '').toLowerCase().includes(search.toLowerCase())\n );\n\n const columns = [\n {\n key: 'title',\n header: t('healthybowl.analytics.reports.table.headers.title', 'Report Title'),\n render: (r: (typeof analyticsReports)[0]) => (\n <div className=\"flex items-center gap-2\">\n <FileText className=\"h-4 w-4 text-text-secondary\" />\n <span className=\"font-medium text-text-primary\">{r.title}</span>\n </div>\n ),\n },\n {\n key: 'type',\n header: t('healthybowl.analytics.reports.table.headers.type', 'Type'),\n render: (r: (typeof analyticsReports)[0]) => (\n <StatusBadge label={r.type} variant={typeVariantMap[r.type] ?? 'default'} />\n ),\n },\n {\n key: 'createdAt',\n header: t('healthybowl.analytics.reports.table.headers.created', 'Created'),\n render: (r: (typeof analyticsReports)[0]) => (\n <span className=\"text-text-secondary\">{formatDate(r.createdAt)}</span>\n ),\n },\n {\n key: 'period',\n header: t('healthybowl.analytics.reports.table.headers.period', 'Period'),\n },\n {\n key: 'status',\n header: t('healthybowl.analytics.reports.table.headers.status', 'Status'),\n render: (r: (typeof analyticsReports)[0]) => (\n <StatusBadge label={r.status} variant={statusVariantMap[r.status ?? 'unknown'] ?? 'default'} dot />\n ),\n },\n {\n key: 'actions',\n header: t('healthybowl.analytics.reports.table.headers.actions', 'Actions'),\n render: (r: (typeof analyticsReports)[0]) =>\n // Only READY rows are downloadable. A download button on a row with no document behind it\n // is the same broken promise as the toast this ticket removes.\n r.status === 'ready' ? (\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"gap-1.5\"\n disabled={downloadingIds.has(r.id)}\n onClick={() => void handleDownload(r.id, r.title)}\n >\n <Download className=\"h-3.5 w-3.5\" />\n {downloadingIds.has(r.id)\n ? t('healthybowl.analytics.reports.table.downloading', 'Preparing…')\n : t('healthybowl.analytics.reports.table.download', 'Download')}\n </Button>\n ) : null,\n },\n ];\n\n return (\n <PageLayout\n title={t('healthybowl.analytics.reports.title', 'Reports')}\n description={t('healthybowl.analytics.reports.description', 'Generate and view farm reports')}\n purpose=\"Generate and revisit formal reports — season summaries, financials, compliance records — that you can save, print, or hand to a buyer, lender, or certifier when they need proof on paper.\"\n actions={\n <Button onClick={() => setShowGenerateModal(true)}>\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.analytics.reports.actions.generate', 'Generate New Report')}\n </Button>\n }\n >\n {loading && analyticsReports.length === 0 ? (\n <LoadingSkeleton variant=\"table\" count={4} />\n ) : analyticsReports.length === 0 ? (\n errors.analytics ? (\n <ErrorState />\n ) : (\n <EmptyState\n illustration=\"empty-files\"\n title={t('healthybowl.analytics.reports.emptyState.title', 'No reports yet')}\n description={t(\n 'healthybowl.analytics.reports.emptyState.description',\n \"Generated farm reports will appear here once they're available.\"\n )}\n />\n )\n ) : (\n <>\n <FilterBar\n searchValue={search}\n onSearchChange={setSearch}\n searchPlaceholder={t('healthybowl.analytics.reports.search.placeholder', 'Search reports...')}\n />\n\n <DataTable columns={columns} data={filtered} keyField=\"id\" />\n </>\n )}\n\n {/* Generate Report Modal */}\n <Modal\n open={showGenerateModal}\n onClose={() => setShowGenerateModal(false)}\n title={t('healthybowl.analytics.reports.modal.title', 'Generate New Report')}\n description={t('healthybowl.analytics.reports.modal.description', 'Configure and generate a new farm report')}\n size=\"md\"\n footer={\n <>\n <Button variant=\"outline\" onClick={() => setShowGenerateModal(false)}>\n {t('healthybowl.common.cancel', 'Cancel')}\n </Button>\n <Button onClick={() => void handleGenerateReport()} disabled={submitting}>\n {submitting\n ? t('healthybowl.analytics.reports.modal.generating', 'Generating…')\n : t('healthybowl.analytics.reports.modal.generate', 'Generate')}\n </Button>\n </>\n }\n >\n <div className=\"space-y-4\">\n <div>\n <label className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.analytics.reports.form.fields.title.label', 'Report Title')}\n </label>\n <input\n type=\"text\"\n value={reportTitle}\n onChange={(e) => setReportTitle(e.target.value)}\n placeholder={t(\n 'healthybowl.analytics.reports.form.fields.title.placeholder',\n 'e.g., Q1 Crop Performance'\n )}\n className=\"h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]\"\n />\n </div>\n <div>\n <label className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.analytics.reports.form.fields.type.label', 'Report Type')}\n </label>\n <Select value={reportType} onValueChange={handleReportTypeChange}>\n <SelectTrigger className=\"h-9 w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {/* Only the types the server can actually build (BOFF-6022). Offering LIVESTOCK,\n WEATHER or MARKETPLACE would let a farmer pick something that is refused on\n submit — the \"not available yet\" toast in a new costume. */}\n {GENERATABLE_REPORT_TYPES.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {t(option.labelKey, option.labelFallback)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n </Modal>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BA,IAAM,IAAuF;CAC3F,WAAW;CACX,MAAM;CACN,WAAW;CACX,SAAS;CACT,aAAa;AACf,GAEM,IAAmE;CACvE,OAAO;CACP,YAAY;CACZ,WAAW;AACb;AAEA,SAAgB,IAAc;CAC5B,IAAM,EAAE,SAAM,EAAQ,GAChB,EAAE,qBAAkB,YAAS,WAAQ,eAAY,EAAmB,GACpE,EAAE,aAAU,cAAU,sBAAmB,EAAoB,GAI7D,CAAC,GAAY,KAAiB,EAAS,EAAK,GAE5C,CAAC,GAAQ,KAAa,EAAS,EAAE,GACjC,CAAC,GAAmB,KAAwB,EAAS,EAAK,GAC1D,CAAC,GAAa,KAAkB,EAAS,EAAE,GAE3C,CAAC,GAAY,KAAiB,EAA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AAC,SAAD;MACE,MAAK;MACL,OAAO;MACP,WAAW,MAAM,EAAe,EAAE,OAAO,KAAK;MAC9C,aAAa,EACX,+DACA,2BACF;MACA,WAAU;KACX,CAAA,CACE,EAAA,CAAA,GACL,kBAAC,OAAD,EAAA,UAAA,CACE,kBAAC,SAAD;MAAO,WAAU;gBACd,EAAE,wDAAwD,aAAa;KACnE,CAAA,GACP,kBAAC,GAAD;MAAQ,OAAO;MAAY,eAAe;gBAA1C,CACE,kBAAC,GAAD;OAAe,WAAU;iBACvB,kBAAC,GAAD,CAAc,CAAA;MACD,CAAA,GACf,kBAAC,GAAD,EAAA,UAIG,EAAyB,KAAK,MAC7B,kBAAC,GAAD;OAA+B,OAAO,EAAO;iBAC1C,EAAE,EAAO,UAAU,EAAO,aAAa;MAC9B,GAFK,EAAO,KAEZ,CACb,EACY,CAAA,CACT;OACL,EAAA,CAAA,CACF;;GACA,CAAA;GAEP,kBAAC,GAAD;IAAwB;IAAQ,WAAW;GAAU,CAAA;EAC3C;;AAEhB"}
|
|
1
|
+
{"version":3,"file":"ReportsPage.js","names":[],"sources":["../../../../src/healthybowl/pages/analytics/ReportsPage.tsx"],"sourcesContent":["import { useState } from 'react';\nimport { Download, FileText, Plus } from 'lucide-react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { Button, Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '@burdenoff/fe-libs/ui';\nimport {\n PageLayout,\n DataTable,\n StatusBadge,\n FilterBar,\n Modal,\n LoadingSkeleton,\n EmptyState,\n ErrorState,\n} from '../../components';\nimport { ToastContainer } from '../../components/Toast';\nimport { useToast } from '../../hooks/useToast';\nimport { useHealthyBowlData } from '../../hooks/useHealthyBowlData';\nimport {\n GENERATABLE_REPORT_TYPES,\n isGeneratableReportType,\n type GeneratableReportType,\n useAnalyticsReports,\n} from '../../hooks/useAnalyticsReports';\nimport { formatDate } from '../../utils/helpers';\nimport { downloadBase64 } from '../../utils/download';\n\nconst typeVariantMap: Record<string, 'info' | 'success' | 'warning' | 'default' | 'muted'> = {\n financial: 'success',\n crop: 'info',\n livestock: 'warning',\n weather: 'default',\n marketplace: 'muted',\n};\n\nconst statusVariantMap: Record<string, 'success' | 'warning' | 'info'> = {\n ready: 'success',\n generating: 'warning',\n scheduled: 'info',\n};\n\nexport function ReportsPage() {\n const { t } = useI18n();\n const { analyticsReports, loading, errors, refetch } = useHealthyBowlData();\n const { generate, download, downloadingIds } = useAnalyticsReports();\n // Covers the WHOLE flow — generate, refetch, close. The hook's own `generating` clears as soon\n // as the mutation resolves, which left the button live during the refetch: long enough on a farm\n // connection for a second click to lodge a duplicate report.\n const [submitting, setSubmitting] = useState(false);\n\n const [search, setSearch] = useState('');\n const [showGenerateModal, setShowGenerateModal] = useState(false);\n const [reportTitle, setReportTitle] = useState('');\n // Defaults to the type most farms have data for; CROP needs recorded harvests.\n const [reportType, setReportType] = useState<GeneratableReportType>('FINANCIAL');\n const { toasts, toast, dismiss } = useToast();\n\n const handleReportTypeChange = (value: string): void => {\n if (isGeneratableReportType(value)) setReportType(value);\n };\n\n const handleGenerateReport = async () => {\n if (submitting) return;\n if (!reportTitle.trim()) {\n toast({\n title: t('healthybowl.analytics.reports.toast.missingTitle.title', 'Missing Title'),\n description: t('healthybowl.analytics.reports.toast.missingTitle.description', 'Please enter a report title'),\n variant: 'warning',\n });\n return;\n }\n // BOFF-6022 — a real generator replaces the \"not part of this release\" toast.\n setSubmitting(true);\n // A same-tick duplicate reaches the hook before React can apply `disabled`. That ignored caller\n // must not release the first caller's page-level lock while it is still refetching.\n let releaseSubmissionLock = true;\n try {\n const result = await generate({ title: reportTitle.trim(), type: reportType });\n if (!result.started) {\n releaseSubmissionLock = false;\n return;\n }\n if (!result.ok) {\n // Surfaces the server's own sentence, which for an unsupported type names the ones that DO\n // work — more use than a generic failure.\n toast({\n title: t('healthybowl.analytics.reports.toast.failed.title', 'Could not generate the report'),\n description: result.message,\n variant: 'error',\n });\n return;\n }\n // The report was already persisted. A failed read must not turn that success into an unhandled\n // rejection or leave the dialog open ready to create a duplicate; navigation retries the list.\n await refetch().catch(() => undefined);\n toast({\n title: t('healthybowl.analytics.reports.toast.generated.title', 'Report ready'),\n description: t(\n 'healthybowl.analytics.reports.toast.generated.description',\n '\"{{title}}\" is ready to download.',\n {\n title: reportTitle.trim(),\n }\n ),\n variant: 'success',\n });\n setShowGenerateModal(false);\n setReportTitle('');\n setReportType('FINANCIAL');\n } finally {\n if (releaseSubmissionLock) setSubmitting(false);\n }\n };\n\n const handleDownload = async (reportId: string, reportTitleForToast: string) => {\n const result = await download(reportId);\n if (!result.ok) {\n toast({\n title: t('healthybowl.analytics.reports.toast.downloadFailed.title', 'Could not download the report'),\n description: result.message,\n variant: 'error',\n });\n return;\n }\n downloadBase64(result.payload.contentBase64, result.payload.filename, result.payload.mimeType);\n toast({\n title: t('healthybowl.analytics.reports.toast.downloaded.title', 'Downloaded'),\n description: reportTitleForToast,\n variant: 'success',\n });\n };\n\n const filtered = analyticsReports.filter(\n (r) =>\n (r.title ?? '').toLowerCase().includes(search.toLowerCase()) ||\n (r.type ?? '').toLowerCase().includes(search.toLowerCase())\n );\n\n const columns = [\n {\n key: 'title',\n header: t('healthybowl.analytics.reports.table.headers.title', 'Report Title'),\n render: (r: (typeof analyticsReports)[0]) => (\n <div className=\"flex items-center gap-2\">\n <FileText className=\"h-4 w-4 text-text-secondary\" />\n <span className=\"font-medium text-text-primary\">{r.title}</span>\n </div>\n ),\n },\n {\n key: 'type',\n header: t('healthybowl.analytics.reports.table.headers.type', 'Type'),\n render: (r: (typeof analyticsReports)[0]) => (\n <StatusBadge label={r.type} variant={typeVariantMap[r.type] ?? 'default'} />\n ),\n },\n {\n key: 'createdAt',\n header: t('healthybowl.analytics.reports.table.headers.created', 'Created'),\n render: (r: (typeof analyticsReports)[0]) => (\n <span className=\"text-text-secondary\">{formatDate(r.createdAt)}</span>\n ),\n },\n {\n key: 'period',\n header: t('healthybowl.analytics.reports.table.headers.period', 'Period'),\n },\n {\n key: 'status',\n header: t('healthybowl.analytics.reports.table.headers.status', 'Status'),\n render: (r: (typeof analyticsReports)[0]) => (\n <StatusBadge label={r.status} variant={statusVariantMap[r.status ?? 'unknown'] ?? 'default'} dot />\n ),\n },\n {\n key: 'actions',\n header: t('healthybowl.analytics.reports.table.headers.actions', 'Actions'),\n render: (r: (typeof analyticsReports)[0]) =>\n // Only READY rows are downloadable. A download button on a row with no document behind it\n // is the same broken promise as the toast this ticket removes.\n r.status === 'ready' ? (\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"gap-1.5\"\n disabled={downloadingIds.has(r.id)}\n onClick={() => void handleDownload(r.id, r.title)}\n >\n <Download className=\"h-3.5 w-3.5\" />\n {downloadingIds.has(r.id)\n ? t('healthybowl.analytics.reports.table.downloading', 'Preparing…')\n : t('healthybowl.analytics.reports.table.download', 'Download')}\n </Button>\n ) : null,\n },\n ];\n\n return (\n <PageLayout\n title={t('healthybowl.analytics.reports.title', 'Reports')}\n description={t('healthybowl.analytics.reports.description', 'Generate and view farm reports')}\n purpose=\"Generate and revisit formal reports — season summaries, financials, compliance records — that you can save, print, or hand to a buyer, lender, or certifier when they need proof on paper.\"\n actions={\n <Button onClick={() => setShowGenerateModal(true)}>\n <Plus className=\"h-4 w-4\" />\n {t('healthybowl.analytics.reports.actions.generate', 'Generate New Report')}\n </Button>\n }\n >\n {loading && analyticsReports.length === 0 ? (\n <LoadingSkeleton variant=\"table\" count={4} />\n ) : analyticsReports.length === 0 ? (\n errors.analytics ? (\n <ErrorState />\n ) : (\n <EmptyState\n illustration=\"empty-files\"\n title={t('healthybowl.analytics.reports.emptyState.title', 'No reports yet')}\n description={t(\n 'healthybowl.analytics.reports.emptyState.description',\n \"Generated farm reports will appear here once they're available.\"\n )}\n />\n )\n ) : (\n <>\n <FilterBar\n searchValue={search}\n onSearchChange={setSearch}\n searchPlaceholder={t('healthybowl.analytics.reports.search.placeholder', 'Search reports...')}\n />\n\n <DataTable columns={columns} data={filtered} keyField=\"id\" />\n </>\n )}\n\n {/* Generate Report Modal */}\n <Modal\n open={showGenerateModal}\n onClose={() => setShowGenerateModal(false)}\n title={t('healthybowl.analytics.reports.modal.title', 'Generate New Report')}\n description={t('healthybowl.analytics.reports.modal.description', 'Configure and generate a new farm report')}\n size=\"md\"\n footer={\n <>\n <Button variant=\"outline\" onClick={() => setShowGenerateModal(false)}>\n {t('healthybowl.common.cancel', 'Cancel')}\n </Button>\n <Button onClick={() => void handleGenerateReport()} disabled={submitting}>\n {submitting\n ? t('healthybowl.analytics.reports.modal.generating', 'Generating…')\n : t('healthybowl.analytics.reports.modal.generate', 'Generate')}\n </Button>\n </>\n }\n >\n <div className=\"space-y-4\">\n <div>\n <label className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.analytics.reports.form.fields.title.label', 'Report Title')}\n </label>\n <input\n type=\"text\"\n value={reportTitle}\n onChange={(e) => setReportTitle(e.target.value)}\n placeholder={t(\n 'healthybowl.analytics.reports.form.fields.title.placeholder',\n 'e.g., Q1 Crop Performance'\n )}\n className=\"h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]\"\n />\n </div>\n <div>\n <label className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.analytics.reports.form.fields.type.label', 'Report Type')}\n </label>\n <Select value={reportType} onValueChange={handleReportTypeChange}>\n <SelectTrigger className=\"h-9 w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {/* Only the types the server can actually build (BOFF-6022). Offering LIVESTOCK,\n WEATHER or MARKETPLACE would let a farmer pick something that is refused on\n submit — the \"not available yet\" toast in a new costume. */}\n {GENERATABLE_REPORT_TYPES.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {t(option.labelKey, option.labelFallback)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n </Modal>\n\n <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,WAAW;GAAU,CAAA;EAC3C;;AAEhB"}
|
|
@@ -82,34 +82,38 @@ var F = {
|
|
|
82
82
|
value: ne
|
|
83
83
|
}
|
|
84
84
|
], $ = async (e) => {
|
|
85
|
-
if (
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
description: b("healthybowl.financial.reports.toast.generated.description", "\"{{title}}\" ({{period}}) is ready under Analytics → Reports.", {
|
|
105
|
-
title: e,
|
|
106
|
-
period: b(n?.labelKey ?? "", n?.labelFallback ?? "")
|
|
107
|
-
}),
|
|
108
|
-
variant: "success"
|
|
85
|
+
if (B) return;
|
|
86
|
+
V(!0);
|
|
87
|
+
let t = !0;
|
|
88
|
+
try {
|
|
89
|
+
let n = g(/* @__PURE__ */ new Date()), r = n.find((e) => e.value === q) ?? n[0], i = await z({
|
|
90
|
+
title: e,
|
|
91
|
+
type: "FINANCIAL",
|
|
92
|
+
startDate: r?.startDate,
|
|
93
|
+
endDate: r?.endDate
|
|
94
|
+
});
|
|
95
|
+
if (!i.started) {
|
|
96
|
+
t = !1;
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (!i.ok) {
|
|
100
|
+
G({
|
|
101
|
+
title: b("healthybowl.financial.reports.toast.generateFailed.title", "Could not generate the report"),
|
|
102
|
+
description: i.message,
|
|
103
|
+
variant: "error"
|
|
109
104
|
});
|
|
110
|
-
|
|
111
|
-
V(!1);
|
|
105
|
+
return;
|
|
112
106
|
}
|
|
107
|
+
await R().catch(() => void 0), G({
|
|
108
|
+
title: b("healthybowl.financial.reports.toast.generated.title", "Report ready"),
|
|
109
|
+
description: b("healthybowl.financial.reports.toast.generated.description", "\"{{title}}\" ({{period}}) is ready under Analytics → Reports.", {
|
|
110
|
+
title: e,
|
|
111
|
+
period: b(r?.labelKey ?? "", r?.labelFallback ?? "")
|
|
112
|
+
}),
|
|
113
|
+
variant: "success"
|
|
114
|
+
});
|
|
115
|
+
} finally {
|
|
116
|
+
t && V(!1);
|
|
113
117
|
}
|
|
114
118
|
}, re = async (e) => {
|
|
115
119
|
await $(U.find((t) => t.id === e)?.title ?? b("healthybowl.financial.reports.toast.fallbackReport", "Financial report"));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FinancialReportsPage.js","names":[],"sources":["../../../../src/healthybowl/pages/financial/FinancialReportsPage.tsx"],"sourcesContent":["import { useState } from 'react';\nimport { BarChart3, FileDown, FileText, TrendingUp, Wallet, Clock, PieChart as PieChartIcon } from 'lucide-react';\nimport { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@burdenoff/fe-libs/ui';\nimport { PageLayout, ChartCard, LoadingSkeleton, EmptyState, ErrorState } from '../../components';\nimport { ToastContainer } from '../../components/Toast';\nimport { useToast } from '../../hooks/useToast';\nimport { useHealthyBowlData } from '../../hooks/useHealthyBowlData';\nimport { reportPeriodOptions, useAnalyticsReports } from '../../hooks/useAnalyticsReports';\nimport { formatCurrency, formatCompactCurrency, HB_DEFAULT_CURRENCY } from '../../utils/helpers';\n\ntype ReportCategory = 'pl' | 'cashflow' | 'budget' | 'tax';\n\ninterface ReportType {\n id: string;\n title: string;\n description: string;\n category: ReportCategory;\n}\n\nconst categoryIcons: Record<ReportCategory, typeof TrendingUp> = {\n pl: TrendingUp,\n cashflow: BarChart3,\n budget: Wallet,\n tax: FileText,\n};\n\nexport const FinancialReportsPage = () => {\n const { t } = useI18n();\n const { transactions, invoices, revenueChartData, loading, errors, refetch } = useHealthyBowlData();\n const { generate } = useAnalyticsReports();\n // Same reason as ReportsPage: the hook's flag clears at the mutation, not at the end of the flow.\n const [submitting, setSubmitting] = useState(false);\n // Derived from the current render date; the submission path recomputes again to stay correct if\n // this screen has been open across a day, quarter, or year boundary.\n const periodOptions = reportPeriodOptions(new Date());\n\n // Templates provide a quick CSV of current financial metrics and a real generated financial PDF.\n // No fabricated \"last generated\" dates or fixed periods — those would imply runs that never happened.\n const reportTypes: ReportType[] = [\n {\n id: 'rpt-pl',\n title: t('healthybowl.financial.reports.types.pl.title', 'Profit & Loss Statement'),\n description: t('healthybowl.financial.reports.types.pl.description', 'Revenue, expenses, and net income summary'),\n category: 'pl',\n },\n {\n id: 'rpt-cf',\n title: t('healthybowl.financial.reports.types.cashflow.title', 'Cash Flow Report'),\n description: t(\n 'healthybowl.financial.reports.types.cashflow.description',\n 'Cash inflows, outflows, and closing balance'\n ),\n category: 'cashflow',\n },\n {\n id: 'rpt-ba',\n title: t('healthybowl.financial.reports.types.budget.title', 'Budget vs Actual'),\n description: t(\n 'healthybowl.financial.reports.types.budget.description',\n 'Budget allocation vs actual spending by category'\n ),\n category: 'budget',\n },\n {\n id: 'rpt-tax',\n title: t('healthybowl.financial.reports.types.tax.title', 'Tax Summary'),\n description: t(\n 'healthybowl.financial.reports.types.tax.description',\n 'Tax collected, paid, and outstanding for the period'\n ),\n category: 'tax',\n },\n {\n id: 'rpt-ar',\n title: t('healthybowl.financial.reports.types.receivableAging.title', 'Accounts Receivable Aging'),\n description: t(\n 'healthybowl.financial.reports.types.receivableAging.description',\n 'Outstanding invoices grouped by aging buckets'\n ),\n category: 'cashflow',\n },\n ];\n\n const { toasts, toast, dismiss } = useToast();\n const [selectedPeriod, setSelectedPeriod] = useState('ytd');\n\n const totalRevenue = transactions.filter((t) => t.type === 'income').reduce((s, t) => s + t.amount, 0);\n const totalExpenses = transactions.filter((t) => t.type === 'expense').reduce((s, t) => s + t.amount, 0);\n const netIncome = totalRevenue - totalExpenses;\n const accountsReceivable = invoices\n .filter((i) => i.status === 'sent' || i.status === 'overdue')\n .reduce((s, i) => s + i.total, 0);\n\n // Only metrics with a real data source. Cash-on-hand and tax-liability were dropped — they were\n // synthesized from arbitrary multipliers (netIncome*0.775, revenue*0.0736), not real balances/tax.\n // No period-over-period deltas: these are all-time totals with no comparable prior period here.\n const financialMetrics = [\n {\n id: 'grossRevenue',\n label: t('healthybowl.financial.reports.metrics.grossRevenue', 'Gross Revenue'),\n value: totalRevenue,\n },\n {\n id: 'operatingExpenses',\n label: t('healthybowl.financial.reports.metrics.operatingExpenses', 'Operating Expenses'),\n value: totalExpenses,\n },\n { id: 'netIncome', label: t('healthybowl.financial.reports.metrics.netIncome', 'Net Income'), value: netIncome },\n {\n id: 'accountsReceivable',\n label: t('healthybowl.financial.reports.metrics.accountsReceivable', 'Accounts Receivable'),\n value: accountsReceivable,\n },\n ];\n\n // BOFF-6022 — a real generator replaces the \"not available yet\" toast. Everything here is a\n // financial report, so the type is fixed; the analytics Reports page owns the type choice.\n const generateFinancialReport = async (title: string) => {\n if (submitting) return;\n setSubmitting(true);\n try {\n // Compute at submission too: a page left open across midnight must not generate yesterday's\n // year-to-date or previous-quarter range.\n const currentPeriodOptions = reportPeriodOptions(new Date());\n const period = currentPeriodOptions.find((o) => o.value === selectedPeriod) ?? currentPeriodOptions[0];\n const result = await generate({\n title,\n type: 'FINANCIAL',\n startDate: period?.startDate,\n endDate: period?.endDate,\n });\n if (!result.ok) {\n toast({\n title: t('healthybowl.financial.reports.toast.generateFailed.title', 'Could not generate the report'),\n description: result.message,\n variant: 'error',\n });\n return;\n }\n // The report is already persisted. A transient read failure must not suppress the success\n // toast or leak an unhandled rejection that invites the farmer to submit it again.\n await refetch().catch(() => undefined);\n toast({\n title: t('healthybowl.financial.reports.toast.generated.title', 'Report ready'),\n description: t(\n 'healthybowl.financial.reports.toast.generated.description',\n '\"{{title}}\" ({{period}}) is ready under Analytics → Reports.',\n { title, period: t(period?.labelKey ?? '', period?.labelFallback ?? '') }\n ),\n variant: 'success',\n });\n } finally {\n setSubmitting(false);\n }\n };\n\n const handleGenerate = async (id: string) => {\n const report = reportTypes.find((r) => r.id === id);\n await generateFinancialReport(\n report?.title ?? t('healthybowl.financial.reports.toast.fallbackReport', 'Financial report')\n );\n };\n\n const handleDownload = (report: ReportType) => {\n const headers = ['Metric', 'Value'];\n const rows = financialMetrics.map((m) => [m.label, String((m.value ?? 0).toFixed(2))]);\n const csv = [headers, ...rows].map((r) => r.map((c) => `\"${c}\"`).join(',')).join('\\n');\n const blob = new Blob([csv], { type: 'text/csv' });\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = `${(report.title ?? '').replace(/\\s+/g, '_')}.csv`;\n a.click();\n URL.revokeObjectURL(url);\n toast({\n title: t('healthybowl.financial.reports.toast.downloaded.title', 'Downloaded as CSV'),\n description: report.title,\n variant: 'success',\n });\n };\n\n const handleGenerateCustom = async () => {\n await generateFinancialReport(t('healthybowl.financial.reports.customTitle', 'Custom financial report'));\n };\n\n // Left honest on purpose. Scheduling needs a cron this service does not have, and the ticket's\n // build order puts it after \"there is something worth scheduling\" — which this PR only just\n // makes true. Replacing this toast with a button that silently does nothing would be worse than\n // the toast.\n const handleScheduleReport = () => {\n toast({\n title: t(\n 'healthybowl.financial.reports.toast.scheduleUnavailable.title',\n 'Report scheduling is not available yet'\n ),\n description: t(\n 'healthybowl.financial.reports.toast.scheduleUnavailable.description',\n 'Scheduled reports have no backend yet — nothing was scheduled. You can generate a report now instead.'\n ),\n variant: 'warning',\n });\n };\n\n // While the first load is still in flight and nothing has arrived yet, show skeletons in place\n // of the metric/chart body so the page never flashes zeros/blank/NaN sections.\n if (loading && transactions.length === 0 && invoices.length === 0 && revenueChartData.length === 0) {\n return (\n <PageLayout\n title={t('healthybowl.financial.reports.title', 'Financial Reports')}\n description={t(\n 'healthybowl.financial.reports.description',\n 'Generate, download, and schedule financial reports'\n )}\n >\n <LoadingSkeleton variant=\"card\" count={4} />\n </PageLayout>\n );\n }\n\n return (\n <PageLayout\n title={t('healthybowl.financial.reports.title', 'Financial Reports')}\n description={t('healthybowl.financial.reports.description', 'Generate, download, and schedule financial reports')}\n purpose=\"Produce the financial statements you need for tax, loans or your own books — and schedule them to arrive automatically. Hand these to your accountant or lender as proof of how the farm is doing.\"\n >\n {/* Report Generation Section */}\n <div className=\"rounded-lg border border-border-subtle bg-bg-surface p-5\">\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.financial.reports.generate.heading', 'Generate Report')}\n </h3>\n <p className=\"mt-0.5 text-xs text-text-secondary\">\n {t('healthybowl.financial.reports.generate.subtitle', 'Generate a financial PDF for the selected period')}\n </p>\n <div className=\"mt-4 flex flex-wrap items-end gap-3\">\n <div>\n <span className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.financial.reports.generate.fields.reportType.label', 'Report Type')}\n </span>\n <p className=\"h-9 rounded-md border border-border-subtle bg-bg-sunken px-3 py-2 text-sm text-text-primary\">\n {t('healthybowl.financial.reports.generate.types.financial', 'Financial')}\n </p>\n </div>\n <div>\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.financial.reports.generate.fields.period.label', 'Period')}\n </label>\n <Select value={selectedPeriod} onValueChange={setSelectedPeriod}>\n <SelectTrigger className=\"h-9 w-auto\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {periodOptions.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {t(option.labelKey, option.labelFallback)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div>\n <span className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.financial.reports.generate.fields.format.label', 'Format')}\n </span>\n <p className=\"h-9 rounded-md border border-border-subtle bg-bg-sunken px-3 py-2 text-sm text-text-primary\">\n {t('healthybowl.financial.reports.generate.formats.pdf', 'PDF')}\n </p>\n </div>\n <Button onClick={() => void handleGenerateCustom()} disabled={submitting}>\n <FileDown className=\"h-4 w-4\" />\n {t('healthybowl.financial.reports.generate.actions.generate', 'Generate')}\n </Button>\n <Button variant=\"outline\" onClick={handleScheduleReport}>\n <Clock className=\"h-4 w-4\" />\n {t('healthybowl.financial.reports.generate.actions.schedule', 'Schedule')}\n </Button>\n </div>\n </div>\n\n {/* Revenue Trend Chart */}\n <ChartCard\n title={t('healthybowl.financial.reports.revenueTrend.title', 'Revenue Trend')}\n description={t('healthybowl.financial.reports.revenueTrend.description', 'Monthly revenue over last 6 months')}\n >\n {revenueChartData.length === 0 ? (\n errors.financial ? (\n <ErrorState />\n ) : (\n <EmptyState\n illustration=\"empty-data\"\n title={t('healthybowl.financial.reports.revenueTrend.empty.title', 'No revenue data yet')}\n description={t(\n 'healthybowl.financial.reports.revenueTrend.empty.description',\n 'Revenue and expense trends will appear here once financial activity is recorded.'\n )}\n />\n )\n ) : (\n <ResponsiveContainer width=\"100%\" height={260}>\n <LineChart data={revenueChartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>\n <CartesianGrid strokeDasharray=\"3 3\" className=\"stroke-border\" />\n <XAxis dataKey=\"month\" className=\"text-xs\" tick={{ fill: 'currentColor' }} />\n <YAxis\n className=\"text-xs\"\n tick={{ fill: 'currentColor' }}\n tickFormatter={(v: number) => formatCompactCurrency(v, HB_DEFAULT_CURRENCY)}\n />\n <Tooltip\n formatter={(value: number) => formatCurrency(value, HB_DEFAULT_CURRENCY)}\n contentStyle={{\n backgroundColor: 'var(--color-card)',\n border: '1px solid var(--color-border)',\n borderRadius: '8px',\n }}\n labelStyle={{ color: 'var(--color-foreground)' }}\n />\n <Legend />\n <Line\n type=\"monotone\"\n dataKey=\"revenue\"\n name={t('healthybowl.financial.reports.revenueTrend.series.revenue', 'Revenue')}\n stroke=\"var(--color-success)\"\n strokeWidth={2}\n dot={{ r: 4, fill: 'var(--color-success)' }}\n activeDot={{ r: 6 }}\n />\n <Line\n type=\"monotone\"\n dataKey=\"expenses\"\n name={t('healthybowl.financial.reports.revenueTrend.series.expenses', 'Expenses')}\n stroke=\"var(--color-destructive)\"\n strokeWidth={2}\n dot={{ r: 4, fill: 'var(--color-destructive)' }}\n activeDot={{ r: 6 }}\n />\n </LineChart>\n </ResponsiveContainer>\n )}\n </ChartCard>\n\n {/* Key Financial Metrics */}\n <div className=\"rounded-lg border border-border-subtle bg-bg-surface p-5\">\n <div className=\"flex items-center gap-2\">\n <PieChartIcon className=\"h-4 w-4 text-text-secondary\" />\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.financial.reports.metrics.heading', 'Key Financial Metrics')}\n </h3>\n </div>\n {transactions.length === 0 && invoices.length === 0 ? (\n errors.financial ? (\n <ErrorState />\n ) : (\n <EmptyState\n illustration=\"empty-data\"\n title={t('healthybowl.financial.reports.metrics.empty.title', 'No financial data yet')}\n description={t(\n 'healthybowl.financial.reports.metrics.empty.description',\n 'Key metrics will appear here once transactions and invoices are recorded.'\n )}\n />\n )\n ) : (\n <div className=\"mt-4 grid grid-cols-2 gap-4 sm:grid-cols-4\">\n {financialMetrics.map((metric) => (\n <div key={metric.id} className=\"rounded-md bg-bg-sunken/50 p-3 text-center\">\n <p className=\"text-xs text-text-secondary\">{metric.label}</p>\n <p className=\"mt-1 text-lg font-bold text-text-primary\">\n {formatCurrency(metric.value, HB_DEFAULT_CURRENCY)}\n </p>\n </div>\n ))}\n </div>\n )}\n </div>\n\n {/* Pre-built Report Cards */}\n <div>\n <h3 className=\"mb-3 text-sm font-semibold text-text-primary\">\n {t('healthybowl.financial.reports.available.heading', 'Available Reports')}\n </h3>\n <div className=\"grid gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n {reportTypes.map((report) => {\n const Icon = categoryIcons[report.category];\n\n return (\n <div key={report.id} className=\"flex flex-col rounded-lg border border-border-subtle bg-bg-surface p-5\">\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-md bg-bg-sunken p-2\">\n <Icon className=\"h-5 w-5 text-text-secondary\" />\n </div>\n <div className=\"flex-1\">\n <h4 className=\"text-sm font-semibold text-text-primary\">{report.title}</h4>\n <p className=\"mt-0.5 text-xs text-text-secondary\">{report.description}</p>\n </div>\n </div>\n\n <div className=\"mt-auto flex items-center justify-end gap-2 pt-4\">\n {/* Download is a real CSV of the current metrics; full report generation is honestly disabled. */}\n <Button variant=\"outline\" size=\"sm\" onClick={() => handleDownload(report)}>\n <FileDown className=\"h-3.5 w-3.5\" />\n {t('healthybowl.financial.reports.available.actions.downloadCsv', 'Download CSV')}\n </Button>\n <Button size=\"sm\" onClick={() => void handleGenerate(report.id)} disabled={submitting}>\n {t('healthybowl.financial.reports.available.actions.generate', 'Generate')}\n </Button>\n </div>\n </div>\n );\n })}\n </div>\n </div>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,IAA2D;CAC/D,IAAI;CACJ,UAAU;CACV,QAAQ;CACR,KAAK;AACP,GAEa,UAA6B;CACxC,IAAM,EAAE,SAAM,EAAQ,GAChB,EAAE,iBAAc,aAAU,qBAAkB,YAAS,WAAQ,eAAY,EAAmB,GAC5F,EAAE,gBAAa,EAAoB,GAEnC,CAAC,GAAY,KAAiB,EAAS,EAAK,GAG5C,IAAgB,kBAAoB,IAAI,KAAK,CAAC,GAI9C,IAA4B;EAChC;GACE,IAAI;GACJ,OAAO,EAAE,gDAAgD,yBAAyB;GAClF,aAAa,EAAE,sDAAsD,2CAA2C;GAChH,UAAU;EACZ;EACA;GACE,IAAI;GACJ,OAAO,EAAE,sDAAsD,kBAAkB;GACjF,aAAa,EACX,4DACA,6CACF;GACA,UAAU;EACZ;EACA;GACE,IAAI;GACJ,OAAO,EAAE,oDAAoD,kBAAkB;GAC/E,aAAa,EACX,0DACA,kDACF;GACA,UAAU;EACZ;EACA;GACE,IAAI;GACJ,OAAO,EAAE,iDAAiD,aAAa;GACvE,aAAa,EACX,uDACA,qDACF;GACA,UAAU;EACZ;EACA;GACE,IAAI;GACJ,OAAO,EA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BAAC,OAAD;QAAK,WAAU;kBACb,kBAAC,GAAD,EAAM,WAAU,8BAA+B,CAAA;OAC5C,CAAA,GACL,kBAAC,OAAD;QAAK,WAAU;kBAAf,CACE,kBAAC,MAAD;SAAI,WAAU;mBAA2C,EAAO;QAAU,CAAA,GAC1E,kBAAC,KAAD;SAAG,WAAU;mBAAsC,EAAO;QAAe,CAAA,CACtE;SACF;UAEL,kBAAC,OAAD;OAAK,WAAU;iBAAf,CAEE,kBAAC,GAAD;QAAQ,SAAQ;QAAU,MAAK;QAAK,eAAe,GAAe,CAAM;kBAAxE,CACE,kBAAC,GAAD,EAAU,WAAU,cAAe,CAAA,GAClC,EAAE,+DAA+D,cAAc,CAC1E;WACR,kBAAC,GAAD;QAAQ,MAAK;QAAK,eAAe,KAAK,GAAe,EAAO,EAAE;QAAG,UAAU;kBACxE,EAAE,4DAA4D,UAAU;OACnE,CAAA,CACL;QACF;QArBK,EAAO,EAqBZ;IAET,CAAC;GACE,CAAA,CACF,EAAA,CAAA;GAEL,kBAAC,GAAD;IAAwB;IAAQ,WAAW;GAAU,CAAA;EAC3C;;AAEhB"}
|
|
1
|
+
{"version":3,"file":"FinancialReportsPage.js","names":[],"sources":["../../../../src/healthybowl/pages/financial/FinancialReportsPage.tsx"],"sourcesContent":["import { useState } from 'react';\nimport { BarChart3, FileDown, FileText, TrendingUp, Wallet, Clock, PieChart as PieChartIcon } from 'lucide-react';\nimport { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@burdenoff/fe-libs/ui';\nimport { PageLayout, ChartCard, LoadingSkeleton, EmptyState, ErrorState } from '../../components';\nimport { ToastContainer } from '../../components/Toast';\nimport { useToast } from '../../hooks/useToast';\nimport { useHealthyBowlData } from '../../hooks/useHealthyBowlData';\nimport { reportPeriodOptions, useAnalyticsReports } from '../../hooks/useAnalyticsReports';\nimport { formatCurrency, formatCompactCurrency, HB_DEFAULT_CURRENCY } from '../../utils/helpers';\n\ntype ReportCategory = 'pl' | 'cashflow' | 'budget' | 'tax';\n\ninterface ReportType {\n id: string;\n title: string;\n description: string;\n category: ReportCategory;\n}\n\nconst categoryIcons: Record<ReportCategory, typeof TrendingUp> = {\n pl: TrendingUp,\n cashflow: BarChart3,\n budget: Wallet,\n tax: FileText,\n};\n\nexport const FinancialReportsPage = () => {\n const { t } = useI18n();\n const { transactions, invoices, revenueChartData, loading, errors, refetch } = useHealthyBowlData();\n const { generate } = useAnalyticsReports();\n // Same reason as ReportsPage: the hook's flag clears at the mutation, not at the end of the flow.\n const [submitting, setSubmitting] = useState(false);\n // Derived from the current render date; the submission path recomputes again to stay correct if\n // this screen has been open across a day, quarter, or year boundary.\n const periodOptions = reportPeriodOptions(new Date());\n\n // Templates provide a quick CSV of current financial metrics and a real generated financial PDF.\n // No fabricated \"last generated\" dates or fixed periods — those would imply runs that never happened.\n const reportTypes: ReportType[] = [\n {\n id: 'rpt-pl',\n title: t('healthybowl.financial.reports.types.pl.title', 'Profit & Loss Statement'),\n description: t('healthybowl.financial.reports.types.pl.description', 'Revenue, expenses, and net income summary'),\n category: 'pl',\n },\n {\n id: 'rpt-cf',\n title: t('healthybowl.financial.reports.types.cashflow.title', 'Cash Flow Report'),\n description: t(\n 'healthybowl.financial.reports.types.cashflow.description',\n 'Cash inflows, outflows, and closing balance'\n ),\n category: 'cashflow',\n },\n {\n id: 'rpt-ba',\n title: t('healthybowl.financial.reports.types.budget.title', 'Budget vs Actual'),\n description: t(\n 'healthybowl.financial.reports.types.budget.description',\n 'Budget allocation vs actual spending by category'\n ),\n category: 'budget',\n },\n {\n id: 'rpt-tax',\n title: t('healthybowl.financial.reports.types.tax.title', 'Tax Summary'),\n description: t(\n 'healthybowl.financial.reports.types.tax.description',\n 'Tax collected, paid, and outstanding for the period'\n ),\n category: 'tax',\n },\n {\n id: 'rpt-ar',\n title: t('healthybowl.financial.reports.types.receivableAging.title', 'Accounts Receivable Aging'),\n description: t(\n 'healthybowl.financial.reports.types.receivableAging.description',\n 'Outstanding invoices grouped by aging buckets'\n ),\n category: 'cashflow',\n },\n ];\n\n const { toasts, toast, dismiss } = useToast();\n const [selectedPeriod, setSelectedPeriod] = useState('ytd');\n\n const totalRevenue = transactions.filter((t) => t.type === 'income').reduce((s, t) => s + t.amount, 0);\n const totalExpenses = transactions.filter((t) => t.type === 'expense').reduce((s, t) => s + t.amount, 0);\n const netIncome = totalRevenue - totalExpenses;\n const accountsReceivable = invoices\n .filter((i) => i.status === 'sent' || i.status === 'overdue')\n .reduce((s, i) => s + i.total, 0);\n\n // Only metrics with a real data source. Cash-on-hand and tax-liability were dropped — they were\n // synthesized from arbitrary multipliers (netIncome*0.775, revenue*0.0736), not real balances/tax.\n // No period-over-period deltas: these are all-time totals with no comparable prior period here.\n const financialMetrics = [\n {\n id: 'grossRevenue',\n label: t('healthybowl.financial.reports.metrics.grossRevenue', 'Gross Revenue'),\n value: totalRevenue,\n },\n {\n id: 'operatingExpenses',\n label: t('healthybowl.financial.reports.metrics.operatingExpenses', 'Operating Expenses'),\n value: totalExpenses,\n },\n { id: 'netIncome', label: t('healthybowl.financial.reports.metrics.netIncome', 'Net Income'), value: netIncome },\n {\n id: 'accountsReceivable',\n label: t('healthybowl.financial.reports.metrics.accountsReceivable', 'Accounts Receivable'),\n value: accountsReceivable,\n },\n ];\n\n // BOFF-6022 — a real generator replaces the \"not available yet\" toast. Everything here is a\n // financial report, so the type is fixed; the analytics Reports page owns the type choice.\n const generateFinancialReport = async (title: string) => {\n if (submitting) return;\n setSubmitting(true);\n // The hook rejects a same-tick duplicate before React has rendered this button disabled. That\n // ignored invocation must not clear the lock owned by the request that actually started.\n let releaseSubmissionLock = true;\n try {\n // Compute at submission too: a page left open across midnight must not generate yesterday's\n // year-to-date or previous-quarter range.\n const currentPeriodOptions = reportPeriodOptions(new Date());\n const period = currentPeriodOptions.find((o) => o.value === selectedPeriod) ?? currentPeriodOptions[0];\n const result = await generate({\n title,\n type: 'FINANCIAL',\n startDate: period?.startDate,\n endDate: period?.endDate,\n });\n if (!result.started) {\n releaseSubmissionLock = false;\n return;\n }\n if (!result.ok) {\n toast({\n title: t('healthybowl.financial.reports.toast.generateFailed.title', 'Could not generate the report'),\n description: result.message,\n variant: 'error',\n });\n return;\n }\n // The report is already persisted. A transient read failure must not suppress the success\n // toast or leak an unhandled rejection that invites the farmer to submit it again.\n await refetch().catch(() => undefined);\n toast({\n title: t('healthybowl.financial.reports.toast.generated.title', 'Report ready'),\n description: t(\n 'healthybowl.financial.reports.toast.generated.description',\n '\"{{title}}\" ({{period}}) is ready under Analytics → Reports.',\n { title, period: t(period?.labelKey ?? '', period?.labelFallback ?? '') }\n ),\n variant: 'success',\n });\n } finally {\n if (releaseSubmissionLock) setSubmitting(false);\n }\n };\n\n const handleGenerate = async (id: string) => {\n const report = reportTypes.find((r) => r.id === id);\n await generateFinancialReport(\n report?.title ?? t('healthybowl.financial.reports.toast.fallbackReport', 'Financial report')\n );\n };\n\n const handleDownload = (report: ReportType) => {\n const headers = ['Metric', 'Value'];\n const rows = financialMetrics.map((m) => [m.label, String((m.value ?? 0).toFixed(2))]);\n const csv = [headers, ...rows].map((r) => r.map((c) => `\"${c}\"`).join(',')).join('\\n');\n const blob = new Blob([csv], { type: 'text/csv' });\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = `${(report.title ?? '').replace(/\\s+/g, '_')}.csv`;\n a.click();\n URL.revokeObjectURL(url);\n toast({\n title: t('healthybowl.financial.reports.toast.downloaded.title', 'Downloaded as CSV'),\n description: report.title,\n variant: 'success',\n });\n };\n\n const handleGenerateCustom = async () => {\n await generateFinancialReport(t('healthybowl.financial.reports.customTitle', 'Custom financial report'));\n };\n\n // Left honest on purpose. Scheduling needs a cron this service does not have, and the ticket's\n // build order puts it after \"there is something worth scheduling\" — which this PR only just\n // makes true. Replacing this toast with a button that silently does nothing would be worse than\n // the toast.\n const handleScheduleReport = () => {\n toast({\n title: t(\n 'healthybowl.financial.reports.toast.scheduleUnavailable.title',\n 'Report scheduling is not available yet'\n ),\n description: t(\n 'healthybowl.financial.reports.toast.scheduleUnavailable.description',\n 'Scheduled reports have no backend yet — nothing was scheduled. You can generate a report now instead.'\n ),\n variant: 'warning',\n });\n };\n\n // While the first load is still in flight and nothing has arrived yet, show skeletons in place\n // of the metric/chart body so the page never flashes zeros/blank/NaN sections.\n if (loading && transactions.length === 0 && invoices.length === 0 && revenueChartData.length === 0) {\n return (\n <PageLayout\n title={t('healthybowl.financial.reports.title', 'Financial Reports')}\n description={t(\n 'healthybowl.financial.reports.description',\n 'Generate, download, and schedule financial reports'\n )}\n >\n <LoadingSkeleton variant=\"card\" count={4} />\n </PageLayout>\n );\n }\n\n return (\n <PageLayout\n title={t('healthybowl.financial.reports.title', 'Financial Reports')}\n description={t('healthybowl.financial.reports.description', 'Generate, download, and schedule financial reports')}\n purpose=\"Produce the financial statements you need for tax, loans or your own books — and schedule them to arrive automatically. Hand these to your accountant or lender as proof of how the farm is doing.\"\n >\n {/* Report Generation Section */}\n <div className=\"rounded-lg border border-border-subtle bg-bg-surface p-5\">\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.financial.reports.generate.heading', 'Generate Report')}\n </h3>\n <p className=\"mt-0.5 text-xs text-text-secondary\">\n {t('healthybowl.financial.reports.generate.subtitle', 'Generate a financial PDF for the selected period')}\n </p>\n <div className=\"mt-4 flex flex-wrap items-end gap-3\">\n <div>\n <span className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.financial.reports.generate.fields.reportType.label', 'Report Type')}\n </span>\n <p className=\"h-9 rounded-md border border-border-subtle bg-bg-sunken px-3 py-2 text-sm text-text-primary\">\n {t('healthybowl.financial.reports.generate.types.financial', 'Financial')}\n </p>\n </div>\n <div>\n <label className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.financial.reports.generate.fields.period.label', 'Period')}\n </label>\n <Select value={selectedPeriod} onValueChange={setSelectedPeriod}>\n <SelectTrigger className=\"h-9 w-auto\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {periodOptions.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {t(option.labelKey, option.labelFallback)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div>\n <span className=\"mb-1 block text-xs font-medium text-text-secondary\">\n {t('healthybowl.financial.reports.generate.fields.format.label', 'Format')}\n </span>\n <p className=\"h-9 rounded-md border border-border-subtle bg-bg-sunken px-3 py-2 text-sm text-text-primary\">\n {t('healthybowl.financial.reports.generate.formats.pdf', 'PDF')}\n </p>\n </div>\n <Button onClick={() => void handleGenerateCustom()} disabled={submitting}>\n <FileDown className=\"h-4 w-4\" />\n {t('healthybowl.financial.reports.generate.actions.generate', 'Generate')}\n </Button>\n <Button variant=\"outline\" onClick={handleScheduleReport}>\n <Clock className=\"h-4 w-4\" />\n {t('healthybowl.financial.reports.generate.actions.schedule', 'Schedule')}\n </Button>\n </div>\n </div>\n\n {/* Revenue Trend Chart */}\n <ChartCard\n title={t('healthybowl.financial.reports.revenueTrend.title', 'Revenue Trend')}\n description={t('healthybowl.financial.reports.revenueTrend.description', 'Monthly revenue over last 6 months')}\n >\n {revenueChartData.length === 0 ? (\n errors.financial ? (\n <ErrorState />\n ) : (\n <EmptyState\n illustration=\"empty-data\"\n title={t('healthybowl.financial.reports.revenueTrend.empty.title', 'No revenue data yet')}\n description={t(\n 'healthybowl.financial.reports.revenueTrend.empty.description',\n 'Revenue and expense trends will appear here once financial activity is recorded.'\n )}\n />\n )\n ) : (\n <ResponsiveContainer width=\"100%\" height={260}>\n <LineChart data={revenueChartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>\n <CartesianGrid strokeDasharray=\"3 3\" className=\"stroke-border\" />\n <XAxis dataKey=\"month\" className=\"text-xs\" tick={{ fill: 'currentColor' }} />\n <YAxis\n className=\"text-xs\"\n tick={{ fill: 'currentColor' }}\n tickFormatter={(v: number) => formatCompactCurrency(v, HB_DEFAULT_CURRENCY)}\n />\n <Tooltip\n formatter={(value: number) => formatCurrency(value, HB_DEFAULT_CURRENCY)}\n contentStyle={{\n backgroundColor: 'var(--color-card)',\n border: '1px solid var(--color-border)',\n borderRadius: '8px',\n }}\n labelStyle={{ color: 'var(--color-foreground)' }}\n />\n <Legend />\n <Line\n type=\"monotone\"\n dataKey=\"revenue\"\n name={t('healthybowl.financial.reports.revenueTrend.series.revenue', 'Revenue')}\n stroke=\"var(--color-success)\"\n strokeWidth={2}\n dot={{ r: 4, fill: 'var(--color-success)' }}\n activeDot={{ r: 6 }}\n />\n <Line\n type=\"monotone\"\n dataKey=\"expenses\"\n name={t('healthybowl.financial.reports.revenueTrend.series.expenses', 'Expenses')}\n stroke=\"var(--color-destructive)\"\n strokeWidth={2}\n dot={{ r: 4, fill: 'var(--color-destructive)' }}\n activeDot={{ r: 6 }}\n />\n </LineChart>\n </ResponsiveContainer>\n )}\n </ChartCard>\n\n {/* Key Financial Metrics */}\n <div className=\"rounded-lg border border-border-subtle bg-bg-surface p-5\">\n <div className=\"flex items-center gap-2\">\n <PieChartIcon className=\"h-4 w-4 text-text-secondary\" />\n <h3 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.financial.reports.metrics.heading', 'Key Financial Metrics')}\n </h3>\n </div>\n {transactions.length === 0 && invoices.length === 0 ? (\n errors.financial ? (\n <ErrorState />\n ) : (\n <EmptyState\n illustration=\"empty-data\"\n title={t('healthybowl.financial.reports.metrics.empty.title', 'No financial data yet')}\n description={t(\n 'healthybowl.financial.reports.metrics.empty.description',\n 'Key metrics will appear here once transactions and invoices are recorded.'\n )}\n />\n )\n ) : (\n <div className=\"mt-4 grid grid-cols-2 gap-4 sm:grid-cols-4\">\n {financialMetrics.map((metric) => (\n <div key={metric.id} className=\"rounded-md bg-bg-sunken/50 p-3 text-center\">\n <p className=\"text-xs text-text-secondary\">{metric.label}</p>\n <p className=\"mt-1 text-lg font-bold text-text-primary\">\n {formatCurrency(metric.value, HB_DEFAULT_CURRENCY)}\n </p>\n </div>\n ))}\n </div>\n )}\n </div>\n\n {/* Pre-built Report Cards */}\n <div>\n <h3 className=\"mb-3 text-sm font-semibold text-text-primary\">\n {t('healthybowl.financial.reports.available.heading', 'Available Reports')}\n </h3>\n <div className=\"grid gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n {reportTypes.map((report) => {\n const Icon = categoryIcons[report.category];\n\n return (\n <div key={report.id} className=\"flex flex-col rounded-lg border border-border-subtle bg-bg-surface p-5\">\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-md bg-bg-sunken p-2\">\n <Icon className=\"h-5 w-5 text-text-secondary\" />\n </div>\n <div className=\"flex-1\">\n <h4 className=\"text-sm font-semibold text-text-primary\">{report.title}</h4>\n <p className=\"mt-0.5 text-xs text-text-secondary\">{report.description}</p>\n </div>\n </div>\n\n <div className=\"mt-auto flex items-center justify-end gap-2 pt-4\">\n {/* Download is a real CSV of the current metrics; full report generation is honestly disabled. */}\n <Button variant=\"outline\" size=\"sm\" onClick={() => handleDownload(report)}>\n <FileDown className=\"h-3.5 w-3.5\" />\n {t('healthybowl.financial.reports.available.actions.downloadCsv', 'Download CSV')}\n </Button>\n <Button size=\"sm\" onClick={() => void handleGenerate(report.id)} disabled={submitting}>\n {t('healthybowl.financial.reports.available.actions.generate', 'Generate')}\n </Button>\n </div>\n </div>\n );\n })}\n </div>\n </div>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,IAA2D;CAC/D,IAAI;CACJ,UAAU;CACV,QAAQ;CACR,KAAK;AACP,GAEa,UAA6B;CACxC,IAAM,EAAE,SAAM,EAAQ,GAChB,EAAE,iBAAc,aAAU,qBAAkB,YAAS,WAAQ,eAAY,EAAmB,GAC5F,EAAE,gB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