@burdenoff/microfe-healthybowl 2026.813.4 → 2026.813.5
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/useHealthyBowlAccounting.js +7 -0
- package/dist/healthybowl/hooks/useHealthyBowlAccounting.js.map +1 -1
- package/dist/healthybowl/pages/financial/AccountingIntegrationsPage.js +149 -123
- package/dist/healthybowl/pages/financial/AccountingIntegrationsPage.js.map +1 -1
- package/dist/healthybowl/pages/financial/FarmAccountingPage.js +5 -5
- package/dist/healthybowl/pages/financial/ProfitLossPage.js +5 -5
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useHealthyBowlAccounting.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlAccounting.ts"],"sourcesContent":["/**\n * Farm Accounting — data hook (BOFF-2888 · roadmap 16).\n *\n * Chart of accounts, double-entry general ledger, Profit & Loss (+ CSV/PDF export),\n * cost-by-crop / per-animal profitability, and Tally/Zoho/QuickBooks integrations.\n * Documents are declared inline with `gql` (not `src/operations/wspace/*.graphql`)\n * because codegen validates operations against the committed `graphql/wspace.graphql`\n * snapshot, which can't know about these fields until the accounting subgraph is live\n * in the supergraph — the same escape hatch `useHealthyBowlDistribution` uses. Types\n * mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/accounting.gql`.\n *\n * Reads use `cache-and-network`; pages opt into only the sections they render (all\n * default off). Every write throws on error then reconciles the reads it invalidates.\n */\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\nconst FALLBACK_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001';\n\n// ── types (mirror accounting.gql) ─────────────────────────────────────────────\nexport type AccountType = 'ASSET' | 'LIABILITY' | 'EQUITY' | 'INCOME' | 'EXPENSE';\nexport type AccountingProvider = 'TALLY' | 'ZOHO_BOOKS' | 'QUICKBOOKS';\nexport type CostCenterKind = 'CROP' | 'ANIMAL' | 'OTHER';\n\nexport interface LedgerAccount {\n id: string;\n code: string;\n name: string;\n accountType: string;\n normalBalance: string;\n description: string | null;\n isActive: boolean;\n isSystem: boolean;\n sortOrder: number;\n balance: number;\n createdAt: string;\n updatedAt: string;\n}\nexport interface JournalLine {\n id: string;\n accountId: string;\n accountCode: string;\n accountName: string;\n accountType: string;\n description: string | null;\n debit: number;\n credit: number;\n costCenterId: string | null;\n costCenterLabel: string | null;\n lineOrder: number;\n}\nexport interface JournalEntry {\n id: string;\n entryNumber: string;\n date: string;\n memo: string;\n reference: string | null;\n status: string;\n source: string;\n totalDebit: number;\n totalCredit: number;\n balanced: boolean;\n billingOrderId: string | null;\n billingSyncStatus: string | null;\n postedAt: string | null;\n lines: JournalLine[];\n createdAt: string;\n updatedAt: string;\n}\nexport interface GeneralLedgerRow {\n id: string;\n entryId: string;\n entryNumber: string;\n date: string;\n accountCode: string;\n accountName: string;\n accountType: string;\n description: string | null;\n reference: string | null;\n debit: number;\n credit: number;\n runningBalance: number;\n costCenterLabel: string | null;\n}\nexport interface GeneralLedger {\n rows: GeneralLedgerRow[];\n totalDebit: number;\n totalCredit: number;\n rowCount: number;\n hasMore: boolean;\n}\nexport interface PnlLine {\n code: string;\n name: string;\n amount: number;\n}\nexport interface ProfitAndLoss {\n periodLabel: string;\n currency: string;\n income: PnlLine[];\n expenses: PnlLine[];\n totalRevenue: number;\n totalExpenses: number;\n netProfit: number;\n grossMarginPct: number;\n generatedAt: string;\n}\n/**\n * BOFF-6026 — the three standard statements, derived from the same posted journal lines the P&L\n * already uses. Each carries its own integrity flag: these documents go to a lender, so one that is\n * quietly wrong is worse than one that admits it cannot be trusted.\n */\nexport interface TrialBalanceRow {\n accountCode: string;\n accountName: string;\n accountType: string;\n totalDebit: number;\n totalCredit: number;\n /** Reported on the account's natural side, so a credit-natured account reads positive. */\n balance: number;\n}\nexport interface TrialBalance {\n periodLabel: string;\n currency: string;\n rows: TrialBalanceRow[];\n totalDebit: number;\n totalCredit: number;\n isBalanced: boolean;\n difference: number;\n}\nexport interface StatementLine {\n accountCode: string;\n accountName: string;\n amount: number;\n}\nexport interface BalanceSheet {\n asOfLabel: string;\n currency: string;\n assets: StatementLine[];\n liabilities: StatementLine[];\n equity: StatementLine[];\n totalAssets: number;\n totalLiabilities: number;\n totalEquityAccounts: number;\n /** Cumulative income − expense. Without it, assets never equal liabilities plus equity. */\n retainedEarnings: number;\n totalEquity: number;\n totalLiabilitiesAndEquity: number;\n isBalanced: boolean;\n difference: number;\n}\nexport interface CashFlowLine extends StatementLine {\n category: 'OPERATING' | 'INVESTING' | 'FINANCING';\n}\nexport interface CashFlowStatement {\n periodLabel: string;\n currency: string;\n operating: CashFlowLine[];\n investing: CashFlowLine[];\n financing: CashFlowLine[];\n netOperating: number;\n netInvesting: number;\n netFinancing: number;\n netChangeInCash: number;\n /** Movement summed straight off the cash accounts — must equal netChangeInCash. */\n cashAccountMovement: number;\n isReconciled: boolean;\n difference: number;\n cashAccounts: StatementLine[];\n unclassifiedCount: number;\n /** True when the period held more lines than one statement can read. */\n isTruncated: boolean;\n entryLimit: number;\n}\nexport interface AccountingExport {\n format: string;\n filename: string;\n mimeType: string;\n contentBase64: string;\n byteSize: number;\n}\nexport interface CostCenter {\n id: string;\n code: string;\n label: string;\n kind: string;\n refType: string | null;\n refId: string | null;\n season: string | null;\n yieldQuantity: number;\n yieldUnit: string;\n isActive: boolean;\n createdAt: string;\n updatedAt: string;\n}\nexport interface CropProfitability {\n costCenterId: string;\n code: string;\n label: string;\n kind: string;\n yieldQuantity: number;\n yieldUnit: string;\n totalCost: number;\n revenue: number;\n costPerKg: number | null;\n revenuePerKg: number | null;\n grossMarginPct: number | null;\n}\nexport interface CostAllocationSlice {\n label: string;\n amount: number;\n percent: number;\n}\nexport interface CostByCropReport {\n rows: CropProfitability[];\n allocation: CostAllocationSlice[];\n totalRevenue: number;\n totalCost: number;\n grossMarginPct: number;\n bestMarginLabel: string | null;\n bestMarginPct: number | null;\n}\nexport interface AccountingIntegration {\n id: string;\n provider: string;\n status: string;\n displayName: string | null;\n endpoint: string | null;\n organizationRef: string | null;\n lastSyncedAt: string | null;\n entriesPushed: number;\n autoSyncDaily: boolean;\n pushInvoices: boolean;\n syncCoaMapping: boolean;\n}\nexport interface AccountingSyncLog {\n id: string;\n provider: string;\n entriesCount: number;\n status: string;\n message: string | null;\n batchRef: string | null;\n syncedAt: string;\n}\nexport interface IntegrationsPayload {\n integrations: AccountingIntegration[];\n syncLogs: AccountingSyncLog[];\n autoSyncDaily: boolean;\n pushInvoices: boolean;\n syncCoaMapping: boolean;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\nexport interface JournalLineInput {\n accountId?: string | null;\n accountCode?: string | null;\n description?: string | null;\n debit?: number;\n credit?: number;\n costCenterId?: string | null;\n}\n\n// ── fragments ──────────────────────────────────────────────────────────────────\nconst ACCOUNT_FIELDS = `id code name accountType normalBalance description isActive isSystem sortOrder balance createdAt updatedAt`;\nconst LINE_FIELDS = `id accountId accountCode accountName accountType description debit credit costCenterId costCenterLabel lineOrder`;\nconst ENTRY_FIELDS = `id entryNumber date memo reference status source totalDebit totalCredit balanced billingOrderId billingSyncStatus postedAt lines { ${LINE_FIELDS} } createdAt updatedAt`;\nconst GL_FIELDS = `rows { id entryId entryNumber date accountCode accountName accountType description reference debit credit runningBalance costCenterLabel } totalDebit totalCredit rowCount hasMore`;\nconst PNL_FIELDS = `periodLabel currency income { code name amount } expenses { code name amount } totalRevenue totalExpenses netProfit grossMarginPct generatedAt`;\nconst COST_CENTER_FIELDS = `id code label kind refType refId season yieldQuantity yieldUnit isActive createdAt updatedAt`;\nconst COST_BY_CROP_FIELDS = `rows { costCenterId code label kind yieldQuantity yieldUnit totalCost revenue costPerKg revenuePerKg grossMarginPct } allocation { label amount percent } totalRevenue totalCost grossMarginPct bestMarginLabel bestMarginPct`;\nconst INTEGRATIONS_FIELDS = `integrations { id provider status displayName endpoint organizationRef lastSyncedAt entriesPushed autoSyncDaily pushInvoices syncCoaMapping } syncLogs { id provider entriesCount status message batchRef syncedAt } autoSyncDaily pushInvoices syncCoaMapping`;\n\n// ── queries ─────────────────────────────────────────────────────────────────────\nconst GET_CHART_OF_ACCOUNTS = gql`query HbChartOfAccounts($context: ContextInput!, $accountType: String, $activeOnly: Boolean) {\n getHealthyBowlChartOfAccounts(context: $context, accountType: $accountType, activeOnly: $activeOnly) { ${ACCOUNT_FIELDS} } }`;\nconst GET_GENERAL_LEDGER = gql`query HbGeneralLedger($context: ContextInput!, $accountType: String, $accountId: ID, $startDate: String, $endDate: String, $search: String, $limit: Int, $offset: Int) {\n getHealthyBowlGeneralLedger(context: $context, accountType: $accountType, accountId: $accountId, startDate: $startDate, endDate: $endDate, search: $search, limit: $limit, offset: $offset) { ${GL_FIELDS} } }`;\nconst GET_JOURNAL_ENTRIES = gql`query HbJournalEntries($context: ContextInput!, $status: String, $startDate: String, $endDate: String, $limit: Int, $offset: Int) {\n getHealthyBowlJournalEntries(context: $context, status: $status, startDate: $startDate, endDate: $endDate, limit: $limit, offset: $offset) { ${ENTRY_FIELDS} } }`;\nconst GET_PROFIT_AND_LOSS = gql`query HbProfitAndLoss($context: ContextInput!, $startDate: String!, $endDate: String!) {\n getHealthyBowlProfitAndLoss(context: $context, startDate: $startDate, endDate: $endDate) { ${PNL_FIELDS} } }`;\nconst GET_PNL_EXPORT = gql`\n query HbPnlExport($context: ContextInput!, $startDate: String!, $endDate: String!, $format: String!) {\n getHealthyBowlProfitAndLossExport(context: $context, startDate: $startDate, endDate: $endDate, format: $format) {\n format\n filename\n mimeType\n contentBase64\n byteSize\n }\n }\n`;\n// BOFF-6026 — trial balance, balance sheet and cash flow.\nconst TRIAL_BALANCE_FIELDS = `periodLabel currency totalDebit totalCredit isBalanced difference rows { accountCode accountName accountType totalDebit totalCredit balance }`;\nconst BALANCE_SHEET_FIELDS = `asOfLabel currency assets { accountCode accountName amount } liabilities { accountCode accountName amount } equity { accountCode accountName amount } totalAssets totalLiabilities totalEquityAccounts retainedEarnings totalEquity totalLiabilitiesAndEquity isBalanced difference`;\nconst CASH_FLOW_FIELDS = `periodLabel currency operating { accountCode accountName category amount } investing { accountCode accountName category amount } financing { accountCode accountName category amount } netOperating netInvesting netFinancing netChangeInCash cashAccountMovement isReconciled difference cashAccounts { accountCode accountName amount } unclassifiedCount isTruncated entryLimit`;\nconst GET_TRIAL_BALANCE = gql`query HbTrialBalance($context: ContextInput!, $startDate: String!, $endDate: String!) {\n getHealthyBowlTrialBalance(context: $context, startDate: $startDate, endDate: $endDate) { ${TRIAL_BALANCE_FIELDS} } }`;\nconst GET_BALANCE_SHEET = gql`query HbBalanceSheet($context: ContextInput!, $asOfDate: String!) {\n getHealthyBowlBalanceSheet(context: $context, asOfDate: $asOfDate) { ${BALANCE_SHEET_FIELDS} } }`;\nconst GET_CASH_FLOW = gql`query HbCashFlow($context: ContextInput!, $startDate: String!, $endDate: String!) {\n getHealthyBowlCashFlowStatement(context: $context, startDate: $startDate, endDate: $endDate) { ${CASH_FLOW_FIELDS} } }`;\nconst GET_COST_BY_CROP = gql`query HbCostByCrop($context: ContextInput!, $startDate: String, $endDate: String, $kind: String) {\n getHealthyBowlCostByCrop(context: $context, startDate: $startDate, endDate: $endDate, kind: $kind) { ${COST_BY_CROP_FIELDS} } }`;\nconst GET_COST_CENTERS = gql`query HbCostCenters($context: ContextInput!, $kind: String, $activeOnly: Boolean) {\n getHealthyBowlCostCenters(context: $context, kind: $kind, activeOnly: $activeOnly) { ${COST_CENTER_FIELDS} } }`;\nconst GET_INTEGRATIONS = gql`query HbAccountingIntegrations($context: ContextInput!) {\n getHealthyBowlAccountingIntegrations(context: $context) { ${INTEGRATIONS_FIELDS} } }`;\n\n// ── mutations ─────────────────────────────────────────────────────────────────\nconst ENSURE_COA = gql`mutation HbEnsureCoa($context: ContextInput!) { ensureHealthyBowlChartOfAccounts(context: $context) { ${ACCOUNT_FIELDS} } }`;\nconst CREATE_ACCOUNT = gql`mutation HbCreateAccount($input: CreateHealthyBowlLedgerAccountInput!) { createHealthyBowlLedgerAccount(input: $input) { ${ACCOUNT_FIELDS} } }`;\nconst UPDATE_ACCOUNT = gql`mutation HbUpdateAccount($input: UpdateHealthyBowlLedgerAccountInput!) { updateHealthyBowlLedgerAccount(input: $input) { ${ACCOUNT_FIELDS} } }`;\nconst DELETE_ACCOUNT = gql`\n mutation HbDeleteAccount($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlLedgerAccount(id: $id, context: $context)\n }\n`;\nconst POST_ENTRY = gql`mutation HbPostEntry($input: PostHealthyBowlJournalEntryInput!) { postHealthyBowlJournalEntry(input: $input) { ${ENTRY_FIELDS} } }`;\nconst SAVE_DRAFT = gql`mutation HbSaveDraft($input: PostHealthyBowlJournalEntryInput!) { saveHealthyBowlJournalEntryDraft(input: $input) { ${ENTRY_FIELDS} } }`;\nconst VOID_ENTRY = gql`mutation HbVoidEntry($id: ID!, $context: ContextInput!) { voidHealthyBowlJournalEntry(id: $id, context: $context) { ${ENTRY_FIELDS} } }`;\nconst PUSH_TO_BILLING = gql`mutation HbPushBilling($id: ID!, $context: ContextInput!) { pushHealthyBowlJournalEntryToBilling(id: $id, context: $context) { ${ENTRY_FIELDS} } }`;\nconst CREATE_COST_CENTER = gql`mutation HbCreateCostCenter($input: CreateHealthyBowlCostCenterInput!) { createHealthyBowlCostCenter(input: $input) { ${COST_CENTER_FIELDS} } }`;\nconst UPDATE_COST_CENTER = gql`mutation HbUpdateCostCenter($input: UpdateHealthyBowlCostCenterInput!) { updateHealthyBowlCostCenter(input: $input) { ${COST_CENTER_FIELDS} } }`;\nconst DELETE_COST_CENTER = gql`\n mutation HbDeleteCostCenter($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlCostCenter(id: $id, context: $context)\n }\n`;\nconst CONNECT_INTEGRATION = gql`\n mutation HbConnect($input: ConnectHealthyBowlAccountingIntegrationInput!) {\n connectHealthyBowlAccountingIntegration(input: $input) {\n id\n provider\n status\n }\n }\n`;\nconst DISCONNECT_INTEGRATION = gql`\n mutation HbDisconnect($provider: String!, $context: ContextInput!) {\n disconnectHealthyBowlAccountingIntegration(provider: $provider, context: $context) {\n id\n provider\n status\n }\n }\n`;\nconst UPDATE_SYNC_SETTINGS = gql`mutation HbSyncSettings($input: UpdateHealthyBowlAccountingSyncSettingsInput!) { updateHealthyBowlAccountingSyncSettings(input: $input) { ${INTEGRATIONS_FIELDS} } }`;\nconst SYNC_INTEGRATION = gql`\n mutation HbSync($input: SyncHealthyBowlAccountingInput!) {\n syncHealthyBowlAccountingIntegration(input: $input) {\n provider\n status\n entriesCount\n message\n log {\n id\n provider\n entriesCount\n status\n message\n batchRef\n syncedAt\n }\n integration {\n id\n provider\n status\n entriesPushed\n lastSyncedAt\n }\n }\n }\n`;\n\nexport interface UseAccountingOptions {\n chartOfAccounts?: boolean;\n chartOfAccountsType?: string | null;\n generalLedger?: boolean;\n ledgerFilters?: {\n accountType?: string | null;\n accountId?: string | null;\n startDate?: string | null;\n endDate?: string | null;\n search?: string | null;\n limit?: number | null;\n offset?: number | null;\n };\n journalEntries?: boolean;\n profitAndLoss?: boolean;\n pnlRange?: { startDate: string; endDate: string };\n /** BOFF-6026 — the three statements share `statementRange`; the balance sheet uses its endDate. */\n trialBalance?: boolean;\n balanceSheet?: boolean;\n cashFlow?: boolean;\n statementRange?: { startDate: string; endDate: string };\n costByCrop?: boolean;\n costByCropParams?: { startDate?: string | null; endDate?: string | null; kind?: string | null };\n costCenters?: boolean;\n integrations?: boolean;\n}\n\nexport function useHealthyBowlAccounting(options: UseAccountingOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const context = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n const withCtx = useCallback(<T extends object>(input: T) => ({ ...input, context }), [context]);\n\n const coaQuery = useQuery<{ getHealthyBowlChartOfAccounts: LedgerAccount[] }>(GET_CHART_OF_ACCOUNTS, {\n variables: { context, accountType: options.chartOfAccountsType ?? null, activeOnly: false },\n fetchPolicy: 'cache-and-network',\n skip: !options.chartOfAccounts,\n });\n const glQuery = useQuery<{ getHealthyBowlGeneralLedger: GeneralLedger }>(GET_GENERAL_LEDGER, {\n variables: { context, ...options.ledgerFilters },\n fetchPolicy: 'cache-and-network',\n skip: !options.generalLedger,\n });\n const entriesQuery = useQuery<{ getHealthyBowlJournalEntries: JournalEntry[] }>(GET_JOURNAL_ENTRIES, {\n variables: { context, limit: 50 },\n fetchPolicy: 'cache-and-network',\n skip: !options.journalEntries,\n });\n const pnlQuery = useQuery<{ getHealthyBowlProfitAndLoss: ProfitAndLoss }>(GET_PROFIT_AND_LOSS, {\n variables: { context, startDate: options.pnlRange?.startDate ?? '', endDate: options.pnlRange?.endDate ?? '' },\n fetchPolicy: 'cache-and-network',\n skip: !options.profitAndLoss || !options.pnlRange,\n });\n const tbQuery = useQuery<{ getHealthyBowlTrialBalance: TrialBalance }>(GET_TRIAL_BALANCE, {\n variables: {\n context,\n startDate: options.statementRange?.startDate ?? '',\n endDate: options.statementRange?.endDate ?? '',\n },\n fetchPolicy: 'cache-and-network',\n skip: !options.trialBalance || !options.statementRange,\n });\n const bsQuery = useQuery<{ getHealthyBowlBalanceSheet: BalanceSheet }>(GET_BALANCE_SHEET, {\n // A balance sheet is a position on a date, not a period, so only the end of the range applies.\n variables: { context, asOfDate: options.statementRange?.endDate ?? '' },\n fetchPolicy: 'cache-and-network',\n skip: !options.balanceSheet || !options.statementRange,\n });\n const cfQuery = useQuery<{ getHealthyBowlCashFlowStatement: CashFlowStatement }>(GET_CASH_FLOW, {\n variables: {\n context,\n startDate: options.statementRange?.startDate ?? '',\n endDate: options.statementRange?.endDate ?? '',\n },\n fetchPolicy: 'cache-and-network',\n skip: !options.cashFlow || !options.statementRange,\n });\n const cbcQuery = useQuery<{ getHealthyBowlCostByCrop: CostByCropReport }>(GET_COST_BY_CROP, {\n variables: {\n context,\n startDate: options.costByCropParams?.startDate ?? null,\n endDate: options.costByCropParams?.endDate ?? null,\n kind: options.costByCropParams?.kind ?? null,\n },\n fetchPolicy: 'cache-and-network',\n skip: !options.costByCrop,\n });\n const centersQuery = useQuery<{ getHealthyBowlCostCenters: CostCenter[] }>(GET_COST_CENTERS, {\n variables: { context, activeOnly: false },\n fetchPolicy: 'cache-and-network',\n skip: !options.costCenters,\n });\n const integrationsQuery = useQuery<{ getHealthyBowlAccountingIntegrations: IntegrationsPayload }>(GET_INTEGRATIONS, {\n variables: { context },\n fetchPolicy: 'cache-and-network',\n skip: !options.integrations,\n });\n\n const reconcile = useCallback(async () => {\n const jobs: Promise<unknown>[] = [];\n if (options.chartOfAccounts) jobs.push(coaQuery.refetch());\n if (options.generalLedger) jobs.push(glQuery.refetch());\n if (options.journalEntries) jobs.push(entriesQuery.refetch());\n if (options.profitAndLoss && options.pnlRange) jobs.push(pnlQuery.refetch());\n if (options.trialBalance && options.statementRange) jobs.push(tbQuery.refetch());\n if (options.balanceSheet && options.statementRange) jobs.push(bsQuery.refetch());\n if (options.cashFlow && options.statementRange) jobs.push(cfQuery.refetch());\n if (options.costByCrop) jobs.push(cbcQuery.refetch());\n if (options.costCenters) jobs.push(centersQuery.refetch());\n if (options.integrations) jobs.push(integrationsQuery.refetch());\n await Promise.all(jobs);\n }, [\n options,\n coaQuery,\n glQuery,\n entriesQuery,\n pnlQuery,\n tbQuery,\n bsQuery,\n cfQuery,\n cbcQuery,\n centersQuery,\n integrationsQuery,\n ]);\n\n const [ensureCoaM] = useMutation(ENSURE_COA);\n const [createAccountM] = useMutation(CREATE_ACCOUNT);\n const [updateAccountM] = useMutation(UPDATE_ACCOUNT);\n const [deleteAccountM] = useMutation(DELETE_ACCOUNT);\n const [postEntryM] = useMutation(POST_ENTRY);\n const [saveDraftM] = useMutation(SAVE_DRAFT);\n const [voidEntryM] = useMutation(VOID_ENTRY);\n const [pushBillingM] = useMutation(PUSH_TO_BILLING);\n const [createCenterM] = useMutation(CREATE_COST_CENTER);\n const [updateCenterM] = useMutation(UPDATE_COST_CENTER);\n const [deleteCenterM] = useMutation(DELETE_COST_CENTER);\n const [connectM] = useMutation(CONNECT_INTEGRATION);\n const [disconnectM] = useMutation(DISCONNECT_INTEGRATION);\n const [syncSettingsM] = useMutation(UPDATE_SYNC_SETTINGS);\n const [syncM] = useMutation(SYNC_INTEGRATION);\n const [pnlExportM] = useMutation(GET_PNL_EXPORT); // query-shaped, but invoked imperatively via useMutation for on-demand fetch\n\n const ensureChartOfAccounts = useCallback(async () => {\n const res = await ensureCoaM({ variables: { context } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { ensureHealthyBowlChartOfAccounts: LedgerAccount[] } | undefined)\n ?.ensureHealthyBowlChartOfAccounts ?? []\n );\n }, [ensureCoaM, context, reconcile]);\n\n const createAccount = useCallback(\n async (input: {\n code: string;\n name: string;\n accountType: string;\n description?: string | null;\n sortOrder?: number;\n }) => {\n const res = await createAccountM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [createAccountM, withCtx, reconcile]\n );\n const updateAccount = useCallback(\n async (input: {\n id: string;\n name?: string;\n accountType?: string;\n description?: string | null;\n isActive?: boolean;\n sortOrder?: number;\n }) => {\n const res = await updateAccountM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [updateAccountM, withCtx, reconcile]\n );\n const deleteAccount = useCallback(\n async (id: string) => {\n const res = await deleteAccountM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [deleteAccountM, context, reconcile]\n );\n\n const postJournalEntry = useCallback(\n async (input: {\n date?: string;\n memo: string;\n reference?: string | null;\n source?: string;\n lines: JournalLineInput[];\n }) => {\n const res = await postEntryM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { postHealthyBowlJournalEntry: JournalEntry } | undefined)?.postHealthyBowlJournalEntry ?? null\n );\n },\n [postEntryM, withCtx, reconcile]\n );\n const saveDraft = useCallback(\n async (input: {\n date?: string;\n memo: string;\n reference?: string | null;\n source?: string;\n lines: JournalLineInput[];\n }) => {\n const res = await saveDraftM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { saveHealthyBowlJournalEntryDraft: JournalEntry } | undefined)\n ?.saveHealthyBowlJournalEntryDraft ?? null\n );\n },\n [saveDraftM, withCtx, reconcile]\n );\n const voidEntry = useCallback(\n async (id: string) => {\n const res = await voidEntryM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [voidEntryM, context, reconcile]\n );\n const pushEntryToBilling = useCallback(\n async (id: string) => {\n const res = await pushBillingM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { pushHealthyBowlJournalEntryToBilling: JournalEntry } | undefined)\n ?.pushHealthyBowlJournalEntryToBilling ?? null\n );\n },\n [pushBillingM, context, reconcile]\n );\n\n const createCostCenter = useCallback(\n async (input: {\n code?: string;\n label: string;\n kind: string;\n refType?: string | null;\n refId?: string | null;\n season?: string | null;\n yieldQuantity?: number;\n yieldUnit?: string;\n }) => {\n const res = await createCenterM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [createCenterM, withCtx, reconcile]\n );\n const updateCostCenter = useCallback(\n async (input: {\n id: string;\n label?: string;\n kind?: string;\n season?: string | null;\n yieldQuantity?: number;\n yieldUnit?: string;\n isActive?: boolean;\n }) => {\n const res = await updateCenterM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [updateCenterM, withCtx, reconcile]\n );\n const deleteCostCenter = useCallback(\n async (id: string) => {\n const res = await deleteCenterM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [deleteCenterM, context, reconcile]\n );\n\n const connectIntegration = useCallback(\n async (input: {\n provider: string;\n displayName?: string | null;\n endpoint?: string | null;\n organizationRef?: string | null;\n }) => {\n const res = await connectM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [connectM, withCtx, reconcile]\n );\n const disconnectIntegration = useCallback(\n async (provider: string) => {\n const res = await disconnectM({ variables: { provider, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [disconnectM, context, reconcile]\n );\n const updateSyncSettings = useCallback(\n async (input: { autoSyncDaily?: boolean; pushInvoices?: boolean; syncCoaMapping?: boolean }) => {\n const res = await syncSettingsM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [syncSettingsM, withCtx, reconcile]\n );\n const syncIntegration = useCallback(\n async (provider: string) => {\n const res = await syncM({ variables: { input: withCtx({ provider }) } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (\n res.data as\n | { syncHealthyBowlAccountingIntegration: { status: string; entriesCount: number; message: string } }\n | undefined\n )?.syncHealthyBowlAccountingIntegration ?? null\n );\n },\n [syncM, withCtx, reconcile]\n );\n\n const exportProfitAndLoss = useCallback(\n async (startDate: string, endDate: string, format: 'CSV' | 'PDF'): Promise<AccountingExport | null> => {\n const res = await pnlExportM({ variables: { context, startDate, endDate, format } });\n if (res.error) throw res.error;\n return (\n (res.data as { getHealthyBowlProfitAndLossExport: AccountingExport } | undefined)\n ?.getHealthyBowlProfitAndLossExport ?? null\n );\n },\n [pnlExportM, context]\n );\n\n return {\n // data\n chartOfAccounts: coaQuery.data?.getHealthyBowlChartOfAccounts ?? [],\n generalLedger: glQuery.data?.getHealthyBowlGeneralLedger ?? null,\n journalEntries: entriesQuery.data?.getHealthyBowlJournalEntries ?? [],\n profitAndLoss: pnlQuery.data?.getHealthyBowlProfitAndLoss ?? null,\n trialBalance: tbQuery.data?.getHealthyBowlTrialBalance ?? null,\n balanceSheet: bsQuery.data?.getHealthyBowlBalanceSheet ?? null,\n cashFlow: cfQuery.data?.getHealthyBowlCashFlowStatement ?? null,\n costByCrop: cbcQuery.data?.getHealthyBowlCostByCrop ?? null,\n costCenters: centersQuery.data?.getHealthyBowlCostCenters ?? [],\n integrations: integrationsQuery.data?.getHealthyBowlAccountingIntegrations ?? null,\n // status\n loading:\n coaQuery.loading ||\n glQuery.loading ||\n entriesQuery.loading ||\n pnlQuery.loading ||\n tbQuery.loading ||\n bsQuery.loading ||\n cfQuery.loading ||\n cbcQuery.loading ||\n centersQuery.loading ||\n integrationsQuery.loading,\n error:\n coaQuery.error ||\n glQuery.error ||\n entriesQuery.error ||\n pnlQuery.error ||\n tbQuery.error ||\n bsQuery.error ||\n cfQuery.error ||\n cbcQuery.error ||\n centersQuery.error ||\n integrationsQuery.error ||\n null,\n reconcile,\n // mutations\n ensureChartOfAccounts,\n createAccount,\n updateAccount,\n deleteAccount,\n postJournalEntry,\n saveDraft,\n voidEntry,\n pushEntryToBilling,\n createCostCenter,\n updateCostCenter,\n deleteCostCenter,\n connectIntegration,\n disconnectIntegration,\n updateSyncSettings,\n syncIntegration,\n exportProfitAndLoss,\n };\n}\n"],"mappings":";;;;;AAmBA,IAAM,IAAwB,wCAwPxB,IAAiB,8GAEjB,IAAe,6QACf,IAAY,sLACZ,IAAa,kJACb,IAAqB,gGACrB,IAAsB,iOACtB,IAAsB,kQAGtB,IAAwB,CAAG;2GAC0E,EAAe,OACpH,IAAqB,CAAG;kMACoK,EAAU,OACtM,IAAsB,CAAG;iJACkH,EAAa,OACxJ,KAAsB,CAAG;+FACgE,EAAW,OACpG,KAAiB,CAAG;;;;;;;;;;GAYpB,IAAuB,iJACvB,IAAuB,uRACvB,IAAmB,sXACnB,IAAoB,CAAG;8FACiE,EAAqB,OAC7G,IAAoB,CAAG;yEAC4C,EAAqB,OACxF,IAAgB,CAAG;mGAC0E,EAAiB,OAC9G,IAAmB,CAAG;yGAC6E,EAAoB,OACvH,IAAmB,CAAG;yFAC6D,EAAmB,OACtG,IAAmB,CAAG;8DACkC,EAAoB,OAG5E,IAAa,CAAG,yGAAyG,EAAe,OACxI,IAAiB,CAAG,4HA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,EAAQ,SACR,EAAQ,SACR,EAAQ,SACR,EAAS,SACT,EAAa,SACb,EAAkB,SAClB;EACF;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
|
|
1
|
+
{"version":3,"file":"useHealthyBowlAccounting.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlAccounting.ts"],"sourcesContent":["/**\n * Farm Accounting — data hook (BOFF-2888 · roadmap 16).\n *\n * Chart of accounts, double-entry general ledger, Profit & Loss (+ CSV/PDF export),\n * cost-by-crop / per-animal profitability, and Tally/Zoho/QuickBooks integrations.\n * Documents are declared inline with `gql` (not `src/operations/wspace/*.graphql`)\n * because codegen validates operations against the committed `graphql/wspace.graphql`\n * snapshot, which can't know about these fields until the accounting subgraph is live\n * in the supergraph — the same escape hatch `useHealthyBowlDistribution` uses. Types\n * mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/accounting.gql`.\n *\n * Reads use `cache-and-network`; pages opt into only the sections they render (all\n * default off). Every write throws on error then reconciles the reads it invalidates.\n */\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\nconst FALLBACK_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001';\n\n// ── types (mirror accounting.gql) ─────────────────────────────────────────────\nexport type AccountType = 'ASSET' | 'LIABILITY' | 'EQUITY' | 'INCOME' | 'EXPENSE';\nexport type AccountingProvider = 'TALLY' | 'ZOHO_BOOKS' | 'QUICKBOOKS';\nexport type CostCenterKind = 'CROP' | 'ANIMAL' | 'OTHER';\n\nexport interface LedgerAccount {\n id: string;\n code: string;\n name: string;\n accountType: string;\n normalBalance: string;\n description: string | null;\n isActive: boolean;\n isSystem: boolean;\n sortOrder: number;\n balance: number;\n createdAt: string;\n updatedAt: string;\n}\nexport interface JournalLine {\n id: string;\n accountId: string;\n accountCode: string;\n accountName: string;\n accountType: string;\n description: string | null;\n debit: number;\n credit: number;\n costCenterId: string | null;\n costCenterLabel: string | null;\n lineOrder: number;\n}\nexport interface JournalEntry {\n id: string;\n entryNumber: string;\n date: string;\n memo: string;\n reference: string | null;\n status: string;\n source: string;\n totalDebit: number;\n totalCredit: number;\n balanced: boolean;\n billingOrderId: string | null;\n billingSyncStatus: string | null;\n postedAt: string | null;\n lines: JournalLine[];\n createdAt: string;\n updatedAt: string;\n}\nexport interface GeneralLedgerRow {\n id: string;\n entryId: string;\n entryNumber: string;\n date: string;\n accountCode: string;\n accountName: string;\n accountType: string;\n description: string | null;\n reference: string | null;\n debit: number;\n credit: number;\n runningBalance: number;\n costCenterLabel: string | null;\n}\nexport interface GeneralLedger {\n rows: GeneralLedgerRow[];\n totalDebit: number;\n totalCredit: number;\n rowCount: number;\n hasMore: boolean;\n}\nexport interface PnlLine {\n code: string;\n name: string;\n amount: number;\n}\nexport interface ProfitAndLoss {\n periodLabel: string;\n currency: string;\n income: PnlLine[];\n expenses: PnlLine[];\n totalRevenue: number;\n totalExpenses: number;\n netProfit: number;\n grossMarginPct: number;\n generatedAt: string;\n}\n/**\n * BOFF-6026 — the three standard statements, derived from the same posted journal lines the P&L\n * already uses. Each carries its own integrity flag: these documents go to a lender, so one that is\n * quietly wrong is worse than one that admits it cannot be trusted.\n */\nexport interface TrialBalanceRow {\n accountCode: string;\n accountName: string;\n accountType: string;\n totalDebit: number;\n totalCredit: number;\n /** Reported on the account's natural side, so a credit-natured account reads positive. */\n balance: number;\n}\nexport interface TrialBalance {\n periodLabel: string;\n currency: string;\n rows: TrialBalanceRow[];\n totalDebit: number;\n totalCredit: number;\n isBalanced: boolean;\n difference: number;\n}\nexport interface StatementLine {\n accountCode: string;\n accountName: string;\n amount: number;\n}\nexport interface BalanceSheet {\n asOfLabel: string;\n currency: string;\n assets: StatementLine[];\n liabilities: StatementLine[];\n equity: StatementLine[];\n totalAssets: number;\n totalLiabilities: number;\n totalEquityAccounts: number;\n /** Cumulative income − expense. Without it, assets never equal liabilities plus equity. */\n retainedEarnings: number;\n totalEquity: number;\n totalLiabilitiesAndEquity: number;\n isBalanced: boolean;\n difference: number;\n}\nexport interface CashFlowLine extends StatementLine {\n category: 'OPERATING' | 'INVESTING' | 'FINANCING';\n}\nexport interface CashFlowStatement {\n periodLabel: string;\n currency: string;\n operating: CashFlowLine[];\n investing: CashFlowLine[];\n financing: CashFlowLine[];\n netOperating: number;\n netInvesting: number;\n netFinancing: number;\n netChangeInCash: number;\n /** Movement summed straight off the cash accounts — must equal netChangeInCash. */\n cashAccountMovement: number;\n isReconciled: boolean;\n difference: number;\n cashAccounts: StatementLine[];\n unclassifiedCount: number;\n /** True when the period held more lines than one statement can read. */\n isTruncated: boolean;\n entryLimit: number;\n}\nexport interface AccountingExport {\n format: string;\n filename: string;\n mimeType: string;\n contentBase64: string;\n byteSize: number;\n}\nexport interface CostCenter {\n id: string;\n code: string;\n label: string;\n kind: string;\n refType: string | null;\n refId: string | null;\n season: string | null;\n yieldQuantity: number;\n yieldUnit: string;\n isActive: boolean;\n createdAt: string;\n updatedAt: string;\n}\nexport interface CropProfitability {\n costCenterId: string;\n code: string;\n label: string;\n kind: string;\n yieldQuantity: number;\n yieldUnit: string;\n totalCost: number;\n revenue: number;\n costPerKg: number | null;\n revenuePerKg: number | null;\n grossMarginPct: number | null;\n}\nexport interface CostAllocationSlice {\n label: string;\n amount: number;\n percent: number;\n}\nexport interface CostByCropReport {\n rows: CropProfitability[];\n allocation: CostAllocationSlice[];\n totalRevenue: number;\n totalCost: number;\n grossMarginPct: number;\n bestMarginLabel: string | null;\n bestMarginPct: number | null;\n}\nexport interface AccountingIntegration {\n id: string;\n provider: string;\n status: string;\n displayName: string | null;\n endpoint: string | null;\n organizationRef: string | null;\n lastSyncedAt: string | null;\n entriesPushed: number;\n autoSyncDaily: boolean;\n pushInvoices: boolean;\n syncCoaMapping: boolean;\n}\nexport interface AccountingSyncLog {\n id: string;\n provider: string;\n entriesCount: number;\n status: string;\n message: string | null;\n batchRef: string | null;\n syncedAt: string;\n}\nexport interface IntegrationsPayload {\n integrations: AccountingIntegration[];\n syncLogs: AccountingSyncLog[];\n autoSyncDaily: boolean;\n pushInvoices: boolean;\n syncCoaMapping: boolean;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\nexport interface JournalLineInput {\n accountId?: string | null;\n accountCode?: string | null;\n description?: string | null;\n debit?: number;\n credit?: number;\n costCenterId?: string | null;\n}\n\n// ── fragments ──────────────────────────────────────────────────────────────────\nconst ACCOUNT_FIELDS = `id code name accountType normalBalance description isActive isSystem sortOrder balance createdAt updatedAt`;\nconst LINE_FIELDS = `id accountId accountCode accountName accountType description debit credit costCenterId costCenterLabel lineOrder`;\nconst ENTRY_FIELDS = `id entryNumber date memo reference status source totalDebit totalCredit balanced billingOrderId billingSyncStatus postedAt lines { ${LINE_FIELDS} } createdAt updatedAt`;\nconst GL_FIELDS = `rows { id entryId entryNumber date accountCode accountName accountType description reference debit credit runningBalance costCenterLabel } totalDebit totalCredit rowCount hasMore`;\nconst PNL_FIELDS = `periodLabel currency income { code name amount } expenses { code name amount } totalRevenue totalExpenses netProfit grossMarginPct generatedAt`;\nconst COST_CENTER_FIELDS = `id code label kind refType refId season yieldQuantity yieldUnit isActive createdAt updatedAt`;\nconst COST_BY_CROP_FIELDS = `rows { costCenterId code label kind yieldQuantity yieldUnit totalCost revenue costPerKg revenuePerKg grossMarginPct } allocation { label amount percent } totalRevenue totalCost grossMarginPct bestMarginLabel bestMarginPct`;\nconst INTEGRATIONS_FIELDS = `integrations { id provider status displayName endpoint organizationRef lastSyncedAt entriesPushed autoSyncDaily pushInvoices syncCoaMapping } syncLogs { id provider entriesCount status message batchRef syncedAt } autoSyncDaily pushInvoices syncCoaMapping`;\n\n// ── queries ─────────────────────────────────────────────────────────────────────\nconst GET_CHART_OF_ACCOUNTS = gql`query HbChartOfAccounts($context: ContextInput!, $accountType: String, $activeOnly: Boolean) {\n getHealthyBowlChartOfAccounts(context: $context, accountType: $accountType, activeOnly: $activeOnly) { ${ACCOUNT_FIELDS} } }`;\nconst GET_GENERAL_LEDGER = gql`query HbGeneralLedger($context: ContextInput!, $accountType: String, $accountId: ID, $startDate: String, $endDate: String, $search: String, $limit: Int, $offset: Int) {\n getHealthyBowlGeneralLedger(context: $context, accountType: $accountType, accountId: $accountId, startDate: $startDate, endDate: $endDate, search: $search, limit: $limit, offset: $offset) { ${GL_FIELDS} } }`;\nconst GET_JOURNAL_ENTRIES = gql`query HbJournalEntries($context: ContextInput!, $status: String, $startDate: String, $endDate: String, $limit: Int, $offset: Int) {\n getHealthyBowlJournalEntries(context: $context, status: $status, startDate: $startDate, endDate: $endDate, limit: $limit, offset: $offset) { ${ENTRY_FIELDS} } }`;\nconst GET_PROFIT_AND_LOSS = gql`query HbProfitAndLoss($context: ContextInput!, $startDate: String!, $endDate: String!) {\n getHealthyBowlProfitAndLoss(context: $context, startDate: $startDate, endDate: $endDate) { ${PNL_FIELDS} } }`;\nconst GET_PNL_EXPORT = gql`\n query HbPnlExport($context: ContextInput!, $startDate: String!, $endDate: String!, $format: String!) {\n getHealthyBowlProfitAndLossExport(context: $context, startDate: $startDate, endDate: $endDate, format: $format) {\n format\n filename\n mimeType\n contentBase64\n byteSize\n }\n }\n`;\n// BOFF-6026 — trial balance, balance sheet and cash flow.\nconst TRIAL_BALANCE_FIELDS = `periodLabel currency totalDebit totalCredit isBalanced difference rows { accountCode accountName accountType totalDebit totalCredit balance }`;\nconst BALANCE_SHEET_FIELDS = `asOfLabel currency assets { accountCode accountName amount } liabilities { accountCode accountName amount } equity { accountCode accountName amount } totalAssets totalLiabilities totalEquityAccounts retainedEarnings totalEquity totalLiabilitiesAndEquity isBalanced difference`;\nconst CASH_FLOW_FIELDS = `periodLabel currency operating { accountCode accountName category amount } investing { accountCode accountName category amount } financing { accountCode accountName category amount } netOperating netInvesting netFinancing netChangeInCash cashAccountMovement isReconciled difference cashAccounts { accountCode accountName amount } unclassifiedCount isTruncated entryLimit`;\nconst GET_TRIAL_BALANCE = gql`query HbTrialBalance($context: ContextInput!, $startDate: String!, $endDate: String!) {\n getHealthyBowlTrialBalance(context: $context, startDate: $startDate, endDate: $endDate) { ${TRIAL_BALANCE_FIELDS} } }`;\nconst GET_BALANCE_SHEET = gql`query HbBalanceSheet($context: ContextInput!, $asOfDate: String!) {\n getHealthyBowlBalanceSheet(context: $context, asOfDate: $asOfDate) { ${BALANCE_SHEET_FIELDS} } }`;\nconst GET_CASH_FLOW = gql`query HbCashFlow($context: ContextInput!, $startDate: String!, $endDate: String!) {\n getHealthyBowlCashFlowStatement(context: $context, startDate: $startDate, endDate: $endDate) { ${CASH_FLOW_FIELDS} } }`;\nconst GET_COST_BY_CROP = gql`query HbCostByCrop($context: ContextInput!, $startDate: String, $endDate: String, $kind: String) {\n getHealthyBowlCostByCrop(context: $context, startDate: $startDate, endDate: $endDate, kind: $kind) { ${COST_BY_CROP_FIELDS} } }`;\nconst GET_COST_CENTERS = gql`query HbCostCenters($context: ContextInput!, $kind: String, $activeOnly: Boolean) {\n getHealthyBowlCostCenters(context: $context, kind: $kind, activeOnly: $activeOnly) { ${COST_CENTER_FIELDS} } }`;\nconst GET_INTEGRATIONS = gql`query HbAccountingIntegrations($context: ContextInput!) {\n getHealthyBowlAccountingIntegrations(context: $context) { ${INTEGRATIONS_FIELDS} } }`;\n\n// ── mutations ─────────────────────────────────────────────────────────────────\nconst ENSURE_COA = gql`mutation HbEnsureCoa($context: ContextInput!) { ensureHealthyBowlChartOfAccounts(context: $context) { ${ACCOUNT_FIELDS} } }`;\nconst CREATE_ACCOUNT = gql`mutation HbCreateAccount($input: CreateHealthyBowlLedgerAccountInput!) { createHealthyBowlLedgerAccount(input: $input) { ${ACCOUNT_FIELDS} } }`;\nconst UPDATE_ACCOUNT = gql`mutation HbUpdateAccount($input: UpdateHealthyBowlLedgerAccountInput!) { updateHealthyBowlLedgerAccount(input: $input) { ${ACCOUNT_FIELDS} } }`;\nconst DELETE_ACCOUNT = gql`\n mutation HbDeleteAccount($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlLedgerAccount(id: $id, context: $context)\n }\n`;\nconst POST_ENTRY = gql`mutation HbPostEntry($input: PostHealthyBowlJournalEntryInput!) { postHealthyBowlJournalEntry(input: $input) { ${ENTRY_FIELDS} } }`;\nconst SAVE_DRAFT = gql`mutation HbSaveDraft($input: PostHealthyBowlJournalEntryInput!) { saveHealthyBowlJournalEntryDraft(input: $input) { ${ENTRY_FIELDS} } }`;\nconst VOID_ENTRY = gql`mutation HbVoidEntry($id: ID!, $context: ContextInput!) { voidHealthyBowlJournalEntry(id: $id, context: $context) { ${ENTRY_FIELDS} } }`;\nconst PUSH_TO_BILLING = gql`mutation HbPushBilling($id: ID!, $context: ContextInput!) { pushHealthyBowlJournalEntryToBilling(id: $id, context: $context) { ${ENTRY_FIELDS} } }`;\nconst CREATE_COST_CENTER = gql`mutation HbCreateCostCenter($input: CreateHealthyBowlCostCenterInput!) { createHealthyBowlCostCenter(input: $input) { ${COST_CENTER_FIELDS} } }`;\nconst UPDATE_COST_CENTER = gql`mutation HbUpdateCostCenter($input: UpdateHealthyBowlCostCenterInput!) { updateHealthyBowlCostCenter(input: $input) { ${COST_CENTER_FIELDS} } }`;\nconst DELETE_COST_CENTER = gql`\n mutation HbDeleteCostCenter($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlCostCenter(id: $id, context: $context)\n }\n`;\nconst CONNECT_INTEGRATION = gql`\n mutation HbConnect($input: ConnectHealthyBowlAccountingIntegrationInput!) {\n connectHealthyBowlAccountingIntegration(input: $input) {\n id\n provider\n status\n }\n }\n`;\nconst DISCONNECT_INTEGRATION = gql`\n mutation HbDisconnect($provider: String!, $context: ContextInput!) {\n disconnectHealthyBowlAccountingIntegration(provider: $provider, context: $context) {\n id\n provider\n status\n }\n }\n`;\nconst UPDATE_SYNC_SETTINGS = gql`mutation HbSyncSettings($input: UpdateHealthyBowlAccountingSyncSettingsInput!) { updateHealthyBowlAccountingSyncSettings(input: $input) { ${INTEGRATIONS_FIELDS} } }`;\nconst SYNC_INTEGRATION = gql`\n mutation HbSync($input: SyncHealthyBowlAccountingInput!) {\n syncHealthyBowlAccountingIntegration(input: $input) {\n provider\n status\n entriesCount\n message\n log {\n id\n provider\n entriesCount\n status\n message\n batchRef\n syncedAt\n }\n integration {\n id\n provider\n status\n entriesPushed\n lastSyncedAt\n }\n batch {\n format\n filename\n mimeType\n contentBase64\n byteSize\n }\n }\n }\n`;\n\nexport interface UseAccountingOptions {\n chartOfAccounts?: boolean;\n chartOfAccountsType?: string | null;\n generalLedger?: boolean;\n ledgerFilters?: {\n accountType?: string | null;\n accountId?: string | null;\n startDate?: string | null;\n endDate?: string | null;\n search?: string | null;\n limit?: number | null;\n offset?: number | null;\n };\n journalEntries?: boolean;\n profitAndLoss?: boolean;\n pnlRange?: { startDate: string; endDate: string };\n /** BOFF-6026 — the three statements share `statementRange`; the balance sheet uses its endDate. */\n trialBalance?: boolean;\n balanceSheet?: boolean;\n cashFlow?: boolean;\n statementRange?: { startDate: string; endDate: string };\n costByCrop?: boolean;\n costByCropParams?: { startDate?: string | null; endDate?: string | null; kind?: string | null };\n costCenters?: boolean;\n integrations?: boolean;\n}\n\nexport function useHealthyBowlAccounting(options: UseAccountingOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const context = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n const withCtx = useCallback(<T extends object>(input: T) => ({ ...input, context }), [context]);\n\n const coaQuery = useQuery<{ getHealthyBowlChartOfAccounts: LedgerAccount[] }>(GET_CHART_OF_ACCOUNTS, {\n variables: { context, accountType: options.chartOfAccountsType ?? null, activeOnly: false },\n fetchPolicy: 'cache-and-network',\n skip: !options.chartOfAccounts,\n });\n const glQuery = useQuery<{ getHealthyBowlGeneralLedger: GeneralLedger }>(GET_GENERAL_LEDGER, {\n variables: { context, ...options.ledgerFilters },\n fetchPolicy: 'cache-and-network',\n skip: !options.generalLedger,\n });\n const entriesQuery = useQuery<{ getHealthyBowlJournalEntries: JournalEntry[] }>(GET_JOURNAL_ENTRIES, {\n variables: { context, limit: 50 },\n fetchPolicy: 'cache-and-network',\n skip: !options.journalEntries,\n });\n const pnlQuery = useQuery<{ getHealthyBowlProfitAndLoss: ProfitAndLoss }>(GET_PROFIT_AND_LOSS, {\n variables: { context, startDate: options.pnlRange?.startDate ?? '', endDate: options.pnlRange?.endDate ?? '' },\n fetchPolicy: 'cache-and-network',\n skip: !options.profitAndLoss || !options.pnlRange,\n });\n const tbQuery = useQuery<{ getHealthyBowlTrialBalance: TrialBalance }>(GET_TRIAL_BALANCE, {\n variables: {\n context,\n startDate: options.statementRange?.startDate ?? '',\n endDate: options.statementRange?.endDate ?? '',\n },\n fetchPolicy: 'cache-and-network',\n skip: !options.trialBalance || !options.statementRange,\n });\n const bsQuery = useQuery<{ getHealthyBowlBalanceSheet: BalanceSheet }>(GET_BALANCE_SHEET, {\n // A balance sheet is a position on a date, not a period, so only the end of the range applies.\n variables: { context, asOfDate: options.statementRange?.endDate ?? '' },\n fetchPolicy: 'cache-and-network',\n skip: !options.balanceSheet || !options.statementRange,\n });\n const cfQuery = useQuery<{ getHealthyBowlCashFlowStatement: CashFlowStatement }>(GET_CASH_FLOW, {\n variables: {\n context,\n startDate: options.statementRange?.startDate ?? '',\n endDate: options.statementRange?.endDate ?? '',\n },\n fetchPolicy: 'cache-and-network',\n skip: !options.cashFlow || !options.statementRange,\n });\n const cbcQuery = useQuery<{ getHealthyBowlCostByCrop: CostByCropReport }>(GET_COST_BY_CROP, {\n variables: {\n context,\n startDate: options.costByCropParams?.startDate ?? null,\n endDate: options.costByCropParams?.endDate ?? null,\n kind: options.costByCropParams?.kind ?? null,\n },\n fetchPolicy: 'cache-and-network',\n skip: !options.costByCrop,\n });\n const centersQuery = useQuery<{ getHealthyBowlCostCenters: CostCenter[] }>(GET_COST_CENTERS, {\n variables: { context, activeOnly: false },\n fetchPolicy: 'cache-and-network',\n skip: !options.costCenters,\n });\n const integrationsQuery = useQuery<{ getHealthyBowlAccountingIntegrations: IntegrationsPayload }>(GET_INTEGRATIONS, {\n variables: { context },\n fetchPolicy: 'cache-and-network',\n skip: !options.integrations,\n });\n\n const reconcile = useCallback(async () => {\n const jobs: Promise<unknown>[] = [];\n if (options.chartOfAccounts) jobs.push(coaQuery.refetch());\n if (options.generalLedger) jobs.push(glQuery.refetch());\n if (options.journalEntries) jobs.push(entriesQuery.refetch());\n if (options.profitAndLoss && options.pnlRange) jobs.push(pnlQuery.refetch());\n if (options.trialBalance && options.statementRange) jobs.push(tbQuery.refetch());\n if (options.balanceSheet && options.statementRange) jobs.push(bsQuery.refetch());\n if (options.cashFlow && options.statementRange) jobs.push(cfQuery.refetch());\n if (options.costByCrop) jobs.push(cbcQuery.refetch());\n if (options.costCenters) jobs.push(centersQuery.refetch());\n if (options.integrations) jobs.push(integrationsQuery.refetch());\n await Promise.all(jobs);\n }, [\n options,\n coaQuery,\n glQuery,\n entriesQuery,\n pnlQuery,\n tbQuery,\n bsQuery,\n cfQuery,\n cbcQuery,\n centersQuery,\n integrationsQuery,\n ]);\n\n const [ensureCoaM] = useMutation(ENSURE_COA);\n const [createAccountM] = useMutation(CREATE_ACCOUNT);\n const [updateAccountM] = useMutation(UPDATE_ACCOUNT);\n const [deleteAccountM] = useMutation(DELETE_ACCOUNT);\n const [postEntryM] = useMutation(POST_ENTRY);\n const [saveDraftM] = useMutation(SAVE_DRAFT);\n const [voidEntryM] = useMutation(VOID_ENTRY);\n const [pushBillingM] = useMutation(PUSH_TO_BILLING);\n const [createCenterM] = useMutation(CREATE_COST_CENTER);\n const [updateCenterM] = useMutation(UPDATE_COST_CENTER);\n const [deleteCenterM] = useMutation(DELETE_COST_CENTER);\n const [connectM] = useMutation(CONNECT_INTEGRATION);\n const [disconnectM] = useMutation(DISCONNECT_INTEGRATION);\n const [syncSettingsM] = useMutation(UPDATE_SYNC_SETTINGS);\n const [syncM] = useMutation(SYNC_INTEGRATION);\n const [pnlExportM] = useMutation(GET_PNL_EXPORT); // query-shaped, but invoked imperatively via useMutation for on-demand fetch\n\n const ensureChartOfAccounts = useCallback(async () => {\n const res = await ensureCoaM({ variables: { context } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { ensureHealthyBowlChartOfAccounts: LedgerAccount[] } | undefined)\n ?.ensureHealthyBowlChartOfAccounts ?? []\n );\n }, [ensureCoaM, context, reconcile]);\n\n const createAccount = useCallback(\n async (input: {\n code: string;\n name: string;\n accountType: string;\n description?: string | null;\n sortOrder?: number;\n }) => {\n const res = await createAccountM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [createAccountM, withCtx, reconcile]\n );\n const updateAccount = useCallback(\n async (input: {\n id: string;\n name?: string;\n accountType?: string;\n description?: string | null;\n isActive?: boolean;\n sortOrder?: number;\n }) => {\n const res = await updateAccountM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [updateAccountM, withCtx, reconcile]\n );\n const deleteAccount = useCallback(\n async (id: string) => {\n const res = await deleteAccountM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [deleteAccountM, context, reconcile]\n );\n\n const postJournalEntry = useCallback(\n async (input: {\n date?: string;\n memo: string;\n reference?: string | null;\n source?: string;\n lines: JournalLineInput[];\n }) => {\n const res = await postEntryM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { postHealthyBowlJournalEntry: JournalEntry } | undefined)?.postHealthyBowlJournalEntry ?? null\n );\n },\n [postEntryM, withCtx, reconcile]\n );\n const saveDraft = useCallback(\n async (input: {\n date?: string;\n memo: string;\n reference?: string | null;\n source?: string;\n lines: JournalLineInput[];\n }) => {\n const res = await saveDraftM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { saveHealthyBowlJournalEntryDraft: JournalEntry } | undefined)\n ?.saveHealthyBowlJournalEntryDraft ?? null\n );\n },\n [saveDraftM, withCtx, reconcile]\n );\n const voidEntry = useCallback(\n async (id: string) => {\n const res = await voidEntryM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [voidEntryM, context, reconcile]\n );\n const pushEntryToBilling = useCallback(\n async (id: string) => {\n const res = await pushBillingM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (res.data as { pushHealthyBowlJournalEntryToBilling: JournalEntry } | undefined)\n ?.pushHealthyBowlJournalEntryToBilling ?? null\n );\n },\n [pushBillingM, context, reconcile]\n );\n\n const createCostCenter = useCallback(\n async (input: {\n code?: string;\n label: string;\n kind: string;\n refType?: string | null;\n refId?: string | null;\n season?: string | null;\n yieldQuantity?: number;\n yieldUnit?: string;\n }) => {\n const res = await createCenterM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [createCenterM, withCtx, reconcile]\n );\n const updateCostCenter = useCallback(\n async (input: {\n id: string;\n label?: string;\n kind?: string;\n season?: string | null;\n yieldQuantity?: number;\n yieldUnit?: string;\n isActive?: boolean;\n }) => {\n const res = await updateCenterM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [updateCenterM, withCtx, reconcile]\n );\n const deleteCostCenter = useCallback(\n async (id: string) => {\n const res = await deleteCenterM({ variables: { id, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [deleteCenterM, context, reconcile]\n );\n\n const connectIntegration = useCallback(\n async (input: {\n provider: string;\n displayName?: string | null;\n endpoint?: string | null;\n organizationRef?: string | null;\n }) => {\n const res = await connectM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [connectM, withCtx, reconcile]\n );\n const disconnectIntegration = useCallback(\n async (provider: string) => {\n const res = await disconnectM({ variables: { provider, context } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [disconnectM, context, reconcile]\n );\n const updateSyncSettings = useCallback(\n async (input: { autoSyncDaily?: boolean; pushInvoices?: boolean; syncCoaMapping?: boolean }) => {\n const res = await syncSettingsM({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile();\n },\n [syncSettingsM, withCtx, reconcile]\n );\n const syncIntegration = useCallback(\n async (provider: string) => {\n const res = await syncM({ variables: { input: withCtx({ provider }) } });\n if (res.error) throw res.error;\n await reconcile();\n return (\n (\n res.data as\n | {\n syncHealthyBowlAccountingIntegration: {\n status: string;\n entriesCount: number;\n message: string;\n batch: AccountingExport | null;\n };\n }\n | undefined\n )?.syncHealthyBowlAccountingIntegration ?? null\n );\n },\n [syncM, withCtx, reconcile]\n );\n\n const exportProfitAndLoss = useCallback(\n async (startDate: string, endDate: string, format: 'CSV' | 'PDF'): Promise<AccountingExport | null> => {\n const res = await pnlExportM({ variables: { context, startDate, endDate, format } });\n if (res.error) throw res.error;\n return (\n (res.data as { getHealthyBowlProfitAndLossExport: AccountingExport } | undefined)\n ?.getHealthyBowlProfitAndLossExport ?? null\n );\n },\n [pnlExportM, context]\n );\n\n return {\n // data\n chartOfAccounts: coaQuery.data?.getHealthyBowlChartOfAccounts ?? [],\n generalLedger: glQuery.data?.getHealthyBowlGeneralLedger ?? null,\n journalEntries: entriesQuery.data?.getHealthyBowlJournalEntries ?? [],\n profitAndLoss: pnlQuery.data?.getHealthyBowlProfitAndLoss ?? null,\n trialBalance: tbQuery.data?.getHealthyBowlTrialBalance ?? null,\n balanceSheet: bsQuery.data?.getHealthyBowlBalanceSheet ?? null,\n cashFlow: cfQuery.data?.getHealthyBowlCashFlowStatement ?? null,\n costByCrop: cbcQuery.data?.getHealthyBowlCostByCrop ?? null,\n costCenters: centersQuery.data?.getHealthyBowlCostCenters ?? [],\n integrations: integrationsQuery.data?.getHealthyBowlAccountingIntegrations ?? null,\n // status\n loading:\n coaQuery.loading ||\n glQuery.loading ||\n entriesQuery.loading ||\n pnlQuery.loading ||\n tbQuery.loading ||\n bsQuery.loading ||\n cfQuery.loading ||\n cbcQuery.loading ||\n centersQuery.loading ||\n integrationsQuery.loading,\n error:\n coaQuery.error ||\n glQuery.error ||\n entriesQuery.error ||\n pnlQuery.error ||\n tbQuery.error ||\n bsQuery.error ||\n cfQuery.error ||\n cbcQuery.error ||\n centersQuery.error ||\n integrationsQuery.error ||\n null,\n reconcile,\n // mutations\n ensureChartOfAccounts,\n createAccount,\n updateAccount,\n deleteAccount,\n postJournalEntry,\n saveDraft,\n voidEntry,\n pushEntryToBilling,\n createCostCenter,\n updateCostCenter,\n deleteCostCenter,\n connectIntegration,\n disconnectIntegration,\n updateSyncSettings,\n syncIntegration,\n exportProfitAndLoss,\n };\n}\n"],"mappings":";;;;;AAmBA,IAAM,IAAwB,wCAwPxB,IAAiB,8GAEjB,IAAe,6QACf,IAAY,sLACZ,IAAa,kJACb,IAAqB,gGACrB,IAAsB,iOACtB,IAAsB,kQAGtB,IAAwB,CAAG;2GAC0E,EAAe,OACpH,IAAqB,CAAG;kMACoK,EAAU,OACtM,IAAsB,CAAG;iJACkH,EAAa,OACxJ,KAAsB,CAAG;+FACgE,EAAW,OACpG,KAAiB,CAAG;;;;;;;;;;GAYpB,IAAuB,iJACvB,IAAuB,uRACvB,IAAmB,sXACnB,IAAoB,CAAG;8FACiE,EAAqB,OAC7G,IAAoB,CAAG;yEAC4C,EAAqB,OACxF,IAAgB,CAAG;mGAC0E,EAAiB,OAC9G,IAAmB,CAAG;yGAC6E,EAAoB,OACvH,IAAmB,CAAG;yFAC6D,EAAmB,OACtG,IAAmB,CAAG;8DACkC,EAAoB,OAG5E,IAAa,CAAG,yGAAyG,EAAe,OACxI,IAAiB,CAAG,4HAA4H,EAAe,OAC/J,KAAiB,CAAG,4HAA4H,EAAe,OAC/J,KAAiB,CAAG;;;;GAKpB,KAAa,CAAG,kHAAkH,EAAa,OAC/I,KAAa,CAAG,uHAAuH,EAAa,OACpJ,KAAa,CAAG,uHAAuH,EAAa,OACpJ,KAAkB,C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10,13 @@ import { LoadingSkeleton as c } from "../../components/LoadingSkeleton.js";
|
|
|
10
10
|
import { Modal as l } from "../../components/Modal.js";
|
|
11
11
|
import { useToast as u } from "../../hooks/useToast.js";
|
|
12
12
|
import "../../components/index.js";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
13
|
+
import { downloadBase64 as d } from "../../utils/download.js";
|
|
14
|
+
import { useHealthyBowlAccounting as f } from "../../hooks/useHealthyBowlAccounting.js";
|
|
15
|
+
import { useState as p } from "react";
|
|
16
|
+
import { Fragment as m, jsx as h, jsxs as g } from "react/jsx-runtime";
|
|
17
|
+
import { Button as _, Switch as v } from "@burdenoff/fe-libs/ui";
|
|
17
18
|
//#region src/healthybowl/pages/financial/AccountingIntegrationsPage.tsx
|
|
18
|
-
var
|
|
19
|
+
var y = "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)]", b = [
|
|
19
20
|
{
|
|
20
21
|
id: "TALLY",
|
|
21
22
|
label: "Tally",
|
|
@@ -32,166 +33,184 @@ var v = "h-9 w-full rounded-md border border-border-subtle bg-bg-surface px-3 te
|
|
|
32
33
|
blurb: "Export journal entries to QuickBooks Online."
|
|
33
34
|
}
|
|
34
35
|
];
|
|
35
|
-
function
|
|
36
|
-
let { toasts:
|
|
37
|
-
if (
|
|
38
|
-
|
|
36
|
+
function x() {
|
|
37
|
+
let { toasts: x, toast: S, dismiss: C } = u(), w = f({ integrations: !0 }), T = w.integrations, [E, D] = p(null), [O, k] = p(""), [A, j] = p(""), [M, N] = p(""), [P, F] = p(""), I = async () => {
|
|
38
|
+
if (E) {
|
|
39
|
+
F("connect");
|
|
39
40
|
try {
|
|
40
|
-
await
|
|
41
|
-
provider:
|
|
42
|
-
displayName:
|
|
43
|
-
endpoint:
|
|
44
|
-
organizationRef:
|
|
45
|
-
}),
|
|
46
|
-
title: `${
|
|
41
|
+
await w.connectIntegration({
|
|
42
|
+
provider: E,
|
|
43
|
+
displayName: O || null,
|
|
44
|
+
endpoint: A || null,
|
|
45
|
+
organizationRef: M || null
|
|
46
|
+
}), S({
|
|
47
|
+
title: `${E} connected`,
|
|
47
48
|
variant: "success"
|
|
48
|
-
}),
|
|
49
|
+
}), D(null), k(""), j(""), N("");
|
|
49
50
|
} catch (e) {
|
|
50
|
-
|
|
51
|
+
S({
|
|
51
52
|
title: "Connect failed",
|
|
52
53
|
description: e instanceof Error ? e.message : void 0,
|
|
53
54
|
variant: "error"
|
|
54
55
|
});
|
|
55
56
|
} finally {
|
|
56
|
-
|
|
57
|
+
F("");
|
|
57
58
|
}
|
|
58
59
|
}
|
|
59
|
-
},
|
|
60
|
-
|
|
60
|
+
}, L = async (e) => {
|
|
61
|
+
F(e);
|
|
61
62
|
try {
|
|
62
|
-
let t = await
|
|
63
|
-
|
|
63
|
+
let t = await w.syncIntegration(e);
|
|
64
|
+
S({
|
|
64
65
|
title: t?.message ?? "Sync complete",
|
|
65
|
-
variant: t?.status === "
|
|
66
|
-
});
|
|
66
|
+
variant: t?.status === "NOT_SENT" ? "warning" : t?.status === "FAILED" ? "error" : "success"
|
|
67
|
+
}), t?.batch && d(t.batch.contentBase64, t.batch.filename, t.batch.mimeType);
|
|
67
68
|
} catch (e) {
|
|
68
|
-
|
|
69
|
+
S({
|
|
69
70
|
title: "Sync failed",
|
|
70
71
|
description: e instanceof Error ? e.message : void 0,
|
|
71
72
|
variant: "error"
|
|
72
73
|
});
|
|
73
74
|
} finally {
|
|
74
|
-
|
|
75
|
+
F("");
|
|
75
76
|
}
|
|
76
|
-
},
|
|
77
|
-
|
|
77
|
+
}, R = async (e) => {
|
|
78
|
+
F(e);
|
|
78
79
|
try {
|
|
79
|
-
await
|
|
80
|
+
await w.disconnectIntegration(e), S({
|
|
80
81
|
title: `${e} disconnected`,
|
|
81
82
|
variant: "success"
|
|
82
83
|
});
|
|
83
84
|
} catch (e) {
|
|
84
|
-
|
|
85
|
+
S({
|
|
85
86
|
title: "Disconnect failed",
|
|
86
87
|
description: e instanceof Error ? e.message : void 0,
|
|
87
88
|
variant: "error"
|
|
88
89
|
});
|
|
89
90
|
} finally {
|
|
90
|
-
|
|
91
|
+
F("");
|
|
91
92
|
}
|
|
92
|
-
},
|
|
93
|
+
}, z = async (e) => {
|
|
93
94
|
try {
|
|
94
|
-
await
|
|
95
|
+
await w.updateSyncSettings(e);
|
|
95
96
|
} catch (e) {
|
|
96
|
-
|
|
97
|
+
S({
|
|
97
98
|
title: "Could not save setting",
|
|
98
99
|
description: e instanceof Error ? e.message : void 0,
|
|
99
100
|
variant: "error"
|
|
100
101
|
});
|
|
101
102
|
}
|
|
102
103
|
};
|
|
103
|
-
return /* @__PURE__ */
|
|
104
|
+
return /* @__PURE__ */ g(t, {
|
|
104
105
|
title: "Accounting Integrations",
|
|
105
106
|
description: "Sync your HealthyBowl ledger with external accounting software.",
|
|
106
107
|
children: [
|
|
107
|
-
/* @__PURE__ */
|
|
108
|
-
toasts:
|
|
109
|
-
onDismiss:
|
|
108
|
+
/* @__PURE__ */ h(s, {
|
|
109
|
+
toasts: x,
|
|
110
|
+
onDismiss: C
|
|
110
111
|
}),
|
|
111
|
-
|
|
112
|
+
w.error && !T ? /* @__PURE__ */ h(a, {
|
|
112
113
|
title: "Could not load integrations",
|
|
113
|
-
description:
|
|
114
|
-
}) :
|
|
114
|
+
description: w.error.message
|
|
115
|
+
}) : w.loading && !T ? /* @__PURE__ */ h(c, {
|
|
115
116
|
variant: "table",
|
|
116
117
|
count: 4
|
|
117
|
-
}) : /* @__PURE__ */
|
|
118
|
+
}) : /* @__PURE__ */ g("div", {
|
|
118
119
|
className: "space-y-6",
|
|
119
120
|
children: [
|
|
120
|
-
/* @__PURE__ */
|
|
121
|
+
/* @__PURE__ */ h("div", {
|
|
121
122
|
className: "grid grid-cols-1 gap-4 md:grid-cols-3",
|
|
122
|
-
children:
|
|
123
|
-
let n =
|
|
124
|
-
return /* @__PURE__ */
|
|
123
|
+
children: b.map((t) => {
|
|
124
|
+
let n = T?.integrations.find((e) => e.provider === t.id), i = n?.status ?? "NOT_CONNECTED", a = i === "CONNECTED" ? "Connected" : i === "SYNC_READY" ? "Sync ready" : "Not connected";
|
|
125
|
+
return /* @__PURE__ */ g("div", {
|
|
125
126
|
className: "rounded-xl border border-border-subtle bg-bg-surface p-4",
|
|
126
127
|
children: [
|
|
127
|
-
/* @__PURE__ */
|
|
128
|
+
/* @__PURE__ */ h("div", {
|
|
128
129
|
className: "mb-1 text-base font-semibold text-text-primary",
|
|
129
130
|
children: t.label
|
|
130
131
|
}),
|
|
131
|
-
/* @__PURE__ */
|
|
132
|
+
/* @__PURE__ */ h("p", {
|
|
132
133
|
className: "mb-3 text-sm text-text-secondary",
|
|
133
134
|
children: t.blurb
|
|
134
135
|
}),
|
|
135
|
-
/* @__PURE__ */
|
|
136
|
+
/* @__PURE__ */ g("div", {
|
|
136
137
|
className: "mb-3",
|
|
137
|
-
children: [
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
138
|
+
children: [
|
|
139
|
+
/* @__PURE__ */ h(r, {
|
|
140
|
+
variant: i === "CONNECTED" ? "success" : i === "SYNC_READY" ? "warning" : "muted",
|
|
141
|
+
label: a
|
|
142
|
+
}),
|
|
143
|
+
n && /* @__PURE__ */ g("div", {
|
|
144
|
+
className: "mt-2 text-xs text-text-secondary",
|
|
145
|
+
children: [
|
|
146
|
+
n.lastSyncedAt ? `Last synced ${e(n.lastSyncedAt)} · ` : "",
|
|
147
|
+
n.entriesPushed,
|
|
148
|
+
" entries pushed"
|
|
149
|
+
]
|
|
150
|
+
}),
|
|
151
|
+
n && i !== "NOT_CONNECTED" && !n.endpoint && /* @__PURE__ */ h("div", {
|
|
152
|
+
className: "mt-2 text-xs text-text-secondary",
|
|
153
|
+
children: "Export only — no endpoint configured"
|
|
154
|
+
})
|
|
155
|
+
]
|
|
148
156
|
}),
|
|
149
|
-
/* @__PURE__ */
|
|
157
|
+
/* @__PURE__ */ h("div", {
|
|
150
158
|
className: "flex gap-2",
|
|
151
|
-
children: i === "NOT_CONNECTED" ? /* @__PURE__ */
|
|
159
|
+
children: i === "NOT_CONNECTED" ? /* @__PURE__ */ h(_, {
|
|
152
160
|
size: "sm",
|
|
153
|
-
onClick: () =>
|
|
161
|
+
onClick: () => D(t.id),
|
|
154
162
|
children: "Connect"
|
|
155
|
-
}) : /* @__PURE__ */
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
163
|
+
}) : /* @__PURE__ */ g(m, { children: [
|
|
164
|
+
/* @__PURE__ */ h(_, {
|
|
165
|
+
size: "sm",
|
|
166
|
+
onClick: () => L(t.id),
|
|
167
|
+
disabled: P === t.id,
|
|
168
|
+
children: P === t.id ? "Exporting…" : `Export to ${t.label}`
|
|
169
|
+
}),
|
|
170
|
+
n && !n.endpoint && /* @__PURE__ */ h(_, {
|
|
171
|
+
size: "sm",
|
|
172
|
+
variant: "outline",
|
|
173
|
+
onClick: () => {
|
|
174
|
+
j(n.endpoint ?? ""), D(t.id);
|
|
175
|
+
},
|
|
176
|
+
children: "Add endpoint"
|
|
177
|
+
}),
|
|
178
|
+
/* @__PURE__ */ h(_, {
|
|
179
|
+
size: "sm",
|
|
180
|
+
variant: "outline",
|
|
181
|
+
onClick: () => R(t.id),
|
|
182
|
+
disabled: P === t.id,
|
|
183
|
+
children: "Disconnect"
|
|
184
|
+
})
|
|
185
|
+
] })
|
|
167
186
|
})
|
|
168
187
|
]
|
|
169
188
|
}, t.id);
|
|
170
189
|
})
|
|
171
190
|
}),
|
|
172
|
-
/* @__PURE__ */
|
|
191
|
+
/* @__PURE__ */ h(o, {
|
|
173
192
|
title: "Sync Settings",
|
|
174
|
-
children: /* @__PURE__ */
|
|
193
|
+
children: /* @__PURE__ */ h("div", {
|
|
175
194
|
className: "space-y-3",
|
|
176
195
|
children: [
|
|
177
196
|
["autoSyncDaily", "Auto-sync journal entries daily"],
|
|
178
197
|
["pushInvoices", "Push invoices to accounting system"],
|
|
179
198
|
["syncCoaMapping", "Sync chart of accounts mapping"]
|
|
180
|
-
].map(([e, t]) => /* @__PURE__ */
|
|
199
|
+
].map(([e, t]) => /* @__PURE__ */ g("div", {
|
|
181
200
|
className: "flex items-center justify-between",
|
|
182
|
-
children: [/* @__PURE__ */
|
|
201
|
+
children: [/* @__PURE__ */ h("span", {
|
|
183
202
|
className: "text-sm text-text-primary",
|
|
184
203
|
children: t
|
|
185
|
-
}), /* @__PURE__ */
|
|
186
|
-
checked: !!
|
|
187
|
-
onCheckedChange: (t) =>
|
|
204
|
+
}), /* @__PURE__ */ h(v, {
|
|
205
|
+
checked: !!T?.[e],
|
|
206
|
+
onCheckedChange: (t) => z({ [e]: t })
|
|
188
207
|
})]
|
|
189
208
|
}, e))
|
|
190
209
|
})
|
|
191
210
|
}),
|
|
192
|
-
/* @__PURE__ */
|
|
211
|
+
/* @__PURE__ */ h(o, {
|
|
193
212
|
title: "Recent Sync Log",
|
|
194
|
-
children:
|
|
213
|
+
children: T && T.syncLogs.length > 0 ? /* @__PURE__ */ h(n, {
|
|
195
214
|
columns: [
|
|
196
215
|
{
|
|
197
216
|
key: "syncedAt",
|
|
@@ -212,76 +231,83 @@ function b() {
|
|
|
212
231
|
{
|
|
213
232
|
key: "status",
|
|
214
233
|
header: "Status",
|
|
215
|
-
render: (e) => /* @__PURE__ */
|
|
234
|
+
render: (e) => /* @__PURE__ */ h(r, {
|
|
216
235
|
variant: e.status === "SUCCESS" ? "success" : e.status === "FAILED" ? "error" : "warning",
|
|
217
|
-
label: e.status
|
|
236
|
+
label: e.status === "NOT_SENT" ? "Not sent" : e.status === "SUCCESS" ? "Success" : e.status === "FAILED" ? "Failed" : e.status
|
|
218
237
|
})
|
|
219
238
|
}
|
|
220
239
|
],
|
|
221
|
-
data:
|
|
240
|
+
data: T.syncLogs,
|
|
222
241
|
keyField: "id",
|
|
223
242
|
pageSize: 10
|
|
224
|
-
}) : /* @__PURE__ */
|
|
243
|
+
}) : /* @__PURE__ */ h(i, {
|
|
225
244
|
title: "No syncs yet",
|
|
226
245
|
description: "Connect a provider and run a sync to see the log here."
|
|
227
246
|
})
|
|
228
247
|
})
|
|
229
248
|
]
|
|
230
249
|
}),
|
|
231
|
-
/* @__PURE__ */
|
|
232
|
-
open:
|
|
233
|
-
onClose: () =>
|
|
234
|
-
title: `Connect ${
|
|
250
|
+
/* @__PURE__ */ h(l, {
|
|
251
|
+
open: E !== null,
|
|
252
|
+
onClose: () => D(null),
|
|
253
|
+
title: `Connect ${E === "ZOHO_BOOKS" ? "Zoho Books" : E === "QUICKBOOKS" ? "QuickBooks" : "Tally"}`,
|
|
235
254
|
description: "Store the non-secret connection details for this provider.",
|
|
236
255
|
size: "md",
|
|
237
|
-
footer: /* @__PURE__ */
|
|
256
|
+
footer: /* @__PURE__ */ g("div", {
|
|
238
257
|
className: "flex justify-end gap-2",
|
|
239
|
-
children: [/* @__PURE__ */
|
|
258
|
+
children: [/* @__PURE__ */ h(_, {
|
|
240
259
|
variant: "outline",
|
|
241
|
-
onClick: () =>
|
|
260
|
+
onClick: () => D(null),
|
|
242
261
|
children: "Cancel"
|
|
243
|
-
}), /* @__PURE__ */
|
|
244
|
-
onClick:
|
|
245
|
-
disabled:
|
|
262
|
+
}), /* @__PURE__ */ h(_, {
|
|
263
|
+
onClick: I,
|
|
264
|
+
disabled: P === "connect",
|
|
246
265
|
children: "Connect"
|
|
247
266
|
})]
|
|
248
267
|
}),
|
|
249
|
-
children: /* @__PURE__ */
|
|
268
|
+
children: /* @__PURE__ */ g("div", {
|
|
250
269
|
className: "space-y-3",
|
|
251
270
|
children: [
|
|
252
|
-
/* @__PURE__ */
|
|
271
|
+
/* @__PURE__ */ g("label", {
|
|
253
272
|
className: "block text-sm",
|
|
254
|
-
children: [/* @__PURE__ */
|
|
273
|
+
children: [/* @__PURE__ */ h("span", {
|
|
255
274
|
className: "mb-1 block text-text-secondary",
|
|
256
275
|
children: "Display name (optional)"
|
|
257
|
-
}), /* @__PURE__ */
|
|
258
|
-
value:
|
|
259
|
-
onChange: (e) =>
|
|
260
|
-
className:
|
|
276
|
+
}), /* @__PURE__ */ h("input", {
|
|
277
|
+
value: O,
|
|
278
|
+
onChange: (e) => k(e.target.value),
|
|
279
|
+
className: y,
|
|
261
280
|
placeholder: "Green Valley Books"
|
|
262
281
|
})]
|
|
263
282
|
}),
|
|
264
|
-
/* @__PURE__ */
|
|
283
|
+
/* @__PURE__ */ g("label", {
|
|
265
284
|
className: "block text-sm",
|
|
266
|
-
children: [
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
285
|
+
children: [
|
|
286
|
+
/* @__PURE__ */ h("span", {
|
|
287
|
+
className: "mb-1 block text-text-secondary",
|
|
288
|
+
children: "API endpoint / gateway URL"
|
|
289
|
+
}),
|
|
290
|
+
/* @__PURE__ */ h("input", {
|
|
291
|
+
value: A,
|
|
292
|
+
onChange: (e) => j(e.target.value),
|
|
293
|
+
className: y,
|
|
294
|
+
placeholder: "https://…"
|
|
295
|
+
}),
|
|
296
|
+
/* @__PURE__ */ h("span", {
|
|
297
|
+
className: "mt-1 block text-xs text-text-secondary",
|
|
298
|
+
children: "Without an endpoint nothing is transmitted — exports are recorded as “Not sent” and downloaded as a file for manual import."
|
|
299
|
+
})
|
|
300
|
+
]
|
|
275
301
|
}),
|
|
276
|
-
/* @__PURE__ */
|
|
302
|
+
/* @__PURE__ */ g("label", {
|
|
277
303
|
className: "block text-sm",
|
|
278
|
-
children: [/* @__PURE__ */
|
|
304
|
+
children: [/* @__PURE__ */ h("span", {
|
|
279
305
|
className: "mb-1 block text-text-secondary",
|
|
280
306
|
children: "Organization id (optional)"
|
|
281
|
-
}), /* @__PURE__ */
|
|
282
|
-
value:
|
|
283
|
-
onChange: (e) =>
|
|
284
|
-
className:
|
|
307
|
+
}), /* @__PURE__ */ h("input", {
|
|
308
|
+
value: M,
|
|
309
|
+
onChange: (e) => N(e.target.value),
|
|
310
|
+
className: y,
|
|
285
311
|
placeholder: "Zoho organization id"
|
|
286
312
|
})]
|
|
287
313
|
})
|
|
@@ -292,6 +318,6 @@ function b() {
|
|
|
292
318
|
});
|
|
293
319
|
}
|
|
294
320
|
//#endregion
|
|
295
|
-
export {
|
|
321
|
+
export { x as AccountingIntegrationsPage };
|
|
296
322
|
|
|
297
323
|
//# sourceMappingURL=AccountingIntegrationsPage.js.map
|
|
@@ -1 +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-end', 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,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Ae,UAAU,MAAS;gBAAW;MAErD,CAAA,CACL;;cAGR,kBAAC,OAAD;KAAK,WAAU;eAAf;MACE,kBAAC,SAAD;OAAO,WAAU;iBAAjB,CACE,kBAAC,QAAD;QAAM,WAAU;kBAAiC;QAA8B,CAAA,EAC/E,kBAAC,SAAD;QACE,OAAO;QACP,WAAW,MAAM,EAAe,EAAE,OAAO,MAAM;QAC/C,WAAW;QACX,aAAY;QACZ,CAAA,CACI;;MACR,kBAAC,SAAD;OAAO,WAAU;iBAAjB,CACE,kBAAC,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"}
|
|
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 { downloadBase64 } from '../../utils/download';\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({\n title: res?.message ?? 'Sync complete',\n variant: res?.status === 'NOT_SENT' ? 'warning' : res?.status === 'FAILED' ? 'error' : 'success',\n });\n if (res?.batch) downloadBase64(res.batch.contentBase64, res.batch.filename, res.batch.mimeType);\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-end', 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={\n r.status === 'NOT_SENT'\n ? 'Not sent'\n : r.status === 'SUCCESS'\n ? 'Success'\n : r.status === 'FAILED'\n ? 'Failed'\n : r.status\n }\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 {found && status !== 'NOT_CONNECTED' && !found.endpoint && (\n <div className=\"mt-2 text-xs text-text-secondary\">Export only — no endpoint configured</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 ? 'Exporting…' : `Export to ${p.label}`}\n </Button>\n {found && !found.endpoint && (\n <Button\n size=\"sm\"\n variant=\"outline\"\n onClick={() => {\n setEndpoint(found.endpoint ?? '');\n setConnectFor(p.id);\n }}\n >\n Add endpoint\n </Button>\n )}\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</span>\n <input\n value={endpoint}\n onChange={(e) => setEndpoint(e.target.value)}\n className={INPUT_CLASS}\n placeholder=\"https://…\"\n />\n <span className=\"mt-1 block text-xs text-text-secondary\">\n Without an endpoint nothing is transmitted — exports are recorded as “Not sent” and downloaded as a file\n for manual import.\n </span>\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":";;;;;;;;;;;;;;;;;;AAoBA,IAAM,IACJ,uMAEI,IAAgG;CACpG;EA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AU;eAAf;MACE,kBAAC,SAAD;OAAO,WAAU;iBAAjB,CACE,kBAAC,QAAD;QAAM,WAAU;kBAAiC;QAA8B,CAAA,EAC/E,kBAAC,SAAD;QACE,OAAO;QACP,WAAW,MAAM,EAAe,EAAE,OAAO,MAAM;QAC/C,WAAW;QACX,aAAY;QACZ,CAAA,CACI;;MACR,kBAAC,SAAD;OAAO,WAAU;iBAAjB;QACE,kBAAC,QAAD;SAAM,WAAU;mBAAiC;SAAiC,CAAA;QAClF,kBAAC,SAAD;SACE,OAAO;SACP,WAAW,MAAM,EAAY,EAAE,OAAO,MAAM;SAC5C,WAAW;SACX,aAAY;SACZ,CAAA;QACF,kBAAC,QAAD;SAAM,WAAU;mBAAyC;SAGlD,CAAA;QACD;;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"}
|
|
@@ -10,9 +10,9 @@ import { ToastContainer as l } from "../../components/Toast.js";
|
|
|
10
10
|
import { LoadingSkeleton as u } from "../../components/LoadingSkeleton.js";
|
|
11
11
|
import { useToast as d } from "../../hooks/useToast.js";
|
|
12
12
|
import "../../components/index.js";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
13
|
+
import { downloadBase64 as f } from "../../utils/download.js";
|
|
14
|
+
import { useHealthyBowlAccounting as p } from "../../hooks/useHealthyBowlAccounting.js";
|
|
15
|
+
import { financialYearRange as m } from "../../utils/period.js";
|
|
16
16
|
import { JournalEntryModal as h } from "./JournalEntryModal.js";
|
|
17
17
|
import { useEffect as g, useMemo as _, useState as v } from "react";
|
|
18
18
|
import { Fragment as y, jsx as b, jsxs as x } from "react/jsx-runtime";
|
|
@@ -46,7 +46,7 @@ var C = [
|
|
|
46
46
|
}
|
|
47
47
|
];
|
|
48
48
|
function w() {
|
|
49
|
-
let { basePath: w, navigate: T } = e(), { toasts: E, toast: D, dismiss: O } = d(), k = _(() =>
|
|
49
|
+
let { basePath: w, navigate: T } = e(), { toasts: E, toast: D, dismiss: O } = d(), k = _(() => m(), []), [A, j] = v(0), [M, N] = v(!1), [P, F] = v(!1), I = p({
|
|
50
50
|
profitAndLoss: !0,
|
|
51
51
|
pnlRange: k,
|
|
52
52
|
generalLedger: !0,
|
|
@@ -72,7 +72,7 @@ function w() {
|
|
|
72
72
|
try {
|
|
73
73
|
let t = await I.exportProfitAndLoss(k.startDate, k.endDate, e);
|
|
74
74
|
if (!t) throw Error("Export produced no content.");
|
|
75
|
-
|
|
75
|
+
f(t.contentBase64, t.filename, t.mimeType), D({
|
|
76
76
|
title: `P&L exported as ${e}`,
|
|
77
77
|
variant: "success"
|
|
78
78
|
});
|
|
@@ -6,16 +6,16 @@ import { ToastContainer as i } from "../../components/Toast.js";
|
|
|
6
6
|
import { LoadingSkeleton as a } from "../../components/LoadingSkeleton.js";
|
|
7
7
|
import { useToast as o } from "../../hooks/useToast.js";
|
|
8
8
|
import "../../components/index.js";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
9
|
+
import { downloadBase64 as s } from "../../utils/download.js";
|
|
10
|
+
import { useHealthyBowlAccounting as c } from "../../hooks/useHealthyBowlAccounting.js";
|
|
11
|
+
import { financialYearRange as l } from "../../utils/period.js";
|
|
12
12
|
import { useState as u } from "react";
|
|
13
13
|
import { jsx as d, jsxs as f } from "react/jsx-runtime";
|
|
14
14
|
import { Button as p } from "@burdenoff/fe-libs/ui";
|
|
15
15
|
//#region src/healthybowl/pages/financial/ProfitLossPage.tsx
|
|
16
16
|
var m = "h-9 rounded-md border border-border-subtle bg-bg-surface px-3 text-sm text-text-primary focus:outline-none focus:ring-2 focus:ring-[var(--color-focus-ring)]";
|
|
17
17
|
function h() {
|
|
18
|
-
let { toasts: h, toast: _, dismiss: v } = o(), y =
|
|
18
|
+
let { toasts: h, toast: _, dismiss: v } = o(), y = l(), [b, x] = u(y.startDate), [S, C] = u(y.endDate), w = c({
|
|
19
19
|
profitAndLoss: !0,
|
|
20
20
|
pnlRange: {
|
|
21
21
|
startDate: b,
|
|
@@ -25,7 +25,7 @@ function h() {
|
|
|
25
25
|
try {
|
|
26
26
|
let t = await w.exportProfitAndLoss(b, S, e);
|
|
27
27
|
if (!t) throw Error("Export produced no content.");
|
|
28
|
-
|
|
28
|
+
s(t.contentBase64, t.filename, t.mimeType), _({
|
|
29
29
|
title: `Exported as ${e}`,
|
|
30
30
|
variant: "success"
|
|
31
31
|
});
|
package/package.json
CHANGED