@burdenoff/microfe-healthybowl 2026.812.4 → 2026.812.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"useCreditsWallet.js","names":[],"sources":["../../../src/healthybowl/hooks/useCreditsWallet.ts"],"sourcesContent":["/**\n * Credits & Payments wallet (roadmap #08 / BOFF-2880) — the money side of HealthyBowl.\n *\n * This hook is a THIN client over the platform `global-billing-svc` credit module — HealthyBowl\n * adds NO payment backend, holds no card data and no Razorpay secrets. Every balance, transaction,\n * top-up and payout is a call to billing's already-composed ops on the GLOBAL gateway:\n *\n * - `getBillingAccountsByOrg` → resolve the farm-org's default billing account id\n * - `getCreditBalanceByType` → purchased / earned / granted / withdrawable / total\n * - `getBillingAccountCreditTransactions` → the recent ledger (top-ups, order spends, payouts)\n * - `myPayoutAccounts` → the bank/UPI payout account a withdrawal pays out to\n * - `initiatePayment` (purchaseType CREDITS) → a real Razorpay order for a credit top-up\n * - `requestCreditWithdrawal` → a payout request against the withdrawable balance\n *\n * These are GLOBAL-gateway ops, so they go through fe-libs `graphqlFetch({ gateway: 'global' })`\n * (which re-derives the bearer token and attaches the `x-org-id` context header from profile\n * storage) — NOT the workspace Apollo client the rest of HB uses. This mirrors\n * `useAssistantApiAccess`, the one other HB caller that reaches the global gateway with auth.\n *\n * The client never credits or debits anything itself: billing's Razorpay webhook settles a top-up\n * and only then does the balance move. After a top-up widget closes (or a payout is requested) we\n * simply re-read balance + transactions so the page reflects billing's authoritative state without\n * a full reload.\n *\n * @module healthybowl\n */\nimport { useCallback, useEffect, useState } from 'react';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n// ── Domain types (mirror the composed global-billing schema) ──────────────────\n\n/** Credit balance broken down by bucket, in the account's currency (INR for HB). */\nexport interface CreditBalances {\n purchased: number;\n earned: number;\n granted: number;\n withdrawable: number;\n total: number;\n}\n\n/** billing `CreditTransactionType` — how the ledger row arose. */\nexport type WalletTxnType = 'purchase' | 'usage' | 'granted' | 'adjustment';\n/** billing `CreditTransactionStatus`. */\nexport type WalletTxnStatus = 'success' | 'pending' | 'failed' | 'refund';\n\n/** One credit-ledger row as HB renders it. */\nexport interface WalletTransaction {\n id: string;\n amount: number;\n type: WalletTxnType;\n status: WalletTxnStatus;\n createdAt: string;\n entityType: string | null;\n /** Which bucket a debit came from (usage rows). */\n fromType: WalletTxnType | null;\n /** Present on the debit reserved for a payout — lets us label it a withdrawal. */\n payoutRequestId: string | null;\n}\n\n/** A resolved payout destination a withdrawal can be sent to. */\nexport interface WalletPayoutAccount {\n id: string;\n label: string;\n displayName: string | null;\n isDefault: boolean;\n isActive: boolean;\n currency: string;\n accountLast4: string | null;\n status: string;\n}\n\n/**\n * What the page needs to open the Razorpay widget for a credit top-up. Billing computes the tax\n * and returns the authoritative `total` — HB opens the widget for exactly that, never a\n * self-computed amount.\n */\nexport interface TopUpSession {\n success: boolean;\n /** RAZORPAY / STRIPE — billing decides; this UI only opens Razorpay. */\n provider: string;\n /** Razorpay `order_xxx`; null when billing routed elsewhere. */\n orderId: string | null;\n razorpayKeyId: string | null;\n clientSecret: string | null;\n subtotal: number;\n taxAmount: number;\n total: number;\n currency: string;\n paymentId: string | null;\n error: string | null;\n}\n\n/** Result of a payout request. */\nexport interface PayoutResult {\n id: string;\n status: string;\n requestedAmount: number;\n currency: string;\n createdAt: string;\n}\n\n// ── GraphQL documents (global-billing ops, executed directly against the gateway) ──\n\nconst BILLING_ACCOUNTS_QUERY = /* GraphQL */ `\n query HbWalletBillingAccounts {\n getBillingAccountsByOrg {\n id\n isDefault\n isActive\n currency\n }\n }\n`;\n\nconst CREDIT_BALANCE_QUERY = /* GraphQL */ `\n query HbWalletCreditBalance($billingAccountId: ID!) {\n getCreditBalanceByType(billingAccountId: $billingAccountId) {\n purchased\n earned\n granted\n withdrawable\n total\n }\n }\n`;\n\nconst CREDIT_TRANSACTIONS_QUERY = /* GraphQL */ `\n query HbWalletCreditTransactions($billingAccountID: ID!, $days: Int!, $page: Int, $pageSize: Int) {\n getBillingAccountCreditTransactions(\n billingAccountID: $billingAccountID\n days: $days\n page: $page\n pageSize: $pageSize\n ) {\n creditTransactions {\n id\n amount\n type\n status\n createdAt\n entityType\n fromType\n payoutRequestId\n }\n totalCount\n hasMore\n }\n }\n`;\n\nconst PAYOUT_ACCOUNTS_QUERY = /* GraphQL */ `\n query HbWalletPayoutAccounts($billingAccountId: ID!) {\n myPayoutAccounts(billingAccountId: $billingAccountId) {\n id\n label\n displayName\n isDefault\n isActive\n currency\n accountLast4\n status\n }\n }\n`;\n\nconst INITIATE_TOPUP_MUTATION = /* GraphQL */ `\n mutation HbWalletInitiateTopUp($input: InitiatePaymentInput!) {\n initiatePayment(input: $input) {\n success\n provider\n orderId\n razorpayKeyId\n clientSecret\n subtotal\n taxAmount\n total\n currency\n paymentId\n error\n }\n }\n`;\n\nconst REQUEST_PAYOUT_MUTATION = /* GraphQL */ `\n mutation HbWalletRequestPayout($input: RequestCreditWithdrawalInput!) {\n requestCreditWithdrawal(input: $input) {\n id\n status\n requestedAmount\n currency\n createdAt\n }\n }\n`;\n\n// ── Wire response shapes ──────────────────────────────────────────────────────\n\ninterface BillingAccountLite {\n id: string | null;\n isDefault: boolean | null;\n isActive: boolean | null;\n currency: string | null;\n}\n\n/** Credits are priced 1:1 with the account currency (₹1 = 1 credit) for HB top-up packs. */\nconst CREDIT_PER_CURRENCY_UNIT = 1;\n/** How far back the transactions ledger reads. */\nconst TRANSACTIONS_WINDOW_DAYS = 365;\nconst DEFAULT_CURRENCY = 'INR';\n\ninterface WalletState {\n billingAccountId: string | null;\n currency: string;\n balances: CreditBalances | null;\n transactions: WalletTransaction[];\n payoutAccounts: WalletPayoutAccount[];\n loading: boolean;\n error: string | null;\n}\n\nconst EMPTY_STATE: WalletState = {\n billingAccountId: null,\n currency: DEFAULT_CURRENCY,\n balances: null,\n transactions: [],\n payoutAccounts: [],\n loading: false,\n error: null,\n};\n\n/** Throw the first GraphQL error, if any — callers surface it as a toast / error state. */\nfunction firstError(errors: { message?: string }[] | undefined, fallback: string): void {\n if (errors?.length) throw new Error(errors[0]?.message ?? fallback);\n}\n\nexport interface UseCreditsWallet extends WalletState {\n /** The default (or first active) payout destination, or null if none is set up. */\n payoutAccount: WalletPayoutAccount | null;\n hasPayoutAccount: boolean;\n /** Re-read balance + transactions (call after a top-up widget closes or a payout is requested). */\n refetch: () => Promise<void>;\n /**\n * Create a real Razorpay order for an `amountInr` credit top-up via billing's `initiatePayment`.\n * Returns the session the PAGE uses to open the Razorpay widget — the client never marks anything\n * paid; billing's webhook settles it and the balance moves on the next {@link refetch}.\n */\n buyCredits: (amountInr: number) => Promise<TopUpSession>;\n /**\n * Request a payout of `amountInr` withdrawable credits to the resolved payout account via\n * `requestCreditWithdrawal`. Refetches on success so the reserving debit shows as Processing.\n */\n requestPayout: (amountInr: number, notes?: string) => Promise<PayoutResult>;\n}\n\nexport function useCreditsWallet(): UseCreditsWallet {\n const { globalGatewayUrl, authToken } = useHealthyBowl();\n const [state, setState] = useState<WalletState>({ ...EMPTY_STATE, loading: true });\n\n /** graphqlFetch options common to every call: global gateway + injected base URL when present. */\n const gqlBase = useCallback(\n () => ({\n gateway: 'global' as const,\n ...(globalGatewayUrl ? { baseUrl: globalGatewayUrl } : {}),\n ...(authToken ? { authToken } : {}),\n }),\n [globalGatewayUrl, authToken]\n );\n\n /** Resolve the farm-org's default billing account id (org comes from the auth context header). */\n const resolveBillingAccountId = useCallback(async (): Promise<{ id: string | null; currency: string }> => {\n const res = await graphqlFetch<{ getBillingAccountsByOrg?: BillingAccountLite[] }>({\n ...gqlBase(),\n query: BILLING_ACCOUNTS_QUERY,\n operationName: 'HbWalletBillingAccounts',\n organizationId: true,\n });\n firstError(res.errors, 'Could not read billing accounts');\n const accounts = (res.data?.getBillingAccountsByOrg ?? []).filter((a): a is BillingAccountLite => Boolean(a?.id));\n const chosen = accounts.find((a) => a.isDefault) ?? accounts.find((a) => a.isActive) ?? accounts[0] ?? null;\n return { id: chosen?.id ?? null, currency: chosen?.currency ?? DEFAULT_CURRENCY };\n }, [gqlBase]);\n\n const fetchBalance = useCallback(\n async (billingAccountId: string): Promise<CreditBalances | null> => {\n const res = await graphqlFetch<{ getCreditBalanceByType?: CreditBalances }>({\n ...gqlBase(),\n query: CREDIT_BALANCE_QUERY,\n variables: { billingAccountId },\n operationName: 'HbWalletCreditBalance',\n organizationId: true,\n });\n firstError(res.errors, 'Could not read credit balance');\n return res.data?.getCreditBalanceByType ?? null;\n },\n [gqlBase]\n );\n\n const fetchTransactions = useCallback(\n async (billingAccountId: string): Promise<WalletTransaction[]> => {\n const res = await graphqlFetch<{\n getBillingAccountCreditTransactions?: { creditTransactions?: WalletTransaction[] };\n }>({\n ...gqlBase(),\n query: CREDIT_TRANSACTIONS_QUERY,\n variables: { billingAccountID: billingAccountId, days: TRANSACTIONS_WINDOW_DAYS, page: 0, pageSize: 50 },\n operationName: 'HbWalletCreditTransactions',\n organizationId: true,\n });\n firstError(res.errors, 'Could not read transactions');\n return res.data?.getBillingAccountCreditTransactions?.creditTransactions ?? [];\n },\n [gqlBase]\n );\n\n const fetchPayoutAccounts = useCallback(\n async (billingAccountId: string): Promise<WalletPayoutAccount[]> => {\n // Best-effort: a farmer with no payout account yet must not break the wallet — the page just\n // can't offer a payout until one is added in billing settings.\n const res = await graphqlFetch<{ myPayoutAccounts?: WalletPayoutAccount[] }>({\n ...gqlBase(),\n query: PAYOUT_ACCOUNTS_QUERY,\n variables: { billingAccountId },\n operationName: 'HbWalletPayoutAccounts',\n organizationId: true,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors?.length) return [];\n return res.data?.myPayoutAccounts ?? [];\n },\n [gqlBase]\n );\n\n /** Full initial load: resolve account, then read balance + transactions + payout accounts. */\n const load = useCallback(async () => {\n setState((prev) => ({ ...prev, loading: true, error: null }));\n try {\n const { id, currency } = await resolveBillingAccountId();\n if (!id) {\n setState({ ...EMPTY_STATE, loading: false });\n return;\n }\n const [balances, transactions, payoutAccounts] = await Promise.all([\n fetchBalance(id),\n fetchTransactions(id),\n fetchPayoutAccounts(id),\n ]);\n setState({\n billingAccountId: id,\n currency: currency || DEFAULT_CURRENCY,\n balances,\n transactions,\n payoutAccounts,\n loading: false,\n error: null,\n });\n } catch (err) {\n setState((prev) => ({\n ...prev,\n loading: false,\n error: err instanceof Error ? err.message : 'Could not load your wallet',\n }));\n }\n }, [resolveBillingAccountId, fetchBalance, fetchTransactions, fetchPayoutAccounts]);\n\n useEffect(() => {\n void load();\n }, [load]);\n\n /** Re-read balance + transactions for the already-resolved account (post top-up / payout). */\n const refetch = useCallback(async () => {\n const id = state.billingAccountId;\n if (!id) {\n await load();\n return;\n }\n try {\n const [balances, transactions] = await Promise.all([fetchBalance(id), fetchTransactions(id)]);\n setState((prev) => ({ ...prev, balances, transactions }));\n } catch {\n // A failed refresh must not clobber the balances already on screen — the money movement\n // (settled by billing) already happened; a transient read failure is not a wallet error.\n }\n }, [state.billingAccountId, fetchBalance, fetchTransactions, load]);\n\n const buyCredits = useCallback(\n async (amountInr: number): Promise<TopUpSession> => {\n const id = state.billingAccountId;\n if (!id) throw new Error('No billing account is set up for this farm yet');\n const res = await graphqlFetch<{ initiatePayment?: TopUpSession }>({\n ...gqlBase(),\n query: INITIATE_TOPUP_MUTATION,\n variables: {\n input: {\n billingAccountId: id,\n purchaseType: 'CREDITS',\n // 1 credit = ₹1 for HB packs; billing recomputes tax and returns the authoritative total.\n creditAmount: Math.round(amountInr * CREDIT_PER_CURRENCY_UNIT),\n amount: amountInr,\n currency: state.currency || DEFAULT_CURRENCY,\n provider: 'RAZORPAY',\n },\n },\n operationName: 'HbWalletInitiateTopUp',\n organizationId: true,\n });\n firstError(res.errors, 'Could not start the top-up');\n const session = res.data?.initiatePayment;\n if (!session) throw new Error('Billing did not return a payment session');\n if (!session.success && session.error) throw new Error(session.error);\n return session;\n },\n [state.billingAccountId, state.currency, gqlBase]\n );\n\n const requestPayout = useCallback(\n async (amountInr: number, notes?: string): Promise<PayoutResult> => {\n const id = state.billingAccountId;\n if (!id) throw new Error('No billing account is set up for this farm yet');\n const payoutAccount =\n state.payoutAccounts.find((p) => p.isDefault && p.isActive) ??\n state.payoutAccounts.find((p) => p.isActive) ??\n state.payoutAccounts[0];\n if (!payoutAccount) {\n throw new Error('Add a payout (bank) account in billing settings before requesting a payout');\n }\n const res = await graphqlFetch<{ requestCreditWithdrawal?: PayoutResult }>({\n ...gqlBase(),\n query: REQUEST_PAYOUT_MUTATION,\n variables: {\n input: {\n billingAccountId: id,\n payoutAccountId: payoutAccount.id,\n creditAmount: amountInr,\n currency: state.currency || DEFAULT_CURRENCY,\n ...(notes ? { notes } : {}),\n },\n },\n operationName: 'HbWalletRequestPayout',\n organizationId: true,\n });\n firstError(res.errors, 'Could not request the payout');\n const payout = res.data?.requestCreditWithdrawal;\n if (!payout) throw new Error('Billing did not return the payout request');\n await refetch();\n return payout;\n },\n [state.billingAccountId, state.currency, state.payoutAccounts, gqlBase, refetch]\n );\n\n const payoutAccount =\n state.payoutAccounts.find((p) => p.isDefault && p.isActive) ??\n state.payoutAccounts.find((p) => p.isActive) ??\n state.payoutAccounts[0] ??\n null;\n\n return {\n ...state,\n payoutAccount,\n hasPayoutAccount: Boolean(payoutAccount),\n refetch,\n buyCredits,\n requestPayout,\n };\n}\n"],"mappings":";;;;AAwGA,IAAM,IAAuC,+IAWvC,IAAqC,6NAYrC,IAA0C,0eAwB1C,IAAsC,sQAetC,IAAwC,8SAkBxC,IAAwC,2NAsBxC,IAA2B,GAE3B,IAA2B,KAC3B,IAAmB,OAYnB,IAA2B;CAC/B,kBAAkB;CAClB,UAAU;CACV,UAAU;CACV,cAAc,EAAE;CAChB,gBAAgB,EAAE;CAClB,SAAS;CACT,OAAO;CACR;AAGD,SAAS,EAAW,GAA4C,GAAwB;AACtF,KAAI,GAAQ,OAAQ,OAAU,MAAM,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,EAAI,MAAM;AACzB,MAAI,CAAC,EAAQ,OAAU,MAAM,4CAA4C;AAEzE,SADA,MAAM,GAAS,EACR;IAET;EAAC,EAAM;EAAkB,EAAM;EAAU,EAAM;EAAgB;EAAS;EAAQ,CACjF,EAEK,IACJ,EAAM,eAAe,MAAM,MAAM,EAAE,aAAa,EAAE,SAAS,IAC3D,EAAM,eAAe,MAAM,MAAM,EAAE,SAAS,IAC5C,EAAM,eAAe,MACrB;AAEF,QAAO;EACL,GAAG;EACH;EACA,kBAAkB,EAAQ;EAC1B;EACA;EACA;EACD"}
1
+ {"version":3,"file":"useCreditsWallet.js","names":[],"sources":["../../../src/healthybowl/hooks/useCreditsWallet.ts"],"sourcesContent":["/**\n * Credits & Payments wallet (roadmap #08 / BOFF-2880) — the money side of HealthyBowl.\n *\n * This hook is a THIN client over the platform `global-billing-svc` credit module — HealthyBowl\n * adds NO payment backend, holds no card data and no Razorpay secrets. Every balance, transaction,\n * top-up and payout is a call to billing's already-composed ops on the GLOBAL gateway:\n *\n * - `getBillingAccountsByOrg` → resolve the farm-org's default billing account id\n * - `getCreditBalanceByType` → purchased / earned / granted / withdrawable / total\n * - `getBillingAccountCreditTransactions` → the recent ledger (top-ups and payouts; HB writes no credit spends)\n * - `myPayoutAccounts` → the bank/UPI payout account a withdrawal pays out to\n * - `initiatePayment` (purchaseType CREDITS) → a real Razorpay order for a credit top-up\n * - `requestCreditWithdrawal` → a payout request against the withdrawable balance\n *\n * These are GLOBAL-gateway ops, so they go through fe-libs `graphqlFetch({ gateway: 'global' })`\n * (which re-derives the bearer token and attaches the `x-org-id` context header from profile\n * storage) — NOT the workspace Apollo client the rest of HB uses. This mirrors\n * `useAssistantApiAccess`, the one other HB caller that reaches the global gateway with auth.\n *\n * The client never credits or debits anything itself: billing's Razorpay webhook settles a top-up\n * and only then does the balance move. After a top-up widget closes (or a payout is requested) we\n * simply re-read balance + transactions so the page reflects billing's authoritative state without\n * a full reload.\n *\n * @module healthybowl\n */\nimport { useCallback, useEffect, useState } from 'react';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n// ── Domain types (mirror the composed global-billing schema) ──────────────────\n\n/** Credit balance broken down by bucket, in the account's currency (INR for HB). */\nexport interface CreditBalances {\n purchased: number;\n earned: number;\n granted: number;\n withdrawable: number;\n total: number;\n}\n\n/** billing `CreditTransactionType` — how the ledger row arose. */\nexport type WalletTxnType = 'purchase' | 'usage' | 'granted' | 'adjustment';\n/** billing `CreditTransactionStatus`. */\nexport type WalletTxnStatus = 'success' | 'pending' | 'failed' | 'refund';\n\n/** One credit-ledger row as HB renders it. */\nexport interface WalletTransaction {\n id: string;\n amount: number;\n type: WalletTxnType;\n status: WalletTxnStatus;\n createdAt: string;\n entityType: string | null;\n /** Which bucket a debit came from (usage rows). */\n fromType: WalletTxnType | null;\n /** Present on the debit reserved for a payout — lets us label it a withdrawal. */\n payoutRequestId: string | null;\n}\n\n/** A resolved payout destination a withdrawal can be sent to. */\nexport interface WalletPayoutAccount {\n id: string;\n label: string;\n displayName: string | null;\n isDefault: boolean;\n isActive: boolean;\n currency: string;\n accountLast4: string | null;\n status: string;\n}\n\n/**\n * What the page needs to open the Razorpay widget for a credit top-up. Billing computes the tax\n * and returns the authoritative `total` — HB opens the widget for exactly that, never a\n * self-computed amount.\n */\nexport interface TopUpSession {\n success: boolean;\n /** RAZORPAY / STRIPE — billing decides; this UI only opens Razorpay. */\n provider: string;\n /** Razorpay `order_xxx`; null when billing routed elsewhere. */\n orderId: string | null;\n razorpayKeyId: string | null;\n clientSecret: string | null;\n subtotal: number;\n taxAmount: number;\n total: number;\n currency: string;\n paymentId: string | null;\n error: string | null;\n}\n\n/** Result of a payout request. */\nexport interface PayoutResult {\n id: string;\n status: string;\n requestedAmount: number;\n currency: string;\n createdAt: string;\n}\n\n// ── GraphQL documents (global-billing ops, executed directly against the gateway) ──\n\nconst BILLING_ACCOUNTS_QUERY = /* GraphQL */ `\n query HbWalletBillingAccounts {\n getBillingAccountsByOrg {\n id\n isDefault\n isActive\n currency\n }\n }\n`;\n\nconst CREDIT_BALANCE_QUERY = /* GraphQL */ `\n query HbWalletCreditBalance($billingAccountId: ID!) {\n getCreditBalanceByType(billingAccountId: $billingAccountId) {\n purchased\n earned\n granted\n withdrawable\n total\n }\n }\n`;\n\nconst CREDIT_TRANSACTIONS_QUERY = /* GraphQL */ `\n query HbWalletCreditTransactions($billingAccountID: ID!, $days: Int!, $page: Int, $pageSize: Int) {\n getBillingAccountCreditTransactions(\n billingAccountID: $billingAccountID\n days: $days\n page: $page\n pageSize: $pageSize\n ) {\n creditTransactions {\n id\n amount\n type\n status\n createdAt\n entityType\n fromType\n payoutRequestId\n }\n totalCount\n hasMore\n }\n }\n`;\n\nconst PAYOUT_ACCOUNTS_QUERY = /* GraphQL */ `\n query HbWalletPayoutAccounts($billingAccountId: ID!) {\n myPayoutAccounts(billingAccountId: $billingAccountId) {\n id\n label\n displayName\n isDefault\n isActive\n currency\n accountLast4\n status\n }\n }\n`;\n\nconst INITIATE_TOPUP_MUTATION = /* GraphQL */ `\n mutation HbWalletInitiateTopUp($input: InitiatePaymentInput!) {\n initiatePayment(input: $input) {\n success\n provider\n orderId\n razorpayKeyId\n clientSecret\n subtotal\n taxAmount\n total\n currency\n paymentId\n error\n }\n }\n`;\n\nconst REQUEST_PAYOUT_MUTATION = /* GraphQL */ `\n mutation HbWalletRequestPayout($input: RequestCreditWithdrawalInput!) {\n requestCreditWithdrawal(input: $input) {\n id\n status\n requestedAmount\n currency\n createdAt\n }\n }\n`;\n\n// ── Wire response shapes ──────────────────────────────────────────────────────\n\ninterface BillingAccountLite {\n id: string | null;\n isDefault: boolean | null;\n isActive: boolean | null;\n currency: string | null;\n}\n\n/** Credits are priced 1:1 with the account currency (₹1 = 1 credit) for HB top-up packs. */\nconst CREDIT_PER_CURRENCY_UNIT = 1;\n/** How far back the transactions ledger reads. */\nconst TRANSACTIONS_WINDOW_DAYS = 365;\nconst DEFAULT_CURRENCY = 'INR';\n\ninterface WalletState {\n billingAccountId: string | null;\n currency: string;\n balances: CreditBalances | null;\n transactions: WalletTransaction[];\n payoutAccounts: WalletPayoutAccount[];\n loading: boolean;\n error: string | null;\n}\n\nconst EMPTY_STATE: WalletState = {\n billingAccountId: null,\n currency: DEFAULT_CURRENCY,\n balances: null,\n transactions: [],\n payoutAccounts: [],\n loading: false,\n error: null,\n};\n\n/** Throw the first GraphQL error, if any — callers surface it as a toast / error state. */\nfunction firstError(errors: { message?: string }[] | undefined, fallback: string): void {\n if (errors?.length) throw new Error(errors[0]?.message ?? fallback);\n}\n\nexport interface UseCreditsWallet extends WalletState {\n /** The default (or first active) payout destination, or null if none is set up. */\n payoutAccount: WalletPayoutAccount | null;\n hasPayoutAccount: boolean;\n /** Re-read balance + transactions (call after a top-up widget closes or a payout is requested). */\n refetch: () => Promise<void>;\n /**\n * Create a real Razorpay order for an `amountInr` credit top-up via billing's `initiatePayment`.\n * Returns the session the PAGE uses to open the Razorpay widget — the client never marks anything\n * paid; billing's webhook settles it and the balance moves on the next {@link refetch}.\n */\n buyCredits: (amountInr: number) => Promise<TopUpSession>;\n /**\n * Request a payout of `amountInr` withdrawable credits to the resolved payout account via\n * `requestCreditWithdrawal`. Refetches on success so the reserving debit shows as Processing.\n */\n requestPayout: (amountInr: number, notes?: string) => Promise<PayoutResult>;\n}\n\nexport function useCreditsWallet(): UseCreditsWallet {\n const { globalGatewayUrl, authToken } = useHealthyBowl();\n const [state, setState] = useState<WalletState>({ ...EMPTY_STATE, loading: true });\n\n /** graphqlFetch options common to every call: global gateway + injected base URL when present. */\n const gqlBase = useCallback(\n () => ({\n gateway: 'global' as const,\n ...(globalGatewayUrl ? { baseUrl: globalGatewayUrl } : {}),\n ...(authToken ? { authToken } : {}),\n }),\n [globalGatewayUrl, authToken]\n );\n\n /** Resolve the farm-org's default billing account id (org comes from the auth context header). */\n const resolveBillingAccountId = useCallback(async (): Promise<{ id: string | null; currency: string }> => {\n const res = await graphqlFetch<{ getBillingAccountsByOrg?: BillingAccountLite[] }>({\n ...gqlBase(),\n query: BILLING_ACCOUNTS_QUERY,\n operationName: 'HbWalletBillingAccounts',\n organizationId: true,\n });\n firstError(res.errors, 'Could not read billing accounts');\n const accounts = (res.data?.getBillingAccountsByOrg ?? []).filter((a): a is BillingAccountLite => Boolean(a?.id));\n const chosen = accounts.find((a) => a.isDefault) ?? accounts.find((a) => a.isActive) ?? accounts[0] ?? null;\n return { id: chosen?.id ?? null, currency: chosen?.currency ?? DEFAULT_CURRENCY };\n }, [gqlBase]);\n\n const fetchBalance = useCallback(\n async (billingAccountId: string): Promise<CreditBalances | null> => {\n const res = await graphqlFetch<{ getCreditBalanceByType?: CreditBalances }>({\n ...gqlBase(),\n query: CREDIT_BALANCE_QUERY,\n variables: { billingAccountId },\n operationName: 'HbWalletCreditBalance',\n organizationId: true,\n });\n firstError(res.errors, 'Could not read credit balance');\n return res.data?.getCreditBalanceByType ?? null;\n },\n [gqlBase]\n );\n\n const fetchTransactions = useCallback(\n async (billingAccountId: string): Promise<WalletTransaction[]> => {\n const res = await graphqlFetch<{\n getBillingAccountCreditTransactions?: { creditTransactions?: WalletTransaction[] };\n }>({\n ...gqlBase(),\n query: CREDIT_TRANSACTIONS_QUERY,\n variables: { billingAccountID: billingAccountId, days: TRANSACTIONS_WINDOW_DAYS, page: 0, pageSize: 50 },\n operationName: 'HbWalletCreditTransactions',\n organizationId: true,\n });\n firstError(res.errors, 'Could not read transactions');\n return res.data?.getBillingAccountCreditTransactions?.creditTransactions ?? [];\n },\n [gqlBase]\n );\n\n const fetchPayoutAccounts = useCallback(\n async (billingAccountId: string): Promise<WalletPayoutAccount[]> => {\n // Best-effort: a farmer with no payout account yet must not break the wallet — the page just\n // can't offer a payout until one is added in billing settings.\n const res = await graphqlFetch<{ myPayoutAccounts?: WalletPayoutAccount[] }>({\n ...gqlBase(),\n query: PAYOUT_ACCOUNTS_QUERY,\n variables: { billingAccountId },\n operationName: 'HbWalletPayoutAccounts',\n organizationId: true,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors?.length) return [];\n return res.data?.myPayoutAccounts ?? [];\n },\n [gqlBase]\n );\n\n /** Full initial load: resolve account, then read balance + transactions + payout accounts. */\n const load = useCallback(async () => {\n setState((prev) => ({ ...prev, loading: true, error: null }));\n try {\n const { id, currency } = await resolveBillingAccountId();\n if (!id) {\n setState({ ...EMPTY_STATE, loading: false });\n return;\n }\n const [balances, transactions, payoutAccounts] = await Promise.all([\n fetchBalance(id),\n fetchTransactions(id),\n fetchPayoutAccounts(id),\n ]);\n setState({\n billingAccountId: id,\n currency: currency || DEFAULT_CURRENCY,\n balances,\n transactions,\n payoutAccounts,\n loading: false,\n error: null,\n });\n } catch (err) {\n setState((prev) => ({\n ...prev,\n loading: false,\n error: err instanceof Error ? err.message : 'Could not load your wallet',\n }));\n }\n }, [resolveBillingAccountId, fetchBalance, fetchTransactions, fetchPayoutAccounts]);\n\n useEffect(() => {\n void load();\n }, [load]);\n\n /** Re-read balance + transactions for the already-resolved account (post top-up / payout). */\n const refetch = useCallback(async () => {\n const id = state.billingAccountId;\n if (!id) {\n await load();\n return;\n }\n try {\n const [balances, transactions] = await Promise.all([fetchBalance(id), fetchTransactions(id)]);\n setState((prev) => ({ ...prev, balances, transactions }));\n } catch {\n // A failed refresh must not clobber the balances already on screen — the money movement\n // (settled by billing) already happened; a transient read failure is not a wallet error.\n }\n }, [state.billingAccountId, fetchBalance, fetchTransactions, load]);\n\n const buyCredits = useCallback(\n async (amountInr: number): Promise<TopUpSession> => {\n const id = state.billingAccountId;\n if (!id) throw new Error('No billing account is set up for this farm yet');\n const res = await graphqlFetch<{ initiatePayment?: TopUpSession }>({\n ...gqlBase(),\n query: INITIATE_TOPUP_MUTATION,\n variables: {\n input: {\n billingAccountId: id,\n purchaseType: 'CREDITS',\n // 1 credit = ₹1 for HB packs; billing recomputes tax and returns the authoritative total.\n creditAmount: Math.round(amountInr * CREDIT_PER_CURRENCY_UNIT),\n amount: amountInr,\n currency: state.currency || DEFAULT_CURRENCY,\n provider: 'RAZORPAY',\n },\n },\n operationName: 'HbWalletInitiateTopUp',\n organizationId: true,\n });\n firstError(res.errors, 'Could not start the top-up');\n const session = res.data?.initiatePayment;\n if (!session) throw new Error('Billing did not return a payment session');\n if (!session.success && session.error) throw new Error(session.error);\n return session;\n },\n [state.billingAccountId, state.currency, gqlBase]\n );\n\n const requestPayout = useCallback(\n async (amountInr: number, notes?: string): Promise<PayoutResult> => {\n const id = state.billingAccountId;\n if (!id) throw new Error('No billing account is set up for this farm yet');\n const payoutAccount =\n state.payoutAccounts.find((p) => p.isDefault && p.isActive) ??\n state.payoutAccounts.find((p) => p.isActive) ??\n state.payoutAccounts[0];\n if (!payoutAccount) {\n throw new Error('Add a payout (bank) account in billing settings before requesting a payout');\n }\n const res = await graphqlFetch<{ requestCreditWithdrawal?: PayoutResult }>({\n ...gqlBase(),\n query: REQUEST_PAYOUT_MUTATION,\n variables: {\n input: {\n billingAccountId: id,\n payoutAccountId: payoutAccount.id,\n creditAmount: amountInr,\n currency: state.currency || DEFAULT_CURRENCY,\n ...(notes ? { notes } : {}),\n },\n },\n operationName: 'HbWalletRequestPayout',\n organizationId: true,\n });\n firstError(res.errors, 'Could not request the payout');\n const payout = res.data?.requestCreditWithdrawal;\n if (!payout) throw new Error('Billing did not return the payout request');\n await refetch();\n return payout;\n },\n [state.billingAccountId, state.currency, state.payoutAccounts, gqlBase, refetch]\n );\n\n const payoutAccount =\n state.payoutAccounts.find((p) => p.isDefault && p.isActive) ??\n state.payoutAccounts.find((p) => p.isActive) ??\n state.payoutAccounts[0] ??\n null;\n\n return {\n ...state,\n payoutAccount,\n hasPayoutAccount: Boolean(payoutAccount),\n refetch,\n buyCredits,\n requestPayout,\n };\n}\n"],"mappings":";;;;AAwGA,IAAM,IAAuC,+IAWvC,IAAqC,6NAYrC,IAA0C,0eAwB1C,IAAsC,sQAetC,IAAwC,8SAkBxC,IAAwC,2NAsB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