@burdenoff/microfe-healthybowl 2026.714.6 → 2026.714.8

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.
Files changed (41) hide show
  1. package/dist/healthybowl/HealthyBowlRoutes.js +135 -95
  2. package/dist/healthybowl/HealthyBowlRoutes.js.map +1 -1
  3. package/dist/healthybowl/hooks/useHealthyBowlAccounting.js +316 -0
  4. package/dist/healthybowl/hooks/useHealthyBowlAccounting.js.map +1 -0
  5. package/dist/healthybowl/hooks/useWeatherIntelligence.js +224 -0
  6. package/dist/healthybowl/hooks/useWeatherIntelligence.js.map +1 -0
  7. package/dist/healthybowl/pages/financial/AccountingIntegrationsPage.js +297 -0
  8. package/dist/healthybowl/pages/financial/AccountingIntegrationsPage.js.map +1 -0
  9. package/dist/healthybowl/pages/financial/ChartOfAccountsPage.js +233 -0
  10. package/dist/healthybowl/pages/financial/ChartOfAccountsPage.js.map +1 -0
  11. package/dist/healthybowl/pages/financial/CostByCropPage.js +365 -0
  12. package/dist/healthybowl/pages/financial/CostByCropPage.js.map +1 -0
  13. package/dist/healthybowl/pages/financial/FarmAccountingPage.js +384 -0
  14. package/dist/healthybowl/pages/financial/FarmAccountingPage.js.map +1 -0
  15. package/dist/healthybowl/pages/financial/FinancialDashboardPage.js +32 -16
  16. package/dist/healthybowl/pages/financial/FinancialDashboardPage.js.map +1 -1
  17. package/dist/healthybowl/pages/financial/GeneralLedgerPage.js +221 -0
  18. package/dist/healthybowl/pages/financial/GeneralLedgerPage.js.map +1 -0
  19. package/dist/healthybowl/pages/financial/JournalEntryModal.js +261 -0
  20. package/dist/healthybowl/pages/financial/JournalEntryModal.js.map +1 -0
  21. package/dist/healthybowl/pages/financial/ProfitLossPage.js +202 -0
  22. package/dist/healthybowl/pages/financial/ProfitLossPage.js.map +1 -0
  23. package/dist/healthybowl/pages/weather/FrostRiskCalendarPage.js +258 -0
  24. package/dist/healthybowl/pages/weather/FrostRiskCalendarPage.js.map +1 -0
  25. package/dist/healthybowl/pages/weather/WeatherAlertHistoryPage.js +255 -0
  26. package/dist/healthybowl/pages/weather/WeatherAlertHistoryPage.js.map +1 -0
  27. package/dist/healthybowl/pages/weather/WeatherAnomalyReportPage.js +387 -0
  28. package/dist/healthybowl/pages/weather/WeatherAnomalyReportPage.js.map +1 -0
  29. package/dist/healthybowl/pages/weather/WeatherHistoryPage.js +313 -114
  30. package/dist/healthybowl/pages/weather/WeatherHistoryPage.js.map +1 -1
  31. package/dist/healthybowl/pages/weather/WeatherOverviewPage.js +554 -213
  32. package/dist/healthybowl/pages/weather/WeatherOverviewPage.js.map +1 -1
  33. package/dist/healthybowl/pages/weather/WeatherSettingsPage.js +457 -0
  34. package/dist/healthybowl/pages/weather/WeatherSettingsPage.js.map +1 -0
  35. package/dist/healthybowl/utils/download.js +11 -0
  36. package/dist/healthybowl/utils/download.js.map +1 -0
  37. package/dist/healthybowl/utils/helpers.js +11 -8
  38. package/dist/healthybowl/utils/helpers.js.map +1 -1
  39. package/dist/healthybowl/utils/period.js +15 -0
  40. package/dist/healthybowl/utils/period.js.map +1 -0
  41. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useWeatherIntelligence.js","names":[],"sources":["../../../src/healthybowl/hooks/useWeatherIntelligence.ts"],"sourcesContent":["/**\n * Weather-Intelligence data hook — historical weather baselines, anomaly\n * reporting, frost-risk calendar, alert events + alert settings\n * (roadmap #20 / BOFF-2892, Historical Weather & Early Warning).\n *\n * Mirrors the raw-gql pattern used by `useDiseaseWarning` (Suppliers / Nursery /\n * Irrigation): the offline codegen doesn't type these operations yet, so they\n * are hand-written `gql` documents executed directly against the live gateway.\n * Every op carries the workspace `context`.\n * @module healthybowl\n */\nimport { useCallback } from 'react';\nimport { gql } from '@apollo/client';\nimport { useLazyQuery, useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** A single month's actual (synced) weather aggregate for one historical year. */\nexport interface WeatherHistoryMonthPoint {\n /** Calendar year (e.g. 2019). */\n year: number;\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label (e.g. \"Jan\"). */\n monthName: string;\n /** Mean temperature for the month, °C. */\n avgTemp: number;\n /** Total accumulated rainfall for the month, mm. */\n totalRainfall: number;\n /** Mean relative humidity for the month, %. */\n avgHumidity: number;\n}\n\n/** A per-month baseline (multi-year average + observed range) for the farm site. */\nexport interface WeatherHistoryBaselinePoint {\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label (e.g. \"Jan\"). */\n monthName: string;\n /** Baseline mean temperature, °C. */\n avgTemp: number;\n /** Coldest baseline temperature seen for this month, °C. */\n tempMin: number;\n /** Warmest baseline temperature seen for this month, °C. */\n tempMax: number;\n /** Baseline mean rainfall, mm. */\n avgRainfall: number;\n /** Lowest baseline rainfall seen for this month, mm. */\n rainfallMin: number;\n /** Highest baseline rainfall seen for this month, mm. */\n rainfallMax: number;\n}\n\n/** Historical weather series + derived baseline for the farm site. */\nexport interface WeatherHistorySeries {\n /** First year covered by the series. */\n startYear: number;\n /** Last year covered by the series. */\n endYear: number;\n /** Number of years the baseline averages over. */\n baselineYears: number;\n /** Provider of the historical data (e.g. \"open-meteo\"). */\n source: string;\n /** True once at least one sync has populated the series. */\n synced: boolean;\n /** ISO-8601 timestamp of the last successful sync, if any. */\n lastSyncedAt?: string | null;\n /** Per-month, per-year observed points. */\n points: WeatherHistoryMonthPoint[];\n /** Per-month baseline (average + range). */\n baseline: WeatherHistoryBaselinePoint[];\n}\n\n/** One month's current-vs-baseline comparison used in the anomaly report. */\nexport interface WeatherAnomalyMonthPoint {\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label (e.g. \"Jan\"). */\n monthName: string;\n /** Current (this-season) value for the metric. */\n currentValue: number;\n /** Baseline average for the metric. */\n baselineAvg: number;\n /** Baseline minimum for the metric. */\n baselineMin: number;\n /** Baseline maximum for the metric. */\n baselineMax: number;\n}\n\n/** A single narrative callout surfaced in the anomaly report. */\nexport interface WeatherAnomalyCallout {\n id: string;\n /** Short headline (e.g. \"Driest June in 8 years\"). */\n title: string;\n /** Severity band: RED | AMBER | GREY. */\n severity: string;\n /** ISO-8601 date the callout refers to. */\n date: string;\n /** Metric the callout concerns (e.g. \"rainfall\" | \"temp\" | \"frost\"). */\n metric: string;\n}\n\n/** Current-season anomaly report against the multi-year baseline. */\nexport interface WeatherAnomalyReport {\n /** Number of years the baseline averages over. */\n baselineYears: number;\n /** First year of the baseline window. */\n startYear: number;\n /** Last year of the baseline window. */\n endYear: number;\n /** Current month number 1–12. */\n currentMonth: number;\n /** Localised/short current-month label. */\n currentMonthName: string;\n /** Rainfall so far this month, mm. */\n rainfallThisMonthMm: number;\n /** Baseline rainfall for this month, mm. */\n rainfallBaselineMm: number;\n /** Rainfall deviation from baseline, %. */\n rainfallDeviationPct: number;\n /** Temperature delta vs baseline, °C. */\n avgTempDeltaC: number;\n /** Frost days observed so far this season. */\n frostDaysThisSeason: number;\n /** Baseline frost days for the season. */\n frostDaysBaseline: number;\n /** Frost-day delta vs baseline. */\n frostDaysDelta: number;\n /** ISO-8601 first-frost date this season, if any. */\n firstFrostDate?: string | null;\n /** ISO-8601 baseline first-frost date, if any. */\n baselineFirstFrostDate?: string | null;\n /** Days earlier(-)/later(+) than the baseline first frost. */\n firstFrostDeltaDays: number;\n /** Per-month rainfall comparison series. */\n monthlyRainfall: WeatherAnomalyMonthPoint[];\n /** Per-month temperature comparison series. */\n monthlyTemperature: WeatherAnomalyMonthPoint[];\n /** Narrative callouts. */\n callouts: WeatherAnomalyCallout[];\n /** ISO-8601 timestamp the report was generated. */\n generatedAt: string;\n /** Provider of the underlying data. */\n source: string;\n /** True once the underlying history has been synced. */\n synced: boolean;\n}\n\n/** A single day cell in the frost-risk calendar. */\nexport interface FrostRiskDay {\n /** ISO-8601 date (YYYY-MM-DD). */\n date: string;\n /** Day of month 1–31. */\n day: number;\n /** Risk band: FROST_HIGH | FROST_WATCH | HEAT | STORM | DISEASE_WINDOW | CLEAR | UNKNOWN. */\n risk: string;\n /** Short label for the cell. */\n label: string;\n /** Longer detail/tooltip text. */\n detail?: string | null;\n /** Forecast/observed minimum temperature, °C. */\n tempMin?: number | null;\n /** Forecast/observed maximum temperature, °C. */\n tempMax?: number | null;\n /** Data source for the cell (e.g. \"forecast\" | \"historical\"). */\n source?: string | null;\n}\n\n/** A month of frost-risk day cells. */\nexport interface FrostRiskCalendar {\n /** Calendar year. */\n year: number;\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label. */\n monthName: string;\n /** Count of days flagged as frost risk in the month. */\n frostRiskDayCount: number;\n /** ISO-8601 historical average first-frost date, if any. */\n historicalFirstFrost?: string | null;\n /** Day cells for the month. */\n days: FrostRiskDay[];\n}\n\n/** A fired weather alert event (delivered / handled / snoozed). */\nexport interface WeatherAlertEvent {\n id: string;\n /** Id of the rule that produced the event. */\n ruleId: string;\n /** Name of the rule that produced the event. */\n ruleName: string;\n /** Alert category: FROST | STORM | HEAT | DISEASE. */\n alertType: string;\n /** Severity band: RED | AMBER | GREY. */\n severity: string;\n /** Alert headline. */\n title: string;\n /** Advisory message shown to the farmer. */\n advisory?: string | null;\n /** Metric evaluated (e.g. \"temp_min\"). */\n metric: string;\n /** Observed metric value at trigger time. */\n observedValue?: number | null;\n /** Threshold the metric was compared against. */\n threshold?: number | null;\n /** Unit label for the metric/threshold (°C, %, mm, km/h). */\n unit?: string | null;\n /** Delivery channels the alert was sent through. */\n channels: string[];\n /** Lifecycle status: delivered | handled | snoozed. */\n status: string;\n /** ISO-8601 timestamp the alert triggered. */\n triggeredAt: string;\n /** ISO-8601 timestamp the alert was handled, if any. */\n handledAt?: string | null;\n /** ISO-8601 timestamp the alert is snoozed until, if any. */\n snoozedUntil?: string | null;\n}\n\n/** Farm-level weather alerting configuration. */\nexport interface WeatherAlertSettings {\n /** In-app notifications enabled. */\n inAppEnabled: boolean;\n /** SMS notifications enabled. */\n smsEnabled: boolean;\n /** Destination SMS number. */\n smsNumber?: string | null;\n /** Email notifications enabled. */\n emailEnabled: boolean;\n /** Webhook delivery enabled. */\n webhookEnabled: boolean;\n /** Destination webhook URL. */\n webhookUrl?: string | null;\n /** Quiet-hours suppression enabled. */\n quietHoursEnabled: boolean;\n /** Quiet-hours start (HH:mm). */\n quietHoursStart?: string | null;\n /** Quiet-hours end (HH:mm). */\n quietHoursEnd?: string | null;\n /** Escalate critical frost alerts past quiet hours. */\n escalateCriticalFrost: boolean;\n /** Lead time (hours) before an event to alert. */\n alertLeadTimeHours: number;\n /** Baseline window (years) for anomaly comparison. */\n baselineYears: number;\n /** Deviation threshold (%) that constitutes an anomaly. */\n deviationThresholdPct: number;\n /** Weekly digest email enabled. */\n weeklyDigestEmail: boolean;\n /** AI advisory generation enabled. */\n aiAdvisoryEnabled: boolean;\n /** Advisory language code (e.g. \"en\"). */\n advisoryLanguage?: string | null;\n /** Unit system: metric | imperial. */\n units?: string | null;\n /** First year of synced history. */\n historyStartYear?: number | null;\n /** Last year of synced history. */\n historyEndYear?: number | null;\n /** ISO-8601 timestamp of the last history sync. */\n historyLastSyncedAt?: string | null;\n}\n\n/** Editable fields for alert-settings upsert (context is attached from the hook). */\nexport interface UpsertWeatherAlertSettingsInput {\n inAppEnabled?: boolean | null;\n smsEnabled?: boolean | null;\n smsNumber?: string | null;\n emailEnabled?: boolean | null;\n webhookEnabled?: boolean | null;\n webhookUrl?: string | null;\n quietHoursEnabled?: boolean | null;\n quietHoursStart?: string | null;\n quietHoursEnd?: string | null;\n escalateCriticalFrost?: boolean | null;\n alertLeadTimeHours?: number | null;\n baselineYears?: number | null;\n deviationThresholdPct?: number | null;\n weeklyDigestEmail?: boolean | null;\n aiAdvisoryEnabled?: boolean | null;\n advisoryLanguage?: string | null;\n units?: string | null;\n}\n\n/** Optional filter for the alert-events lazy loader. */\nexport interface WeatherAlertEventsFilter {\n /** FROST | STORM | HEAT | DISEASE. */\n alertType?: string | null;\n /** delivered | handled | snoozed. */\n status?: string | null;\n}\n\n/** Options accepted by {@link useWeatherIntelligence}. */\nexport interface UseWeatherIntelligenceOptions {\n /** Number of years of history to load for the eager series query. */\n years?: number;\n}\n\n// ── GraphQL documents ────────────────────────────────────────────────────────\n\nconst WEATHER_HISTORY_SERIES_FIELDS = `\n startYear\n endYear\n baselineYears\n source\n synced\n lastSyncedAt\n points {\n year\n month\n monthName\n avgTemp\n totalRainfall\n avgHumidity\n }\n baseline {\n month\n monthName\n avgTemp\n tempMin\n tempMax\n avgRainfall\n rainfallMin\n rainfallMax\n }\n`;\n\nconst WEATHER_ALERT_EVENT_FIELDS = `\n id\n ruleId\n ruleName\n alertType\n severity\n title\n advisory\n metric\n observedValue\n threshold\n unit\n channels\n status\n triggeredAt\n handledAt\n snoozedUntil\n`;\n\nconst WEATHER_ALERT_SETTINGS_FIELDS = `\n inAppEnabled\n smsEnabled\n smsNumber\n emailEnabled\n webhookEnabled\n webhookUrl\n quietHoursEnabled\n quietHoursStart\n quietHoursEnd\n escalateCriticalFrost\n alertLeadTimeHours\n baselineYears\n deviationThresholdPct\n weeklyDigestEmail\n aiAdvisoryEnabled\n advisoryLanguage\n units\n historyStartYear\n historyEndYear\n historyLastSyncedAt\n`;\n\nconst WEATHER_HISTORY_SERIES_QUERY = gql`\n query GetHealthyBowlWeatherHistorySeries($context: ContextInput!, $years: Int) {\n getHealthyBowlWeatherHistorySeries(context: $context, years: $years) {\n ${WEATHER_HISTORY_SERIES_FIELDS}\n }\n }\n`;\n\nconst WEATHER_ANOMALY_REPORT_QUERY = gql`\n query GetHealthyBowlWeatherAnomalyReport($context: ContextInput!) {\n getHealthyBowlWeatherAnomalyReport(context: $context) {\n baselineYears\n startYear\n endYear\n currentMonth\n currentMonthName\n rainfallThisMonthMm\n rainfallBaselineMm\n rainfallDeviationPct\n avgTempDeltaC\n frostDaysThisSeason\n frostDaysBaseline\n frostDaysDelta\n firstFrostDate\n baselineFirstFrostDate\n firstFrostDeltaDays\n monthlyRainfall {\n month\n monthName\n currentValue\n baselineAvg\n baselineMin\n baselineMax\n }\n monthlyTemperature {\n month\n monthName\n currentValue\n baselineAvg\n baselineMin\n baselineMax\n }\n callouts {\n id\n title\n severity\n date\n metric\n }\n generatedAt\n source\n synced\n }\n }\n`;\n\nconst FROST_RISK_CALENDAR_QUERY = gql`\n query GetHealthyBowlFrostRiskCalendar($context: ContextInput!, $year: Int, $month: Int) {\n getHealthyBowlFrostRiskCalendar(context: $context, year: $year, month: $month) {\n year\n month\n monthName\n frostRiskDayCount\n historicalFirstFrost\n days {\n date\n day\n risk\n label\n detail\n tempMin\n tempMax\n source\n }\n }\n }\n`;\n\nconst WEATHER_ALERT_EVENTS_QUERY = gql`\n query GetHealthyBowlWeatherAlertEvents($context: ContextInput!, $alertType: String, $status: String) {\n getHealthyBowlWeatherAlertEvents(context: $context, alertType: $alertType, status: $status) {\n ${WEATHER_ALERT_EVENT_FIELDS}\n }\n }\n`;\n\nconst WEATHER_ALERT_SETTINGS_QUERY = gql`\n query GetHealthyBowlWeatherAlertSettings($context: ContextInput!) {\n getHealthyBowlWeatherAlertSettings(context: $context) {\n ${WEATHER_ALERT_SETTINGS_FIELDS}\n }\n }\n`;\n\nconst SYNC_WEATHER_HISTORY = gql`\n mutation SyncHealthyBowlWeatherHistory($context: ContextInput!) {\n syncHealthyBowlWeatherHistory(context: $context) {\n ${WEATHER_HISTORY_SERIES_FIELDS}\n }\n }\n`;\n\nconst MARK_WEATHER_ALERT_HANDLED = gql`\n mutation MarkHealthyBowlWeatherAlertHandled($id: ID!, $context: ContextInput!) {\n markHealthyBowlWeatherAlertHandled(id: $id, context: $context) {\n ${WEATHER_ALERT_EVENT_FIELDS}\n }\n }\n`;\n\nconst SNOOZE_WEATHER_ALERT = gql`\n mutation SnoozeHealthyBowlWeatherAlert($id: ID!, $until: String!, $context: ContextInput!) {\n snoozeHealthyBowlWeatherAlert(id: $id, until: $until, context: $context) {\n ${WEATHER_ALERT_EVENT_FIELDS}\n }\n }\n`;\n\nconst UPSERT_WEATHER_ALERT_SETTINGS = gql`\n mutation UpsertHealthyBowlWeatherAlertSettings($input: UpsertHealthyBowlWeatherAlertSettingsInput!) {\n upsertHealthyBowlWeatherAlertSettings(input: $input) {\n ${WEATHER_ALERT_SETTINGS_FIELDS}\n }\n }\n`;\n\n// ── Query result shapes ──────────────────────────────────────────────────────\n\ninterface WeatherHistorySeriesQueryData {\n getHealthyBowlWeatherHistorySeries: WeatherHistorySeries;\n}\ninterface WeatherAnomalyReportQueryData {\n getHealthyBowlWeatherAnomalyReport: WeatherAnomalyReport;\n}\ninterface FrostRiskCalendarQueryData {\n getHealthyBowlFrostRiskCalendar: FrostRiskCalendar;\n}\ninterface WeatherAlertEventsQueryData {\n getHealthyBowlWeatherAlertEvents: WeatherAlertEvent[];\n}\ninterface WeatherAlertSettingsQueryData {\n getHealthyBowlWeatherAlertSettings: WeatherAlertSettings;\n}\ninterface SyncWeatherHistoryMutationData {\n syncHealthyBowlWeatherHistory: WeatherHistorySeries;\n}\ninterface MarkHandledMutationData {\n markHealthyBowlWeatherAlertHandled: WeatherAlertEvent;\n}\ninterface SnoozeMutationData {\n snoozeHealthyBowlWeatherAlert: WeatherAlertEvent;\n}\ninterface UpsertSettingsMutationData {\n upsertHealthyBowlWeatherAlertSettings: WeatherAlertSettings;\n}\n\n/**\n * Loads weather-intelligence data for the active workspace: historical series +\n * baseline, the current-season anomaly report, the frost-risk calendar (current\n * month eager, other months via `loadCalendar`), fired alert events (eager list\n * + filtered `loadEvents`), and alert settings — plus the mutations to re-sync\n * history, handle/snooze alerts and save settings. Mutations refetch the\n * relevant query so the caller's view stays in sync.\n */\nexport function useWeatherIntelligence(options: UseWeatherIntelligenceOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const { years } = options;\n\n // ── History series ──────────────────────────────────────────────────────\n const {\n data: seriesData,\n loading: loadingSeries,\n error: errorSeries,\n refetch: refetchSeries,\n } = useQuery<WeatherHistorySeriesQueryData>(WEATHER_HISTORY_SERIES_QUERY, {\n variables: { context, years },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n // ── Anomaly report ──────────────────────────────────────────────────────\n const {\n data: anomalyData,\n loading: loadingAnomaly,\n error: errorAnomaly,\n refetch: refetchAnomaly,\n } = useQuery<WeatherAnomalyReportQueryData>(WEATHER_ANOMALY_REPORT_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n // ── Frost-risk calendar — eager current month + lazy month paging ─────────\n const {\n data: calendarData,\n loading: loadingCalendar,\n error: errorCalendar,\n refetch: refetchCalendar,\n } = useQuery<FrostRiskCalendarQueryData>(FROST_RISK_CALENDAR_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n const [runLoadCalendar] = useLazyQuery<FrostRiskCalendarQueryData>(FROST_RISK_CALENDAR_QUERY, {\n fetchPolicy: 'cache-and-network',\n });\n\n // ── Alert events — eager list + lazy filtered loader ──────────────────────\n const {\n data: eventsData,\n loading: loadingEvents,\n error: errorEvents,\n refetch: refetchEvents,\n } = useQuery<WeatherAlertEventsQueryData>(WEATHER_ALERT_EVENTS_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n const [runLoadEvents] = useLazyQuery<WeatherAlertEventsQueryData>(WEATHER_ALERT_EVENTS_QUERY, {\n fetchPolicy: 'cache-and-network',\n });\n\n // ── Settings ────────────────────────────────────────────────────────────\n const {\n data: settingsData,\n loading: loadingSettings,\n error: errorSettings,\n refetch: refetchSettings,\n } = useQuery<WeatherAlertSettingsQueryData>(WEATHER_ALERT_SETTINGS_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n // ── Mutations ───────────────────────────────────────────────────────────\n const [syncHistoryMutation] = useMutation<SyncWeatherHistoryMutationData>(SYNC_WEATHER_HISTORY);\n const [markHandledMutation] = useMutation<MarkHandledMutationData>(MARK_WEATHER_ALERT_HANDLED);\n const [snoozeMutation] = useMutation<SnoozeMutationData>(SNOOZE_WEATHER_ALERT);\n const [saveSettingsMutation] = useMutation<UpsertSettingsMutationData>(UPSERT_WEATHER_ALERT_SETTINGS);\n\n const loadCalendar = useCallback(\n async (year: number, month: number): Promise<FrostRiskCalendar | null> => {\n const result = await runLoadCalendar({ variables: { context, year, month } });\n return result.data?.getHealthyBowlFrostRiskCalendar ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [runLoadCalendar, workspaceId]\n );\n\n const loadEvents = useCallback(\n async (filter: WeatherAlertEventsFilter = {}): Promise<WeatherAlertEvent[]> => {\n const result = await runLoadEvents({\n variables: { context, alertType: filter.alertType ?? null, status: filter.status ?? null },\n });\n return result.data?.getHealthyBowlWeatherAlertEvents ?? [];\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [runLoadEvents, workspaceId]\n );\n\n const syncHistory = useCallback(\n async (): Promise<WeatherHistorySeries | null> => {\n const result = await syncHistoryMutation({ variables: { context } });\n await refetchSeries();\n await refetchAnomaly();\n return result.data?.syncHealthyBowlWeatherHistory ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [syncHistoryMutation, refetchSeries, refetchAnomaly, workspaceId]\n );\n\n const markHandled = useCallback(\n async (id: string): Promise<WeatherAlertEvent | null> => {\n const result = await markHandledMutation({ variables: { id, context } });\n await refetchEvents();\n return result.data?.markHealthyBowlWeatherAlertHandled ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [markHandledMutation, refetchEvents, workspaceId]\n );\n\n const snooze = useCallback(\n async (id: string, until: string): Promise<WeatherAlertEvent | null> => {\n const result = await snoozeMutation({ variables: { id, until, context } });\n await refetchEvents();\n return result.data?.snoozeHealthyBowlWeatherAlert ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snoozeMutation, refetchEvents, workspaceId]\n );\n\n const saveSettings = useCallback(\n async (input: UpsertWeatherAlertSettingsInput): Promise<WeatherAlertSettings | null> => {\n const result = await saveSettingsMutation({ variables: { input: { ...input, context } } });\n await refetchSettings();\n return result.data?.upsertHealthyBowlWeatherAlertSettings ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [saveSettingsMutation, refetchSettings, workspaceId]\n );\n\n return {\n // History series\n series: seriesData?.getHealthyBowlWeatherHistorySeries ?? null,\n loadingSeries,\n errorSeries: errorSeries ?? null,\n refetchSeries,\n // Anomaly report\n anomaly: anomalyData?.getHealthyBowlWeatherAnomalyReport ?? null,\n loadingAnomaly,\n errorAnomaly: errorAnomaly ?? null,\n refetchAnomaly,\n // Frost-risk calendar\n frostCalendar: calendarData?.getHealthyBowlFrostRiskCalendar ?? null,\n loadingCalendar,\n errorCalendar: errorCalendar ?? null,\n refetchCalendar,\n loadCalendar,\n // Alert events\n alertEvents: eventsData?.getHealthyBowlWeatherAlertEvents ?? [],\n loadingEvents,\n errorEvents: errorEvents ?? null,\n refetchEvents,\n loadEvents,\n // Settings\n settings: settingsData?.getHealthyBowlWeatherAlertSettings ?? null,\n loadingSettings,\n errorSettings: errorSettings ?? null,\n refetchSettings,\n // Mutations\n syncHistory,\n markHandled,\n snooze,\n saveSettings,\n };\n}\n"],"mappings":";;;;;AA6SA,IAAM,IAAgC,gUA2BhC,IAA6B,kMAmB7B,IAAgC,uXAuBhC,IAA+B,CAAG;;;QAGhC,EAA8B;;;GAKhC,IAA+B,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDlC,IAA4B,CAAG;;;;;;;;;;;;;;;;;;;;GAsB/B,IAA6B,CAAG;;;QAG9B,EAA2B;;;GAK7B,IAA+B,CAAG;;;QAGhC,EAA8B;;;GAKhC,IAAuB,CAAG;;;QAGxB,EAA8B;;;GAKhC,I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aAAa,KAAe;EAC5B;EAEA,SAAS,GAAa,sCAAsC;EAC5D;EACA,cAAc,KAAgB;EAC9B;EAEA,eAAe,GAAc,mCAAmC;EAChE;EACA,eAAe,KAAiB;EAChC;EACA;EAEA,aAAa,GAAY,oCAAoC,EAAE;EAC/D;EACA,aAAa,KAAe;EAC5B;EACA;EAEA,UAAU,GAAc,sCAAsC;EAC9D;EACA,eAAe,KAAiB;EAChC;EAEA;EACA;EACA;EACA;EACD"}
@@ -0,0 +1,297 @@
1
+ import { formatDate as e } from "../../utils/helpers.js";
2
+ import { PageLayout as t } from "../../components/PageLayout.js";
3
+ import { DataTable as n } from "../../components/DataTable.js";
4
+ import { StatusBadge as r } from "../../components/StatusBadge.js";
5
+ import { EmptyState as i } from "../../components/EmptyState.js";
6
+ import { ErrorState as a } from "../../components/ErrorState.js";
7
+ import { ChartCard as o } from "../../components/ChartCard.js";
8
+ import { ToastContainer as s } from "../../components/Toast.js";
9
+ import { LoadingSkeleton as c } from "../../components/LoadingSkeleton.js";
10
+ import { Modal as l } from "../../components/Modal.js";
11
+ import { useToast as u } from "../../hooks/useToast.js";
12
+ import "../../components/index.js";
13
+ import { useHealthyBowlAccounting as d } from "../../hooks/useHealthyBowlAccounting.js";
14
+ import { useState as f } from "react";
15
+ import { Fragment as p, jsx as m, jsxs as h } from "react/jsx-runtime";
16
+ import { Button as g, Switch as _ } from "@burdenoff/fe-libs/ui";
17
+ //#region src/healthybowl/pages/financial/AccountingIntegrationsPage.tsx
18
+ var v = "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)]", y = [
19
+ {
20
+ id: "TALLY",
21
+ label: "Tally",
22
+ blurb: "Push journal entries to Tally via its XML import gateway."
23
+ },
24
+ {
25
+ id: "ZOHO_BOOKS",
26
+ label: "Zoho Books",
27
+ blurb: "Sync journals and invoices with your Zoho Books organization."
28
+ },
29
+ {
30
+ id: "QUICKBOOKS",
31
+ label: "QuickBooks",
32
+ blurb: "Export journal entries to QuickBooks Online."
33
+ }
34
+ ];
35
+ function b() {
36
+ let { toasts: b, toast: x, dismiss: S } = u(), C = d({ integrations: !0 }), w = C.integrations, [T, E] = f(null), [D, O] = f(""), [k, A] = f(""), [j, M] = f(""), [N, P] = f(""), F = async () => {
37
+ if (T) {
38
+ P("connect");
39
+ try {
40
+ await C.connectIntegration({
41
+ provider: T,
42
+ displayName: D || null,
43
+ endpoint: k || null,
44
+ organizationRef: j || null
45
+ }), x({
46
+ title: `${T} connected`,
47
+ variant: "success"
48
+ }), E(null), O(""), A(""), M("");
49
+ } catch (e) {
50
+ x({
51
+ title: "Connect failed",
52
+ description: e instanceof Error ? e.message : void 0,
53
+ variant: "error"
54
+ });
55
+ } finally {
56
+ P("");
57
+ }
58
+ }
59
+ }, I = async (e) => {
60
+ P(e);
61
+ try {
62
+ let t = await C.syncIntegration(e);
63
+ x({
64
+ title: t?.message ?? "Sync complete",
65
+ variant: t?.status === "FAILED" ? "warning" : "success"
66
+ });
67
+ } catch (e) {
68
+ x({
69
+ title: "Sync failed",
70
+ description: e instanceof Error ? e.message : void 0,
71
+ variant: "error"
72
+ });
73
+ } finally {
74
+ P("");
75
+ }
76
+ }, L = async (e) => {
77
+ P(e);
78
+ try {
79
+ await C.disconnectIntegration(e), x({
80
+ title: `${e} disconnected`,
81
+ variant: "success"
82
+ });
83
+ } catch (e) {
84
+ x({
85
+ title: "Disconnect failed",
86
+ description: e instanceof Error ? e.message : void 0,
87
+ variant: "error"
88
+ });
89
+ } finally {
90
+ P("");
91
+ }
92
+ }, R = async (e) => {
93
+ try {
94
+ await C.updateSyncSettings(e);
95
+ } catch (e) {
96
+ x({
97
+ title: "Could not save setting",
98
+ description: e instanceof Error ? e.message : void 0,
99
+ variant: "error"
100
+ });
101
+ }
102
+ };
103
+ return /* @__PURE__ */ h(t, {
104
+ title: "Accounting Integrations",
105
+ description: "Sync your HealthyBowl ledger with external accounting software.",
106
+ children: [
107
+ /* @__PURE__ */ m(s, {
108
+ toasts: b,
109
+ onDismiss: S
110
+ }),
111
+ C.error && !w ? /* @__PURE__ */ m(a, {
112
+ title: "Could not load integrations",
113
+ description: C.error.message
114
+ }) : C.loading && !w ? /* @__PURE__ */ m(c, {
115
+ variant: "table",
116
+ count: 4
117
+ }) : /* @__PURE__ */ h("div", {
118
+ className: "space-y-6",
119
+ children: [
120
+ /* @__PURE__ */ m("div", {
121
+ className: "grid grid-cols-1 gap-4 md:grid-cols-3",
122
+ children: y.map((t) => {
123
+ let n = w?.integrations.find((e) => e.provider === t.id), i = n?.status ?? "NOT_CONNECTED", a = i === "CONNECTED" ? "Connected" : i === "SYNC_READY" ? "Sync ready" : "Not connected";
124
+ return /* @__PURE__ */ h("div", {
125
+ className: "rounded-xl border border-border-subtle bg-bg-surface p-4",
126
+ children: [
127
+ /* @__PURE__ */ m("div", {
128
+ className: "mb-1 text-base font-semibold text-text-primary",
129
+ children: t.label
130
+ }),
131
+ /* @__PURE__ */ m("p", {
132
+ className: "mb-3 text-sm text-text-secondary",
133
+ children: t.blurb
134
+ }),
135
+ /* @__PURE__ */ h("div", {
136
+ className: "mb-3",
137
+ children: [/* @__PURE__ */ m(r, {
138
+ variant: i === "CONNECTED" ? "success" : i === "SYNC_READY" ? "warning" : "muted",
139
+ label: a
140
+ }), n && /* @__PURE__ */ h("div", {
141
+ className: "mt-2 text-xs text-text-secondary",
142
+ children: [
143
+ n.lastSyncedAt ? `Last synced ${e(n.lastSyncedAt)} · ` : "",
144
+ n.entriesPushed,
145
+ " entries pushed"
146
+ ]
147
+ })]
148
+ }),
149
+ /* @__PURE__ */ m("div", {
150
+ className: "flex gap-2",
151
+ children: i === "NOT_CONNECTED" ? /* @__PURE__ */ m(g, {
152
+ size: "sm",
153
+ onClick: () => E(t.id),
154
+ children: "Connect"
155
+ }) : /* @__PURE__ */ h(p, { children: [/* @__PURE__ */ m(g, {
156
+ size: "sm",
157
+ onClick: () => I(t.id),
158
+ disabled: N === t.id,
159
+ children: N === t.id ? "Syncing…" : "Sync now"
160
+ }), /* @__PURE__ */ m(g, {
161
+ size: "sm",
162
+ variant: "outline",
163
+ onClick: () => L(t.id),
164
+ disabled: N === t.id,
165
+ children: "Disconnect"
166
+ })] })
167
+ })
168
+ ]
169
+ }, t.id);
170
+ })
171
+ }),
172
+ /* @__PURE__ */ m(o, {
173
+ title: "Sync Settings",
174
+ children: /* @__PURE__ */ m("div", {
175
+ className: "space-y-3",
176
+ children: [
177
+ ["autoSyncDaily", "Auto-sync journal entries daily"],
178
+ ["pushInvoices", "Push invoices to accounting system"],
179
+ ["syncCoaMapping", "Sync chart of accounts mapping"]
180
+ ].map(([e, t]) => /* @__PURE__ */ h("div", {
181
+ className: "flex items-center justify-between",
182
+ children: [/* @__PURE__ */ m("span", {
183
+ className: "text-sm text-text-primary",
184
+ children: t
185
+ }), /* @__PURE__ */ m(_, {
186
+ checked: !!w?.[e],
187
+ onCheckedChange: (t) => R({ [e]: t })
188
+ })]
189
+ }, e))
190
+ })
191
+ }),
192
+ /* @__PURE__ */ m(o, {
193
+ title: "Recent Sync Log",
194
+ children: w && w.syncLogs.length > 0 ? /* @__PURE__ */ m(n, {
195
+ columns: [
196
+ {
197
+ key: "syncedAt",
198
+ header: "When",
199
+ render: (t) => e(t.syncedAt)
200
+ },
201
+ {
202
+ key: "provider",
203
+ header: "Provider",
204
+ render: (e) => e.provider === "ZOHO_BOOKS" ? "Zoho Books" : e.provider === "QUICKBOOKS" ? "QuickBooks" : "Tally"
205
+ },
206
+ {
207
+ key: "entriesCount",
208
+ header: "Entries",
209
+ className: "text-right",
210
+ render: (e) => e.entriesCount
211
+ },
212
+ {
213
+ key: "status",
214
+ header: "Status",
215
+ render: (e) => /* @__PURE__ */ m(r, {
216
+ variant: e.status === "SUCCESS" ? "success" : e.status === "FAILED" ? "error" : "warning",
217
+ label: e.status
218
+ })
219
+ }
220
+ ],
221
+ data: w.syncLogs,
222
+ keyField: "id",
223
+ pageSize: 10
224
+ }) : /* @__PURE__ */ m(i, {
225
+ title: "No syncs yet",
226
+ description: "Connect a provider and run a sync to see the log here."
227
+ })
228
+ })
229
+ ]
230
+ }),
231
+ /* @__PURE__ */ m(l, {
232
+ open: T !== null,
233
+ onClose: () => E(null),
234
+ title: `Connect ${T === "ZOHO_BOOKS" ? "Zoho Books" : T === "QUICKBOOKS" ? "QuickBooks" : "Tally"}`,
235
+ description: "Store the non-secret connection details for this provider.",
236
+ size: "md",
237
+ footer: /* @__PURE__ */ h("div", {
238
+ className: "flex justify-end gap-2",
239
+ children: [/* @__PURE__ */ m(g, {
240
+ variant: "outline",
241
+ onClick: () => E(null),
242
+ children: "Cancel"
243
+ }), /* @__PURE__ */ m(g, {
244
+ onClick: F,
245
+ disabled: N === "connect",
246
+ children: "Connect"
247
+ })]
248
+ }),
249
+ children: /* @__PURE__ */ h("div", {
250
+ className: "space-y-3",
251
+ children: [
252
+ /* @__PURE__ */ h("label", {
253
+ className: "block text-sm",
254
+ children: [/* @__PURE__ */ m("span", {
255
+ className: "mb-1 block text-text-secondary",
256
+ children: "Display name (optional)"
257
+ }), /* @__PURE__ */ m("input", {
258
+ value: D,
259
+ onChange: (e) => O(e.target.value),
260
+ className: v,
261
+ placeholder: "Green Valley Books"
262
+ })]
263
+ }),
264
+ /* @__PURE__ */ h("label", {
265
+ className: "block text-sm",
266
+ children: [/* @__PURE__ */ m("span", {
267
+ className: "mb-1 block text-text-secondary",
268
+ children: "API endpoint / gateway URL (optional)"
269
+ }), /* @__PURE__ */ m("input", {
270
+ value: k,
271
+ onChange: (e) => A(e.target.value),
272
+ className: v,
273
+ placeholder: "https://…"
274
+ })]
275
+ }),
276
+ /* @__PURE__ */ h("label", {
277
+ className: "block text-sm",
278
+ children: [/* @__PURE__ */ m("span", {
279
+ className: "mb-1 block text-text-secondary",
280
+ children: "Organization id (optional)"
281
+ }), /* @__PURE__ */ m("input", {
282
+ value: j,
283
+ onChange: (e) => M(e.target.value),
284
+ className: v,
285
+ placeholder: "Zoho organization id"
286
+ })]
287
+ })
288
+ ]
289
+ })
290
+ })
291
+ ]
292
+ });
293
+ }
294
+ //#endregion
295
+ export { b as AccountingIntegrationsPage };
296
+
297
+ //# sourceMappingURL=AccountingIntegrationsPage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AccountingIntegrationsPage.js","names":[],"sources":["../../../../src/healthybowl/pages/financial/AccountingIntegrationsPage.tsx"],"sourcesContent":["import { useState } from 'react';\nimport { Button, Switch } from '@burdenoff/fe-libs/ui';\nimport {\n PageLayout,\n ChartCard,\n DataTable,\n StatusBadge,\n LoadingSkeleton,\n ErrorState,\n EmptyState,\n Modal,\n ToastContainer,\n} from '../../components';\nimport type { Column } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { formatDate } from '../../utils/helpers';\nimport { useHealthyBowlAccounting } from '../../hooks/useHealthyBowlAccounting';\nimport type { AccountingSyncLog } from '../../hooks/useHealthyBowlAccounting';\n\nconst INPUT_CLASS =\n '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\nconst PROVIDERS: Array<{ id: 'TALLY' | 'ZOHO_BOOKS' | 'QUICKBOOKS'; label: string; blurb: string }> = [\n { id: 'TALLY', label: 'Tally', blurb: 'Push journal entries to Tally via its XML import gateway.' },\n { id: 'ZOHO_BOOKS', label: 'Zoho Books', blurb: 'Sync journals and invoices with your Zoho Books organization.' },\n { id: 'QUICKBOOKS', label: 'QuickBooks', blurb: 'Export journal entries to QuickBooks Online.' },\n];\n\nexport function AccountingIntegrationsPage() {\n const { toasts, toast, dismiss } = useToast();\n const acc = useHealthyBowlAccounting({ integrations: true });\n const payload = acc.integrations;\n const [connectFor, setConnectFor] = useState<null | 'TALLY' | 'ZOHO_BOOKS' | 'QUICKBOOKS'>(null);\n const [displayName, setDisplayName] = useState('');\n const [endpoint, setEndpoint] = useState('');\n const [organizationRef, setOrganizationRef] = useState('');\n const [busy, setBusy] = useState('');\n\n const submitConnect = async () => {\n if (!connectFor) return;\n setBusy('connect');\n try {\n await acc.connectIntegration({\n provider: connectFor,\n displayName: displayName || null,\n endpoint: endpoint || null,\n organizationRef: organizationRef || null,\n });\n toast({ title: `${connectFor} connected`, variant: 'success' });\n setConnectFor(null);\n setDisplayName('');\n setEndpoint('');\n setOrganizationRef('');\n } catch (err) {\n toast({ title: 'Connect failed', description: err instanceof Error ? err.message : undefined, variant: 'error' });\n } finally {\n setBusy('');\n }\n };\n\n const sync = async (provider: string) => {\n setBusy(provider);\n try {\n const res = await acc.syncIntegration(provider);\n toast({ title: res?.message ?? 'Sync complete', variant: res?.status === 'FAILED' ? 'warning' : 'success' });\n } catch (err) {\n toast({ title: 'Sync failed', description: err instanceof Error ? err.message : undefined, variant: 'error' });\n } finally {\n setBusy('');\n }\n };\n\n const disconnect = async (provider: string) => {\n setBusy(provider);\n try {\n await acc.disconnectIntegration(provider);\n toast({ title: `${provider} disconnected`, variant: 'success' });\n } catch (err) {\n toast({\n title: 'Disconnect failed',\n description: err instanceof Error ? err.message : undefined,\n variant: 'error',\n });\n } finally {\n setBusy('');\n }\n };\n\n const setSetting = async (patch: { autoSyncDaily?: boolean; pushInvoices?: boolean; syncCoaMapping?: boolean }) => {\n try {\n await acc.updateSyncSettings(patch);\n } catch (err) {\n toast({\n title: 'Could not save setting',\n description: err instanceof Error ? err.message : undefined,\n variant: 'error',\n });\n }\n };\n\n const logColumns: Column<AccountingSyncLog>[] = [\n { key: 'syncedAt', header: 'When', render: (r) => formatDate(r.syncedAt) },\n {\n key: 'provider',\n header: 'Provider',\n render: (r) =>\n r.provider === 'ZOHO_BOOKS' ? 'Zoho Books' : r.provider === 'QUICKBOOKS' ? 'QuickBooks' : 'Tally',\n },\n { key: 'entriesCount', header: 'Entries', className: 'text-right', render: (r) => r.entriesCount },\n {\n key: 'status',\n header: 'Status',\n render: (r) => (\n <StatusBadge\n variant={r.status === 'SUCCESS' ? 'success' : r.status === 'FAILED' ? 'error' : 'warning'}\n label={r.status}\n />\n ),\n },\n ];\n\n return (\n <PageLayout\n title=\"Accounting Integrations\"\n description=\"Sync your HealthyBowl ledger with external accounting software.\"\n >\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n {acc.error && !payload ? (\n <ErrorState title=\"Could not load integrations\" description={acc.error.message} />\n ) : acc.loading && !payload ? (\n <LoadingSkeleton variant=\"table\" count={4} />\n ) : (\n <div className=\"space-y-6\">\n <div className=\"grid grid-cols-1 gap-4 md:grid-cols-3\">\n {PROVIDERS.map((p) => {\n const found = payload?.integrations.find((i) => i.provider === p.id);\n const status = found?.status ?? 'NOT_CONNECTED';\n const statusLabel =\n status === 'CONNECTED' ? 'Connected' : status === 'SYNC_READY' ? 'Sync ready' : 'Not connected';\n return (\n <div key={p.id} className=\"rounded-xl border border-border-subtle bg-bg-surface p-4\">\n <div className=\"mb-1 text-base font-semibold text-text-primary\">{p.label}</div>\n <p className=\"mb-3 text-sm text-text-secondary\">{p.blurb}</p>\n <div className=\"mb-3\">\n <StatusBadge\n variant={status === 'CONNECTED' ? 'success' : status === 'SYNC_READY' ? 'warning' : 'muted'}\n label={statusLabel}\n />\n {found && (\n <div className=\"mt-2 text-xs text-text-secondary\">\n {found.lastSyncedAt ? `Last synced ${formatDate(found.lastSyncedAt)} · ` : ''}\n {found.entriesPushed} entries pushed\n </div>\n )}\n </div>\n <div className=\"flex gap-2\">\n {status === 'NOT_CONNECTED' ? (\n <Button size=\"sm\" onClick={() => setConnectFor(p.id)}>\n Connect\n </Button>\n ) : (\n <>\n <Button size=\"sm\" onClick={() => sync(p.id)} disabled={busy === p.id}>\n {busy === p.id ? 'Syncing…' : 'Sync now'}\n </Button>\n <Button size=\"sm\" variant=\"outline\" onClick={() => disconnect(p.id)} disabled={busy === p.id}>\n Disconnect\n </Button>\n </>\n )}\n </div>\n </div>\n );\n })}\n </div>\n\n <ChartCard title=\"Sync Settings\">\n <div className=\"space-y-3\">\n {(\n [\n ['autoSyncDaily', 'Auto-sync journal entries daily'],\n ['pushInvoices', 'Push invoices to accounting system'],\n ['syncCoaMapping', 'Sync chart of accounts mapping'],\n ] as const\n ).map(([key, label]) => (\n <div key={key} className=\"flex items-center justify-between\">\n <span className=\"text-sm text-text-primary\">{label}</span>\n <Switch\n checked={Boolean(payload?.[key])}\n onCheckedChange={(v: boolean) => setSetting({ [key]: v })}\n />\n </div>\n ))}\n </div>\n </ChartCard>\n\n <ChartCard title=\"Recent Sync Log\">\n {payload && payload.syncLogs.length > 0 ? (\n <DataTable columns={logColumns} data={payload.syncLogs} keyField=\"id\" pageSize={10} />\n ) : (\n <EmptyState title=\"No syncs yet\" description=\"Connect a provider and run a sync to see the log here.\" />\n )}\n </ChartCard>\n </div>\n )}\n\n <Modal\n open={connectFor !== null}\n onClose={() => setConnectFor(null)}\n title={`Connect ${connectFor === 'ZOHO_BOOKS' ? 'Zoho Books' : connectFor === 'QUICKBOOKS' ? 'QuickBooks' : 'Tally'}`}\n description=\"Store the non-secret connection details for this provider.\"\n size=\"md\"\n footer={\n <div className=\"flex justify-end gap-2\">\n <Button variant=\"outline\" onClick={() => setConnectFor(null)}>\n Cancel\n </Button>\n <Button onClick={submitConnect} disabled={busy === 'connect'}>\n Connect\n </Button>\n </div>\n }\n >\n <div className=\"space-y-3\">\n <label className=\"block text-sm\">\n <span className=\"mb-1 block text-text-secondary\">Display name (optional)</span>\n <input\n value={displayName}\n onChange={(e) => setDisplayName(e.target.value)}\n className={INPUT_CLASS}\n placeholder=\"Green Valley Books\"\n />\n </label>\n <label className=\"block text-sm\">\n <span className=\"mb-1 block text-text-secondary\">API endpoint / gateway URL (optional)</span>\n <input\n value={endpoint}\n onChange={(e) => setEndpoint(e.target.value)}\n className={INPUT_CLASS}\n placeholder=\"https://…\"\n />\n </label>\n <label className=\"block text-sm\">\n <span className=\"mb-1 block text-text-secondary\">Organization id (optional)</span>\n <input\n value={organizationRef}\n onChange={(e) => setOrganizationRef(e.target.value)}\n className={INPUT_CLASS}\n placeholder=\"Zoho organization id\"\n />\n </label>\n </div>\n </Modal>\n </PageLayout>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,IAAM,IACJ,uMAEI,IAAgG;CACpG;EAAE,IAAI;EAAS,OAAO;EAAS,OAAO;EAA6D;CACnG;EAAE,IAAI;EAAc,OAAO;EAAc,OAAO;EAAiE;CACjH;EAAE,IAAI;EAAc,OAAO;EAAc,OAAO;EAAgD;CACjG;AAED,SAAgB,IAA6B;CAC3C,IAAM,EAAE,WAAQ,UAAO,eAAY,GAAU,EACvC,IAAM,EAAyB,EAAE,cAAc,IAAM,CAAC,EACtD,IAAU,EAAI,cACd,CAAC,GAAY,KAAiB,EAAuD,KAAK,EAC1F,CAAC,GAAa,KAAkB,EAAS,GAAG,EAC5C,CAAC,GAAU,KAAe,EAAS,GAAG,EACtC,CAAC,GAAiB,KAAsB,EAAS,GAAG,EACpD,CAAC,GAAM,KAAW,EAAS,GAAG,EAE9B,IAAgB,YAAY;AAC3B,SACL;KAAQ,UAAU;AAClB,OAAI;AAWF,IAVA,MAAM,EAAI,mBAAmB;KAC3B,UAAU;KACV,aAAa,KAAe;KAC5B,UAAU,KAAY;KACtB,iBAAiB,KAAmB;KACrC,CAAC,EACF,EAAM;KAAE,OAAO,GAAG,EAAW;KAAa,SAAS;KAAW,CAAC,EAC/D,EAAc,KAAK,EACnB,EAAe,GAAG,EAClB,EAAY,GAAG,EACf,EAAmB,GAAG;YACf,GAAK;AACZ,MAAM;KAAE,OAAO;KAAkB,aAAa,aAAe,QAAQ,EAAI,UAAU,KAAA;KAAW,SAAS;KAAS,CAAC;aACzG;AACR,MAAQ,GAAG;;;IAIT,IAAO,OAAO,MAAqB;AACvC,IAAQ,EAAS;AACjB,MAAI;GACF,IAAM,IAAM,MAAM,EAAI,gBAAgB,EAAS;AAC/C,KAAM;IAAE,OAAO,GAAK,WAAW;IAAiB,SAAS,GAAK,WAAW,WAA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,QAAD;QAAM,WAAU;kBAAiC;QAA4C,CAAA,EAC7F,kBAAC,SAAD;QACE,OAAO;QACP,WAAW,MAAM,EAAY,EAAE,OAAO,MAAM;QAC5C,WAAW;QACX,aAAY;QACZ,CAAA,CACI;;MACR,kBAAC,SAAD;OAAO,WAAU;iBAAjB,CACE,kBAAC,QAAD;QAAM,WAAU;kBAAiC;QAAiC,CAAA,EAClF,kBAAC,SAAD;QACE,OAAO;QACP,WAAW,MAAM,EAAmB,EAAE,OAAO,MAAM;QACnD,WAAW;QACX,aAAY;QACZ,CAAA,CACI;;MACJ;;IACA,CAAA;GACG"}
@@ -0,0 +1,233 @@
1
+ import { formatCurrency as e } from "../../utils/helpers.js";
2
+ import { PageLayout as t } from "../../components/PageLayout.js";
3
+ import { DataTable as n } from "../../components/DataTable.js";
4
+ import { StatusBadge as r } from "../../components/StatusBadge.js";
5
+ import { EmptyState as i } from "../../components/EmptyState.js";
6
+ import { ErrorState as a } from "../../components/ErrorState.js";
7
+ import { ToastContainer as o } from "../../components/Toast.js";
8
+ import { useConfirm as s } from "../../components/ConfirmDialog.js";
9
+ import { LoadingSkeleton as c } from "../../components/LoadingSkeleton.js";
10
+ import { Modal as l } from "../../components/Modal.js";
11
+ import { useToast as u } from "../../hooks/useToast.js";
12
+ import "../../components/index.js";
13
+ import { useHealthyBowlAccounting as d } from "../../hooks/useHealthyBowlAccounting.js";
14
+ import { useEffect as f, useState as p } from "react";
15
+ import { jsx as m, jsxs as h } from "react/jsx-runtime";
16
+ import { Button as g } from "@burdenoff/fe-libs/ui";
17
+ //#region src/healthybowl/pages/financial/ChartOfAccountsPage.tsx
18
+ var _ = "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)]", v = [
19
+ "ASSET",
20
+ "LIABILITY",
21
+ "EQUITY",
22
+ "INCOME",
23
+ "EXPENSE"
24
+ ];
25
+ function y() {
26
+ let { toasts: y, toast: b, dismiss: x } = u(), S = s(), C = d({ chartOfAccounts: !0 }), [w, T] = p(!1), [E, D] = p(!1), [O, k] = p(null), [A, j] = p(""), [M, N] = p(""), [P, F] = p("EXPENSE"), [I, L] = p(!1);
27
+ f(() => {
28
+ w || !C.loading && C.chartOfAccounts.length === 0 && !C.error && (T(!0), C.ensureChartOfAccounts().catch(() => void 0));
29
+ }, [C, w]);
30
+ let R = () => {
31
+ k(null), j(""), N(""), F("EXPENSE"), D(!0);
32
+ }, z = (e) => {
33
+ k(e), j(e.code), N(e.name), F(e.accountType), D(!0);
34
+ }, B = async () => {
35
+ if (!M.trim() || !O && !A.trim()) {
36
+ b({
37
+ title: "Code and name are required",
38
+ variant: "error"
39
+ });
40
+ return;
41
+ }
42
+ L(!0);
43
+ try {
44
+ O ? (await C.updateAccount({
45
+ id: O.id,
46
+ name: M.trim(),
47
+ accountType: P
48
+ }), b({
49
+ title: "Account updated",
50
+ variant: "success"
51
+ })) : (await C.createAccount({
52
+ code: A.trim(),
53
+ name: M.trim(),
54
+ accountType: P
55
+ }), b({
56
+ title: "Account created",
57
+ variant: "success"
58
+ })), D(!1);
59
+ } catch (e) {
60
+ b({
61
+ title: "Save failed",
62
+ description: e instanceof Error ? e.message : void 0,
63
+ variant: "error"
64
+ });
65
+ } finally {
66
+ L(!1);
67
+ }
68
+ }, V = async (e) => {
69
+ if (await S({
70
+ title: "Delete account?",
71
+ message: `Delete "${e.code} · ${e.name}"? Accounts used by entries cannot be deleted.`
72
+ })) try {
73
+ await C.deleteAccount(e.id), b({
74
+ title: "Account deleted",
75
+ variant: "success"
76
+ });
77
+ } catch (e) {
78
+ b({
79
+ title: "Delete failed",
80
+ description: e instanceof Error ? e.message : void 0,
81
+ variant: "error"
82
+ });
83
+ }
84
+ };
85
+ return /* @__PURE__ */ h(t, {
86
+ title: "Chart of Accounts",
87
+ description: "The accounts your double-entry ledger posts to.",
88
+ actions: /* @__PURE__ */ m(g, {
89
+ onClick: R,
90
+ children: "New account"
91
+ }),
92
+ children: [
93
+ /* @__PURE__ */ m(o, {
94
+ toasts: y,
95
+ onDismiss: x
96
+ }),
97
+ C.error && C.chartOfAccounts.length === 0 ? /* @__PURE__ */ m(a, {
98
+ title: "Could not load accounts",
99
+ description: C.error.message
100
+ }) : C.loading && C.chartOfAccounts.length === 0 ? /* @__PURE__ */ m(c, {
101
+ variant: "table",
102
+ count: 8
103
+ }) : C.chartOfAccounts.length === 0 ? /* @__PURE__ */ m(i, {
104
+ title: "No accounts yet",
105
+ description: "A default chart of accounts is being set up…"
106
+ }) : /* @__PURE__ */ m(n, {
107
+ columns: [
108
+ {
109
+ key: "code",
110
+ header: "Code",
111
+ render: (e) => e.code
112
+ },
113
+ {
114
+ key: "name",
115
+ header: "Name",
116
+ render: (e) => e.name
117
+ },
118
+ {
119
+ key: "accountType",
120
+ header: "Type",
121
+ render: (e) => e.accountType
122
+ },
123
+ {
124
+ key: "normalBalance",
125
+ header: "Normal",
126
+ render: (e) => e.normalBalance
127
+ },
128
+ {
129
+ key: "balance",
130
+ header: "Balance (₹)",
131
+ className: "text-right",
132
+ render: (t) => e(t.balance, "INR")
133
+ },
134
+ {
135
+ key: "isActive",
136
+ header: "Active",
137
+ render: (e) => /* @__PURE__ */ m(r, {
138
+ variant: e.isActive ? "success" : "muted",
139
+ label: e.isActive ? "Active" : "Inactive"
140
+ })
141
+ },
142
+ {
143
+ key: "actions",
144
+ header: "",
145
+ render: (e) => /* @__PURE__ */ h("div", {
146
+ className: "flex justify-end gap-1",
147
+ children: [/* @__PURE__ */ m(g, {
148
+ variant: "ghost",
149
+ size: "sm",
150
+ onClick: () => z(e),
151
+ children: "Edit"
152
+ }), !e.isSystem && /* @__PURE__ */ m(g, {
153
+ variant: "ghost",
154
+ size: "sm",
155
+ onClick: () => V(e),
156
+ children: "Delete"
157
+ })]
158
+ })
159
+ }
160
+ ],
161
+ data: C.chartOfAccounts,
162
+ keyField: "id",
163
+ pageSize: 20
164
+ }),
165
+ /* @__PURE__ */ m(l, {
166
+ open: E,
167
+ onClose: () => D(!1),
168
+ title: O ? "Edit account" : "New account",
169
+ size: "md",
170
+ footer: /* @__PURE__ */ h("div", {
171
+ className: "flex justify-end gap-2",
172
+ children: [/* @__PURE__ */ m(g, {
173
+ variant: "outline",
174
+ onClick: () => D(!1),
175
+ children: "Cancel"
176
+ }), /* @__PURE__ */ m(g, {
177
+ onClick: B,
178
+ disabled: I,
179
+ children: "Save"
180
+ })]
181
+ }),
182
+ children: /* @__PURE__ */ h("div", {
183
+ className: "space-y-3",
184
+ children: [/* @__PURE__ */ h("div", {
185
+ className: "grid grid-cols-3 gap-3",
186
+ children: [/* @__PURE__ */ h("label", {
187
+ className: "block text-sm",
188
+ children: [/* @__PURE__ */ m("span", {
189
+ className: "mb-1 block text-text-secondary",
190
+ children: "Code"
191
+ }), /* @__PURE__ */ m("input", {
192
+ value: A,
193
+ onChange: (e) => j(e.target.value),
194
+ className: _,
195
+ placeholder: "5100",
196
+ disabled: !!O
197
+ })]
198
+ }), /* @__PURE__ */ h("label", {
199
+ className: "col-span-2 block text-sm",
200
+ children: [/* @__PURE__ */ m("span", {
201
+ className: "mb-1 block text-text-secondary",
202
+ children: "Name"
203
+ }), /* @__PURE__ */ m("input", {
204
+ value: M,
205
+ onChange: (e) => N(e.target.value),
206
+ className: _,
207
+ placeholder: "Seeds & Inputs"
208
+ })]
209
+ })]
210
+ }), /* @__PURE__ */ h("label", {
211
+ className: "block text-sm",
212
+ children: [/* @__PURE__ */ m("span", {
213
+ className: "mb-1 block text-text-secondary",
214
+ children: "Type"
215
+ }), /* @__PURE__ */ m("select", {
216
+ value: P,
217
+ onChange: (e) => F(e.target.value),
218
+ className: _,
219
+ children: v.map((e) => /* @__PURE__ */ m("option", {
220
+ value: e,
221
+ children: e.charAt(0) + e.slice(1).toLowerCase()
222
+ }, e))
223
+ })]
224
+ })]
225
+ })
226
+ })
227
+ ]
228
+ });
229
+ }
230
+ //#endregion
231
+ export { y as ChartOfAccountsPage };
232
+
233
+ //# sourceMappingURL=ChartOfAccountsPage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChartOfAccountsPage.js","names":[],"sources":["../../../../src/healthybowl/pages/financial/ChartOfAccountsPage.tsx"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport {\n PageLayout,\n DataTable,\n StatusBadge,\n Modal,\n LoadingSkeleton,\n ErrorState,\n EmptyState,\n ToastContainer,\n useConfirm,\n} from '../../components';\nimport type { Column } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { formatCurrency } from '../../utils/helpers';\nimport { useHealthyBowlAccounting } from '../../hooks/useHealthyBowlAccounting';\nimport type { LedgerAccount } from '../../hooks/useHealthyBowlAccounting';\n\nconst INPUT_CLASS =\n '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)]';\nconst TYPES = ['ASSET', 'LIABILITY', 'EQUITY', 'INCOME', 'EXPENSE'];\n\nexport function ChartOfAccountsPage() {\n const { toasts, toast, dismiss } = useToast();\n const confirm = useConfirm();\n const acc = useHealthyBowlAccounting({ chartOfAccounts: true });\n const [seeded, setSeeded] = useState(false);\n const [open, setOpen] = useState(false);\n const [editing, setEditing] = useState<LedgerAccount | null>(null);\n const [code, setCode] = useState('');\n const [name, setName] = useState('');\n const [accountType, setAccountType] = useState('EXPENSE');\n const [busy, setBusy] = useState(false);\n\n useEffect(() => {\n if (seeded) return;\n if (!acc.loading && acc.chartOfAccounts.length === 0 && !acc.error) {\n setSeeded(true);\n acc.ensureChartOfAccounts().catch(() => undefined);\n }\n }, [acc, seeded]);\n\n const openCreate = () => {\n setEditing(null);\n setCode('');\n setName('');\n setAccountType('EXPENSE');\n setOpen(true);\n };\n const openEdit = (a: LedgerAccount) => {\n setEditing(a);\n setCode(a.code);\n setName(a.name);\n setAccountType(a.accountType);\n setOpen(true);\n };\n\n const save = async () => {\n if (!name.trim() || (!editing && !code.trim())) {\n toast({ title: 'Code and name are required', variant: 'error' });\n return;\n }\n setBusy(true);\n try {\n if (editing) {\n await acc.updateAccount({ id: editing.id, name: name.trim(), accountType });\n toast({ title: 'Account updated', variant: 'success' });\n } else {\n await acc.createAccount({ code: code.trim(), name: name.trim(), accountType });\n toast({ title: 'Account created', variant: 'success' });\n }\n setOpen(false);\n } catch (err) {\n toast({ title: 'Save failed', description: err instanceof Error ? err.message : undefined, variant: 'error' });\n } finally {\n setBusy(false);\n }\n };\n\n const remove = async (a: LedgerAccount) => {\n const ok = await confirm({\n title: 'Delete account?',\n message: `Delete \"${a.code} · ${a.name}\"? Accounts used by entries cannot be deleted.`,\n });\n if (!ok) return;\n try {\n await acc.deleteAccount(a.id);\n toast({ title: 'Account deleted', variant: 'success' });\n } catch (err) {\n toast({ title: 'Delete failed', description: err instanceof Error ? err.message : undefined, variant: 'error' });\n }\n };\n\n const columns: Column<LedgerAccount>[] = [\n { key: 'code', header: 'Code', render: (a) => a.code },\n { key: 'name', header: 'Name', render: (a) => a.name },\n { key: 'accountType', header: 'Type', render: (a) => a.accountType },\n { key: 'normalBalance', header: 'Normal', render: (a) => a.normalBalance },\n { key: 'balance', header: 'Balance (₹)', className: 'text-right', render: (a) => formatCurrency(a.balance, 'INR') },\n {\n key: 'isActive',\n header: 'Active',\n render: (a) => (\n <StatusBadge variant={a.isActive ? 'success' : 'muted'} label={a.isActive ? 'Active' : 'Inactive'} />\n ),\n },\n {\n key: 'actions',\n header: '',\n render: (a) => (\n <div className=\"flex justify-end gap-1\">\n <Button variant=\"ghost\" size=\"sm\" onClick={() => openEdit(a)}>\n Edit\n </Button>\n {!a.isSystem && (\n <Button variant=\"ghost\" size=\"sm\" onClick={() => remove(a)}>\n Delete\n </Button>\n )}\n </div>\n ),\n },\n ];\n\n return (\n <PageLayout\n title=\"Chart of Accounts\"\n description=\"The accounts your double-entry ledger posts to.\"\n actions={<Button onClick={openCreate}>New account</Button>}\n >\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n {acc.error && acc.chartOfAccounts.length === 0 ? (\n <ErrorState title=\"Could not load accounts\" description={acc.error.message} />\n ) : acc.loading && acc.chartOfAccounts.length === 0 ? (\n <LoadingSkeleton variant=\"table\" count={8} />\n ) : acc.chartOfAccounts.length === 0 ? (\n <EmptyState title=\"No accounts yet\" description=\"A default chart of accounts is being set up…\" />\n ) : (\n <DataTable columns={columns} data={acc.chartOfAccounts} keyField=\"id\" pageSize={20} />\n )}\n\n <Modal\n open={open}\n onClose={() => setOpen(false)}\n title={editing ? 'Edit account' : 'New account'}\n size=\"md\"\n footer={\n <div className=\"flex justify-end gap-2\">\n <Button variant=\"outline\" onClick={() => setOpen(false)}>\n Cancel\n </Button>\n <Button onClick={save} disabled={busy}>\n Save\n </Button>\n </div>\n }\n >\n <div className=\"space-y-3\">\n <div className=\"grid grid-cols-3 gap-3\">\n <label className=\"block text-sm\">\n <span className=\"mb-1 block text-text-secondary\">Code</span>\n <input\n value={code}\n onChange={(e) => setCode(e.target.value)}\n className={INPUT_CLASS}\n placeholder=\"5100\"\n disabled={!!editing}\n />\n </label>\n <label className=\"col-span-2 block text-sm\">\n <span className=\"mb-1 block text-text-secondary\">Name</span>\n <input\n value={name}\n onChange={(e) => setName(e.target.value)}\n className={INPUT_CLASS}\n placeholder=\"Seeds & Inputs\"\n />\n </label>\n </div>\n <label className=\"block text-sm\">\n <span className=\"mb-1 block text-text-secondary\">Type</span>\n <select value={accountType} onChange={(e) => setAccountType(e.target.value)} className={INPUT_CLASS}>\n {TYPES.map((t) => (\n <option key={t} value={t}>\n {t.charAt(0) + t.slice(1).toLowerCase()}\n </option>\n ))}\n </select>\n </label>\n </div>\n </Modal>\n </PageLayout>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,IAAM,IACJ,uMACI,IAAQ;CAAC;CAAS;CAAa;CAAU;CAAU;CAAU;AAEnE,SAAgB,IAAsB;CACpC,IAAM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