@burdenoff/microfe-healthybowl 2026.812.4 → 2026.812.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.
@@ -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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WAAW,EACT,OAAO;IACL,kBAAkB;IAClB,iBAAiB,EAAc;IAC/B,cAAc;IACd,UAAU,EAAM,YAAY;IAC5B,GAAI,IAAQ,EAAE,UAAO,GAAG,EAAE;IAC3B,EACF;GACD,eAAe;GACf,gBAAgB;GACjB,CAAC;AACF,IAAW,EAAI,QAAQ,+BAA+B;EACtD,IAAM,IAAS,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"}
@@ -195,8 +195,8 @@ var k = () => {
195
195
  ];
196
196
  return /* @__PURE__ */ w(r, {
197
197
  title: k("healthybowl.wallet.title", "Credits & Payments"),
198
- description: k("healthybowl.wallet.description", "Top up credits with Razorpay, pay for produce orders, and cash out what you earn."),
199
- purpose: "Your farm's money wallet. Buy credits (UPI / card / netbanking via Razorpay) to pay for marketplace orders, and request a payout of the credits you earn from produce sales to your bank. All payments run through the platform billing rail — HealthyBowl keeps no card data.",
198
+ description: k("healthybowl.wallet.description", "Top up your platform credit balance with Razorpay and request a payout of your withdrawable balance to your bank."),
199
+ purpose: "Your farm-org's platform credit balance. Buy credits (UPI / card / netbanking via Razorpay) on the platform billing rail, and request a payout of your withdrawable balance to a bank account added in billing settings. Produce orders are paid at checkout by card / UPI — not from this balance. All payments run through the platform billing rail — HealthyBowl keeps no card data.",
200
200
  children: [L && !P ? /* @__PURE__ */ C(te, {}) : R && !P ? /* @__PURE__ */ C(c, {
201
201
  onRetry: () => void H(),
202
202
  title: k("healthybowl.wallet.error", "Couldn't load your wallet")
@@ -246,7 +246,7 @@ var k = () => {
246
246
  children: k("healthybowl.wallet.empty.title", "Buy your first credits")
247
247
  }), /* @__PURE__ */ C("p", {
248
248
  className: "text-xs text-text-secondary",
249
- children: k("healthybowl.wallet.empty.description", "Your wallet is empty. Top up to pay for marketplace produce orders without leaving HealthyBowl.")
249
+ children: k("healthybowl.wallet.empty.description", "Your wallet is empty. Top up your credit balance with UPI, card or netbanking via Razorpay.")
250
250
  })] })]
251
251
  }),
252
252
  /* @__PURE__ */ C("div", {
@@ -288,7 +288,7 @@ var k = () => {
288
288
  }),
289
289
  /* @__PURE__ */ C("p", {
290
290
  className: "text-xs text-text-secondary",
291
- children: k("healthybowl.wallet.payout.blurb", "Cash out the credits you earned from produce sales to your bank account.")
291
+ children: k("healthybowl.wallet.payout.blurb", "Request a payout of your withdrawable credit balance to your linked bank account.")
292
292
  }),
293
293
  /* @__PURE__ */ w("div", {
294
294
  className: "rounded-lg bg-bg-sunken/40 p-3",
@@ -329,7 +329,7 @@ var k = () => {
329
329
  }), I.length === 0 ? /* @__PURE__ */ C(s, {
330
330
  illustration: "empty-files",
331
331
  title: k("healthybowl.wallet.txns.empty.title", "No transactions yet"),
332
- description: k("healthybowl.wallet.txns.empty.description", "Your top-ups, order payments and payouts will appear here.")
332
+ description: k("healthybowl.wallet.txns.empty.description", "Your top-ups and payouts will appear here.")
333
333
  }) : /* @__PURE__ */ C(a, {
334
334
  columns: se,
335
335
  data: I,
@@ -1 +1 @@
1
- {"version":3,"file":"CreditsWalletPage.js","names":[],"sources":["../../../../src/healthybowl/pages/wallet/CreditsWalletPage.tsx"],"sourcesContent":["/**\n * Credits & Payments wallet (roadmap #08 / BOFF-2880) — the money side of HealthyBowl.\n *\n * Reads the farm-org's credit balance (purchased / earned / withdrawable) from the platform\n * `global-billing-svc`, lets the farmer top up with a Razorpay pack, request a payout of earned\n * (withdrawable) credits to their bank, and see the recent credit-ledger transactions. All money\n * movement goes through billing — HealthyBowl adds no payment backend, holds no card data and no\n * Razorpay secrets (see {@link useCreditsWallet}). The top-up widget flow mirrors the marketplace\n * order checkout in `useOrderPayments`/`OrdersPage`: create a real billing order, open Razorpay,\n * and let billing's webhook settle it — the client never marks anything paid, it just re-reads the\n * balance once the widget closes.\n *\n * @module healthybowl\n */\nimport { useState, type FC } from 'react';\nimport { ArrowDownToLine, CreditCard, Landmark, Receipt, ShieldCheck, Sparkles, Wallet } from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { PageLayout, StatCard, DataTable, StatusBadge, EmptyState, ErrorState, PageLoader } from '../../components';\nimport type { Column } from '../../components';\nimport { ToastContainer } from '../../components/Toast';\nimport { useToast } from '../../hooks/useToast';\nimport { useConfirm } from '../../components/ConfirmDialog';\nimport { useCreditsWallet, type WalletTransaction } from '../../hooks/useCreditsWallet';\nimport { loadRazorpayCheckout } from '../../hooks/useOrderPayments';\nimport { formatCurrency, formatDate, cn } from '../../utils/helpers';\n\n/** The fixed top-up packs, in rupees (spec §3 / mockup §6). */\nconst TOP_UP_PACKS = [500, 1000, 2500, 5000] as const;\n\n/** The fe-libs translate function (key + literal fallback + optional interpolation vars). */\ntype TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;\n\n/** Map billing's `CreditTransactionStatus` onto a display label + StatusBadge variant. */\nfunction statusBadge(txn: WalletTransaction): { label: string; variant: 'success' | 'warning' | 'error' | 'info' } {\n switch (txn.status) {\n case 'success':\n // A settled purchase reads as \"Paid\"; every other settled row reads as \"Completed\".\n return txn.type === 'purchase'\n ? { label: 'Paid', variant: 'success' }\n : { label: 'Completed', variant: 'success' };\n case 'pending':\n return { label: 'Processing', variant: 'warning' };\n case 'failed':\n return { label: 'Failed', variant: 'error' };\n case 'refund':\n return { label: 'Refunded', variant: 'info' };\n default:\n return { label: txn.status, variant: 'info' };\n }\n}\n\n/** Human description of a ledger row from its type + entity. */\nfunction describe(txn: WalletTransaction, t: TFn): string {\n if (txn.payoutRequestId) return t('healthybowl.wallet.txn.payout', 'Payout to bank');\n switch (txn.type) {\n case 'purchase':\n return t('healthybowl.wallet.txn.purchase', 'Credit top-up');\n case 'usage':\n return txn.entityType\n ? t('healthybowl.wallet.txn.usageOn', 'Paid with credits — {{entity}}', { entity: txn.entityType })\n : t('healthybowl.wallet.txn.usage', 'Paid with credits');\n case 'granted':\n return t('healthybowl.wallet.txn.granted', 'Credits granted');\n case 'adjustment':\n return t('healthybowl.wallet.txn.adjustment', 'Balance adjustment');\n default:\n return txn.type;\n }\n}\n\n/** The payment method for a ledger row. */\nfunction methodOf(txn: WalletTransaction, t: TFn): string {\n if (txn.payoutRequestId) return t('healthybowl.wallet.method.bank', 'Bank payout');\n if (txn.type === 'purchase') return t('healthybowl.wallet.method.razorpay', 'Razorpay');\n return t('healthybowl.wallet.method.credits', 'Credits');\n}\n\n/** Debits (spends/payouts) are negative; top-ups/grants/refunds are positive. */\nfunction signedAmount(txn: WalletTransaction): number {\n const magnitude = Math.abs(txn.amount);\n return txn.type === 'usage' ? -magnitude : magnitude;\n}\n\nexport const CreditsWalletPage: FC = () => {\n // fe-libs `t(key, fallback, vars)` — falls back to the literal and interpolates `{{vars}}`.\n const { t } = useI18n();\n const { toasts, toast, dismiss } = useToast();\n const confirm = useConfirm();\n\n const {\n balances,\n currency,\n transactions,\n loading,\n error,\n billingAccountId,\n payoutAccount,\n hasPayoutAccount,\n refetch,\n buyCredits,\n requestPayout,\n } = useCreditsWallet();\n\n const [selectedPack, setSelectedPack] = useState<number>(TOP_UP_PACKS[0]);\n const [buying, setBuying] = useState(false);\n const [payingOut, setPayingOut] = useState(false);\n\n const inr = (amount: number) => formatCurrency(amount, currency || 'INR');\n const total = balances?.total ?? 0;\n const withdrawable = balances?.withdrawable ?? 0;\n const isEmptyWallet = !loading && !error && total <= 0 && transactions.length === 0;\n\n // ── Top-up (Razorpay) ───────────────────────────────────────────────────────\n const handleBuy = async () => {\n setBuying(true);\n let widgetOpened = false;\n try {\n const session = await buyCredits(selectedPack);\n if (session.provider !== 'RAZORPAY') {\n toast({\n title: t('healthybowl.wallet.toast.unsupported.title', 'Unsupported payment provider'),\n description: t(\n 'healthybowl.wallet.toast.unsupported.description',\n 'Billing routed this top-up to {{provider}}, which this wallet cannot open yet.',\n { provider: session.provider }\n ),\n variant: 'warning',\n });\n return;\n }\n if (!session.orderId || !session.razorpayKeyId) {\n toast({\n title: t('healthybowl.wallet.toast.incomplete.title', 'Payment session incomplete'),\n description: t(\n 'healthybowl.wallet.toast.incomplete.description',\n 'Billing did not return the handles needed to open Razorpay. Please try again.'\n ),\n variant: 'error',\n });\n return;\n }\n\n const Razorpay = await loadRazorpayCheckout();\n // Razorpay can fire `handler` and then `ondismiss` for the same payment; settle once.\n let settled = false;\n const onClose = () => {\n if (settled) return;\n settled = true;\n setBuying(false);\n // Billing's webhook credits the balance asynchronously; re-read so the top-up shows without\n // a reload. If the webhook hasn't landed yet the balance simply updates on the next read.\n void refetch().then(() => {\n toast({\n title: t('healthybowl.wallet.toast.topupDone.title', 'Top-up submitted'),\n description: t(\n 'healthybowl.wallet.toast.topupDone.description',\n 'Your payment is being confirmed by billing. Your balance updates here once it settles.'\n ),\n variant: 'success',\n });\n });\n };\n\n const widget = new Razorpay({\n key: session.razorpayKeyId,\n order_id: session.orderId,\n // Razorpay bills in the smallest currency unit (paise for INR); use billing's total.\n amount: Math.round(session.total * 100),\n currency: session.currency,\n name: 'HealthyBowl',\n description: t('healthybowl.wallet.topup.description', 'Credit top-up — {{amount}}', {\n amount: inr(selectedPack),\n }),\n handler: onClose,\n modal: { ondismiss: onClose },\n });\n widget.open();\n widgetOpened = true;\n } catch (err) {\n toast({\n title: t('healthybowl.wallet.toast.topupFailed.title', 'Could not start the top-up'),\n description: err instanceof Error ? err.message : t('healthybowl.common.error', 'Unknown error'),\n variant: 'error',\n });\n } finally {\n // The widget's onClose clears `buying` once it's on screen; every other path clears here.\n if (!widgetOpened) setBuying(false);\n }\n };\n\n // ── Payout (withdraw) ─────────────────────────────────────────────────────────\n const handleRequestPayout = async () => {\n if (withdrawable <= 0) return;\n const ok = await confirm({\n title: t('healthybowl.wallet.payout.confirm.title', 'Request a payout?'),\n message: t(\n 'healthybowl.wallet.payout.confirm.message',\n 'Request a payout of {{amount}} from your withdrawable credits to {{account}}. It will show as Processing until billing pays it out.',\n {\n amount: inr(withdrawable),\n account:\n payoutAccount?.displayName || payoutAccount?.label || t('healthybowl.wallet.payout.yourBank', 'your bank'),\n }\n ),\n okButtonTitle: t('healthybowl.wallet.payout.confirm.ok', 'Request Payout'),\n destructive: false,\n });\n if (!ok) return;\n setPayingOut(true);\n try {\n await requestPayout(withdrawable);\n toast({\n title: t('healthybowl.wallet.toast.payoutDone.title', 'Payout requested'),\n description: t(\n 'healthybowl.wallet.toast.payoutDone.description',\n 'Your payout of {{amount}} is now Processing.',\n { amount: inr(withdrawable) }\n ),\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.wallet.toast.payoutFailed.title', 'Could not request the payout'),\n description: err instanceof Error ? err.message : t('healthybowl.common.error', 'Unknown error'),\n variant: 'error',\n });\n } finally {\n setPayingOut(false);\n }\n };\n\n const columns: Column<WalletTransaction>[] = [\n {\n key: 'createdAt',\n header: t('healthybowl.wallet.col.date', 'Date'),\n render: (txn) => <span className=\"whitespace-nowrap text-text-secondary\">{formatDate(txn.createdAt)}</span>,\n },\n {\n key: 'description',\n header: t('healthybowl.wallet.col.description', 'Description'),\n render: (txn) => <span className=\"font-medium text-text-primary\">{describe(txn, t)}</span>,\n },\n {\n key: 'method',\n header: t('healthybowl.wallet.col.method', 'Method'),\n render: (txn) => <span className=\"text-text-secondary\">{methodOf(txn, t)}</span>,\n },\n {\n key: 'amount',\n header: t('healthybowl.wallet.col.amount', 'Amount'),\n render: (txn) => {\n const amount = signedAmount(txn);\n return (\n <span className={cn('font-semibold tabular-nums', amount < 0 ? 'text-status-error-text' : 'text-success')}>\n {amount > 0 ? '+' : amount < 0 ? '-' : ''}\n {inr(Math.abs(amount))}\n </span>\n );\n },\n },\n {\n key: 'status',\n header: t('healthybowl.wallet.col.status', 'Status'),\n render: (txn) => {\n const badge = statusBadge(txn);\n return <StatusBadge label={badge.label} variant={badge.variant} />;\n },\n },\n ];\n\n return (\n <PageLayout\n title={t('healthybowl.wallet.title', 'Credits & Payments')}\n description={t(\n 'healthybowl.wallet.description',\n 'Top up credits with Razorpay, pay for produce orders, and cash out what you earn.'\n )}\n purpose=\"Your farm's money wallet. Buy credits (UPI / card / netbanking via Razorpay) to pay for marketplace orders, and request a payout of the credits you earn from produce sales to your bank. All payments run through the platform billing rail — HealthyBowl keeps no card data.\"\n >\n {loading && !balances ? (\n <PageLoader />\n ) : error && !balances ? (\n <ErrorState onRetry={() => void refetch()} title={t('healthybowl.wallet.error', \"Couldn't load your wallet\")} />\n ) : !billingAccountId ? (\n <EmptyState\n illustration=\"empty-data\"\n title={t('healthybowl.wallet.noAccount.title', 'No billing account yet')}\n description={t(\n 'healthybowl.wallet.noAccount.description',\n \"This farm's organization doesn't have a billing account set up yet. Once it does, your credit balance and payments will appear here.\"\n )}\n />\n ) : (\n <>\n {/* Balance cards */}\n <div className=\"grid grid-cols-2 gap-4 lg:grid-cols-4\">\n <StatCard\n hero\n label={t('healthybowl.wallet.balance.total', 'Credit Balance')}\n value={inr(total)}\n icon={<Wallet className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.wallet.balance.purchased', 'Purchased')}\n value={inr(balances?.purchased ?? 0)}\n icon={<CreditCard className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.wallet.balance.earned', 'Earned')}\n value={inr(balances?.earned ?? 0)}\n icon={<Sparkles className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.wallet.balance.withdrawable', 'Withdrawable')}\n value={inr(withdrawable)}\n icon={<ArrowDownToLine className=\"h-5 w-5\" />}\n />\n </div>\n\n <div className=\"grid gap-4 lg:grid-cols-3\">\n {/* Buy credits */}\n <div className=\"lg:col-span-2 flex flex-col gap-4 rounded-lg border border-border-subtle bg-bg-surface p-4 shadow-sm\">\n <div className=\"flex items-center gap-2\">\n <CreditCard className=\"h-4 w-4 text-text-secondary\" />\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.buy.title', 'Buy Credits')}\n </h2>\n </div>\n\n {isEmptyWallet && (\n <div className=\"flex items-start gap-3 rounded-lg border border-action-primary-bg/40 bg-action-primary-bg/10 p-3\">\n <Sparkles className=\"mt-0.5 h-4 w-4 shrink-0 text-action-primary-bg\" />\n <div>\n <p className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.empty.title', 'Buy your first credits')}\n </p>\n <p className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.wallet.empty.description',\n 'Your wallet is empty. Top up to pay for marketplace produce orders without leaving HealthyBowl.'\n )}\n </p>\n </div>\n </div>\n )}\n\n <div className=\"grid grid-cols-2 gap-2 sm:grid-cols-4\">\n {TOP_UP_PACKS.map((pack) => (\n <button\n key={pack}\n type=\"button\"\n onClick={() => setSelectedPack(pack)}\n aria-pressed={selectedPack === pack}\n className={cn(\n 'rounded-lg border p-3 text-center transition-colors',\n selectedPack === pack\n ? 'border-action-primary-bg bg-action-primary-bg/10 text-text-primary'\n : 'border-border-subtle text-text-secondary hover:bg-bg-sunken/50 hover:text-text-primary'\n )}\n >\n <span className=\"block text-base font-bold tabular-nums\">{inr(pack)}</span>\n <span className=\"text-[10px] text-text-secondary\">\n {t('healthybowl.wallet.buy.credits', '{{count}} credits', { count: String(pack) })}\n </span>\n </button>\n ))}\n </div>\n\n <Button onClick={() => void handleBuy()} disabled={buying} className=\"w-full sm:w-auto\">\n <CreditCard className=\"h-4 w-4\" />\n {buying\n ? t('healthybowl.wallet.buy.processing', 'Opening Razorpay…')\n : t('healthybowl.wallet.buy.cta', 'Buy Credits — {{amount}}', { amount: inr(selectedPack) })}\n </Button>\n\n <p className=\"flex items-center gap-1.5 text-[11px] text-text-secondary\">\n <ShieldCheck className=\"h-3.5 w-3.5\" />\n {t(\n 'healthybowl.wallet.buy.poweredBy',\n 'Powered by platform billing + Razorpay (UPI / card / netbanking). HealthyBowl stores no card data.'\n )}\n </p>\n </div>\n\n {/* Payout */}\n <div className=\"flex flex-col gap-3 rounded-lg border border-border-subtle bg-bg-surface p-4 shadow-sm\">\n <div className=\"flex items-center gap-2\">\n <Landmark className=\"h-4 w-4 text-text-secondary\" />\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.payout.title', 'Request Payout')}\n </h2>\n </div>\n <p className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.wallet.payout.blurb',\n 'Cash out the credits you earned from produce sales to your bank account.'\n )}\n </p>\n <div className=\"rounded-lg bg-bg-sunken/40 p-3\">\n <p className=\"text-[11px] uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.wallet.payout.available', 'Withdrawable')}\n </p>\n <p className=\"text-2xl font-semibold tabular-nums text-text-primary\">{inr(withdrawable)}</p>\n </div>\n <Button\n variant=\"outline\"\n onClick={() => void handleRequestPayout()}\n disabled={payingOut || withdrawable <= 0 || !hasPayoutAccount}\n className=\"w-full\"\n >\n <ArrowDownToLine className=\"h-4 w-4\" />\n {payingOut\n ? t('healthybowl.wallet.payout.processing', 'Processing…')\n : t('healthybowl.wallet.payout.cta', 'Request Payout')}\n </Button>\n {!hasPayoutAccount && withdrawable > 0 && (\n <p className=\"text-[11px] text-status-warning-text\">\n {t(\n 'healthybowl.wallet.payout.noAccount',\n 'Add a payout (bank) account in billing settings to request a payout.'\n )}\n </p>\n )}\n {withdrawable <= 0 && (\n <p className=\"text-[11px] text-text-secondary\">\n {t('healthybowl.wallet.payout.nothing', 'You have no withdrawable credits yet.')}\n </p>\n )}\n </div>\n </div>\n\n {/* Recent transactions */}\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex items-center gap-2\">\n <Receipt className=\"h-4 w-4 text-text-secondary\" />\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.txns.title', 'Recent Transactions')}\n </h2>\n </div>\n {transactions.length === 0 ? (\n <EmptyState\n illustration=\"empty-files\"\n title={t('healthybowl.wallet.txns.empty.title', 'No transactions yet')}\n description={t(\n 'healthybowl.wallet.txns.empty.description',\n 'Your top-ups, order payments and payouts will appear here.'\n )}\n />\n ) : (\n <DataTable\n columns={columns}\n data={transactions}\n keyField=\"id\"\n pageSize={10}\n emptyMessage={t('healthybowl.wallet.txns.empty.title', 'No transactions yet')}\n />\n )}\n </div>\n </>\n )}\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,IAAM,IAAe;CAAC;CAAK;CAAM;CAAM;CAAK;AAM5C,SAAS,EAAY,GAA8F;AACjH,SAAQ,EAAI,QAAZ;EACE,KAAK,UAEH,QAAO,EAAI,SAAS,aAChB;GAAE,OAAO;GAAQ,SAAS;GAAW,GACrC;GAAE,OAAO;GAAa,SAAS;GAAW;EAChD,KAAK,UACH,QAAO;GAAE,OAAO;GAAc,SAAS;GAAW;EACpD,KAAK,SACH,QAAO;GAAE,OAAO;GAAU,SAAS;GAAS;EAC9C,KAAK,SACH,QAAO;GAAE,OAAO;GAAY,SAAS;GAAQ;EAC/C,QACE,QAAO;GAAE,OAAO,EAAI;GAAQ,SAAS;GAAQ;;;AAKnD,SAAS,EAAS,GAAwB,GAAgB;AACxD,KAAI,EAAI,gBAAiB,QAAO,EAAE,iCAAiC,iBAAiB;AACpF,SAAQ,EAAI,MAAZ;EACE,KAAK,WACH,QAAO,EAAE,mCAAmC,gBAAgB;EAC9D,KAAK,QACH,QAAO,EAAI,aACP,EAAE,kCAAkC,kCAAkC,EAAE,QAAQ,EAAI,YAAY,CAAC,GACjG,EAAE,gCAAgC,oBAAoB;EAC5D,KAAK,UACH,QAAO,EAAE,kCAAkC,kBAAkB;EAC/D,KAAK,aACH,QAAO,EAA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AAA,EACtC,IACG,EAAE,wCAAwC,cAAc,GACxD,EAAE,iCAAiC,iBAAiB,CACjD;;MACR,CAAC,KAAoB,IAAe,KACnC,kBAAC,KAAD;OAAG,WAAU;iBACV,EACC,uCACA,uEACD;OACC,CAAA;MAEL,KAAgB,KACf,kBAAC,KAAD;OAAG,WAAU;iBACV,EAAE,qCAAqC,wCAAwC;OAC9E,CAAA;MAEF;OACF;;GAGN,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,OAAD;KAAK,WAAU;eAAf,CACE,kBAAC,GAAD,EAAS,WAAU,+BAAgC,CAAA,EACnD,kBAAC,MAAD;MAAI,WAAU;gBACX,EAAE,iCAAiC,sBAAsB;MACvD,CAAA,CACD;QACL,EAAa,WAAW,IACvB,kBAAC,GAAD;KACE,cAAa;KACb,OAAO,EAAE,uCAAuC,sBAAsB;KACtE,aAAa,EACX,6CACA,6DACD;KACD,CAAA,GAEF,kBAAC,GAAD;KACW;KACT,MAAM;KACN,UAAS;KACT,UAAU;KACV,cAAc,EAAE,uCAAuC,sBAAsB;KAC7E,CAAA,CAEA;;GACL,EAAA,CAAA,GA9KH,kBAAC,GAAD;GACE,cAAa;GACb,OAAO,EAAE,sCAAsC,yBAAyB;GACxE,aAAa,EACX,4CACA,uIACD;GACD,CAAA,EA0KJ,kBAAC,GAAD;GAAwB;GAAQ,WAAW;GAAW,CAAA,CAC3C"}
1
+ {"version":3,"file":"CreditsWalletPage.js","names":[],"sources":["../../../../src/healthybowl/pages/wallet/CreditsWalletPage.tsx"],"sourcesContent":["/**\n * Credits & Payments wallet (roadmap #08 / BOFF-2880) — the money side of HealthyBowl.\n *\n * Reads the farm-org's platform credit balance (purchased / earned / withdrawable) from the\n * platform `global-billing-svc`, lets the farmer top up with a Razorpay pack, request a payout of\n * the withdrawable balance to their bank, and see the recent credit-ledger transactions. HealthyBowl\n * itself never writes the earned bucket and credits are NOT a produce-order payment method — orders\n * are charged at checkout by card / UPI through billing's Razorpay order rail (see\n * `useOrderPayments`), not debited from this balance. All money movement goes through billing —\n * HealthyBowl adds no payment backend, holds no card data and no Razorpay secrets (see\n * {@link useCreditsWallet}). The top-up widget flow mirrors that order checkout: create a real\n * billing order, open Razorpay, and let billing's webhook settle it — the client never marks\n * anything paid, it just re-reads the balance once the widget closes.\n *\n * @module healthybowl\n */\nimport { useState, type FC } from 'react';\nimport { ArrowDownToLine, CreditCard, Landmark, Receipt, ShieldCheck, Sparkles, Wallet } from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { PageLayout, StatCard, DataTable, StatusBadge, EmptyState, ErrorState, PageLoader } from '../../components';\nimport type { Column } from '../../components';\nimport { ToastContainer } from '../../components/Toast';\nimport { useToast } from '../../hooks/useToast';\nimport { useConfirm } from '../../components/ConfirmDialog';\nimport { useCreditsWallet, type WalletTransaction } from '../../hooks/useCreditsWallet';\nimport { loadRazorpayCheckout } from '../../hooks/useOrderPayments';\nimport { formatCurrency, formatDate, cn } from '../../utils/helpers';\n\n/** The fixed top-up packs, in rupees (spec §3 / mockup §6). */\nconst TOP_UP_PACKS = [500, 1000, 2500, 5000] as const;\n\n/** The fe-libs translate function (key + literal fallback + optional interpolation vars). */\ntype TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;\n\n/** Map billing's `CreditTransactionStatus` onto a display label + StatusBadge variant. */\nfunction statusBadge(txn: WalletTransaction): { label: string; variant: 'success' | 'warning' | 'error' | 'info' } {\n switch (txn.status) {\n case 'success':\n // A settled purchase reads as \"Paid\"; every other settled row reads as \"Completed\".\n return txn.type === 'purchase'\n ? { label: 'Paid', variant: 'success' }\n : { label: 'Completed', variant: 'success' };\n case 'pending':\n return { label: 'Processing', variant: 'warning' };\n case 'failed':\n return { label: 'Failed', variant: 'error' };\n case 'refund':\n return { label: 'Refunded', variant: 'info' };\n default:\n return { label: txn.status, variant: 'info' };\n }\n}\n\n/** Human description of a ledger row from its type + entity. */\nfunction describe(txn: WalletTransaction, t: TFn): string {\n if (txn.payoutRequestId) return t('healthybowl.wallet.txn.payout', 'Payout to bank');\n switch (txn.type) {\n case 'purchase':\n return t('healthybowl.wallet.txn.purchase', 'Credit top-up');\n case 'usage':\n return txn.entityType\n ? t('healthybowl.wallet.txn.usageOn', 'Paid with credits — {{entity}}', { entity: txn.entityType })\n : t('healthybowl.wallet.txn.usage', 'Paid with credits');\n case 'granted':\n return t('healthybowl.wallet.txn.granted', 'Credits granted');\n case 'adjustment':\n return t('healthybowl.wallet.txn.adjustment', 'Balance adjustment');\n default:\n return txn.type;\n }\n}\n\n/** The payment method for a ledger row. */\nfunction methodOf(txn: WalletTransaction, t: TFn): string {\n if (txn.payoutRequestId) return t('healthybowl.wallet.method.bank', 'Bank payout');\n if (txn.type === 'purchase') return t('healthybowl.wallet.method.razorpay', 'Razorpay');\n return t('healthybowl.wallet.method.credits', 'Credits');\n}\n\n/** Debits (spends/payouts) are negative; top-ups/grants/refunds are positive. */\nfunction signedAmount(txn: WalletTransaction): number {\n const magnitude = Math.abs(txn.amount);\n return txn.type === 'usage' ? -magnitude : magnitude;\n}\n\nexport const CreditsWalletPage: FC = () => {\n // fe-libs `t(key, fallback, vars)` — falls back to the literal and interpolates `{{vars}}`.\n const { t } = useI18n();\n const { toasts, toast, dismiss } = useToast();\n const confirm = useConfirm();\n\n const {\n balances,\n currency,\n transactions,\n loading,\n error,\n billingAccountId,\n payoutAccount,\n hasPayoutAccount,\n refetch,\n buyCredits,\n requestPayout,\n } = useCreditsWallet();\n\n const [selectedPack, setSelectedPack] = useState<number>(TOP_UP_PACKS[0]);\n const [buying, setBuying] = useState(false);\n const [payingOut, setPayingOut] = useState(false);\n\n const inr = (amount: number) => formatCurrency(amount, currency || 'INR');\n const total = balances?.total ?? 0;\n const withdrawable = balances?.withdrawable ?? 0;\n const isEmptyWallet = !loading && !error && total <= 0 && transactions.length === 0;\n\n // ── Top-up (Razorpay) ───────────────────────────────────────────────────────\n const handleBuy = async () => {\n setBuying(true);\n let widgetOpened = false;\n try {\n const session = await buyCredits(selectedPack);\n if (session.provider !== 'RAZORPAY') {\n toast({\n title: t('healthybowl.wallet.toast.unsupported.title', 'Unsupported payment provider'),\n description: t(\n 'healthybowl.wallet.toast.unsupported.description',\n 'Billing routed this top-up to {{provider}}, which this wallet cannot open yet.',\n { provider: session.provider }\n ),\n variant: 'warning',\n });\n return;\n }\n if (!session.orderId || !session.razorpayKeyId) {\n toast({\n title: t('healthybowl.wallet.toast.incomplete.title', 'Payment session incomplete'),\n description: t(\n 'healthybowl.wallet.toast.incomplete.description',\n 'Billing did not return the handles needed to open Razorpay. Please try again.'\n ),\n variant: 'error',\n });\n return;\n }\n\n const Razorpay = await loadRazorpayCheckout();\n // Razorpay can fire `handler` and then `ondismiss` for the same payment; settle once.\n let settled = false;\n const onClose = () => {\n if (settled) return;\n settled = true;\n setBuying(false);\n // Billing's webhook credits the balance asynchronously; re-read so the top-up shows without\n // a reload. If the webhook hasn't landed yet the balance simply updates on the next read.\n void refetch().then(() => {\n toast({\n title: t('healthybowl.wallet.toast.topupDone.title', 'Top-up submitted'),\n description: t(\n 'healthybowl.wallet.toast.topupDone.description',\n 'Your payment is being confirmed by billing. Your balance updates here once it settles.'\n ),\n variant: 'success',\n });\n });\n };\n\n const widget = new Razorpay({\n key: session.razorpayKeyId,\n order_id: session.orderId,\n // Razorpay bills in the smallest currency unit (paise for INR); use billing's total.\n amount: Math.round(session.total * 100),\n currency: session.currency,\n name: 'HealthyBowl',\n description: t('healthybowl.wallet.topup.description', 'Credit top-up — {{amount}}', {\n amount: inr(selectedPack),\n }),\n handler: onClose,\n modal: { ondismiss: onClose },\n });\n widget.open();\n widgetOpened = true;\n } catch (err) {\n toast({\n title: t('healthybowl.wallet.toast.topupFailed.title', 'Could not start the top-up'),\n description: err instanceof Error ? err.message : t('healthybowl.common.error', 'Unknown error'),\n variant: 'error',\n });\n } finally {\n // The widget's onClose clears `buying` once it's on screen; every other path clears here.\n if (!widgetOpened) setBuying(false);\n }\n };\n\n // ── Payout (withdraw) ─────────────────────────────────────────────────────────\n const handleRequestPayout = async () => {\n if (withdrawable <= 0) return;\n const ok = await confirm({\n title: t('healthybowl.wallet.payout.confirm.title', 'Request a payout?'),\n message: t(\n 'healthybowl.wallet.payout.confirm.message',\n 'Request a payout of {{amount}} from your withdrawable credits to {{account}}. It will show as Processing until billing pays it out.',\n {\n amount: inr(withdrawable),\n account:\n payoutAccount?.displayName || payoutAccount?.label || t('healthybowl.wallet.payout.yourBank', 'your bank'),\n }\n ),\n okButtonTitle: t('healthybowl.wallet.payout.confirm.ok', 'Request Payout'),\n destructive: false,\n });\n if (!ok) return;\n setPayingOut(true);\n try {\n await requestPayout(withdrawable);\n toast({\n title: t('healthybowl.wallet.toast.payoutDone.title', 'Payout requested'),\n description: t(\n 'healthybowl.wallet.toast.payoutDone.description',\n 'Your payout of {{amount}} is now Processing.',\n { amount: inr(withdrawable) }\n ),\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.wallet.toast.payoutFailed.title', 'Could not request the payout'),\n description: err instanceof Error ? err.message : t('healthybowl.common.error', 'Unknown error'),\n variant: 'error',\n });\n } finally {\n setPayingOut(false);\n }\n };\n\n const columns: Column<WalletTransaction>[] = [\n {\n key: 'createdAt',\n header: t('healthybowl.wallet.col.date', 'Date'),\n render: (txn) => <span className=\"whitespace-nowrap text-text-secondary\">{formatDate(txn.createdAt)}</span>,\n },\n {\n key: 'description',\n header: t('healthybowl.wallet.col.description', 'Description'),\n render: (txn) => <span className=\"font-medium text-text-primary\">{describe(txn, t)}</span>,\n },\n {\n key: 'method',\n header: t('healthybowl.wallet.col.method', 'Method'),\n render: (txn) => <span className=\"text-text-secondary\">{methodOf(txn, t)}</span>,\n },\n {\n key: 'amount',\n header: t('healthybowl.wallet.col.amount', 'Amount'),\n render: (txn) => {\n const amount = signedAmount(txn);\n return (\n <span className={cn('font-semibold tabular-nums', amount < 0 ? 'text-status-error-text' : 'text-success')}>\n {amount > 0 ? '+' : amount < 0 ? '-' : ''}\n {inr(Math.abs(amount))}\n </span>\n );\n },\n },\n {\n key: 'status',\n header: t('healthybowl.wallet.col.status', 'Status'),\n render: (txn) => {\n const badge = statusBadge(txn);\n return <StatusBadge label={badge.label} variant={badge.variant} />;\n },\n },\n ];\n\n return (\n <PageLayout\n title={t('healthybowl.wallet.title', 'Credits & Payments')}\n description={t(\n 'healthybowl.wallet.description',\n 'Top up your platform credit balance with Razorpay and request a payout of your withdrawable balance to your bank.'\n )}\n purpose=\"Your farm-org's platform credit balance. Buy credits (UPI / card / netbanking via Razorpay) on the platform billing rail, and request a payout of your withdrawable balance to a bank account added in billing settings. Produce orders are paid at checkout by card / UPI — not from this balance. All payments run through the platform billing rail — HealthyBowl keeps no card data.\"\n >\n {loading && !balances ? (\n <PageLoader />\n ) : error && !balances ? (\n <ErrorState onRetry={() => void refetch()} title={t('healthybowl.wallet.error', \"Couldn't load your wallet\")} />\n ) : !billingAccountId ? (\n <EmptyState\n illustration=\"empty-data\"\n title={t('healthybowl.wallet.noAccount.title', 'No billing account yet')}\n description={t(\n 'healthybowl.wallet.noAccount.description',\n \"This farm's organization doesn't have a billing account set up yet. Once it does, your credit balance and payments will appear here.\"\n )}\n />\n ) : (\n <>\n {/* Balance cards */}\n <div className=\"grid grid-cols-2 gap-4 lg:grid-cols-4\">\n <StatCard\n hero\n label={t('healthybowl.wallet.balance.total', 'Credit Balance')}\n value={inr(total)}\n icon={<Wallet className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.wallet.balance.purchased', 'Purchased')}\n value={inr(balances?.purchased ?? 0)}\n icon={<CreditCard className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.wallet.balance.earned', 'Earned')}\n value={inr(balances?.earned ?? 0)}\n icon={<Sparkles className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.wallet.balance.withdrawable', 'Withdrawable')}\n value={inr(withdrawable)}\n icon={<ArrowDownToLine className=\"h-5 w-5\" />}\n />\n </div>\n\n <div className=\"grid gap-4 lg:grid-cols-3\">\n {/* Buy credits */}\n <div className=\"lg:col-span-2 flex flex-col gap-4 rounded-lg border border-border-subtle bg-bg-surface p-4 shadow-sm\">\n <div className=\"flex items-center gap-2\">\n <CreditCard className=\"h-4 w-4 text-text-secondary\" />\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.buy.title', 'Buy Credits')}\n </h2>\n </div>\n\n {isEmptyWallet && (\n <div className=\"flex items-start gap-3 rounded-lg border border-action-primary-bg/40 bg-action-primary-bg/10 p-3\">\n <Sparkles className=\"mt-0.5 h-4 w-4 shrink-0 text-action-primary-bg\" />\n <div>\n <p className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.empty.title', 'Buy your first credits')}\n </p>\n <p className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.wallet.empty.description',\n 'Your wallet is empty. Top up your credit balance with UPI, card or netbanking via Razorpay.'\n )}\n </p>\n </div>\n </div>\n )}\n\n <div className=\"grid grid-cols-2 gap-2 sm:grid-cols-4\">\n {TOP_UP_PACKS.map((pack) => (\n <button\n key={pack}\n type=\"button\"\n onClick={() => setSelectedPack(pack)}\n aria-pressed={selectedPack === pack}\n className={cn(\n 'rounded-lg border p-3 text-center transition-colors',\n selectedPack === pack\n ? 'border-action-primary-bg bg-action-primary-bg/10 text-text-primary'\n : 'border-border-subtle text-text-secondary hover:bg-bg-sunken/50 hover:text-text-primary'\n )}\n >\n <span className=\"block text-base font-bold tabular-nums\">{inr(pack)}</span>\n <span className=\"text-[10px] text-text-secondary\">\n {t('healthybowl.wallet.buy.credits', '{{count}} credits', { count: String(pack) })}\n </span>\n </button>\n ))}\n </div>\n\n <Button onClick={() => void handleBuy()} disabled={buying} className=\"w-full sm:w-auto\">\n <CreditCard className=\"h-4 w-4\" />\n {buying\n ? t('healthybowl.wallet.buy.processing', 'Opening Razorpay…')\n : t('healthybowl.wallet.buy.cta', 'Buy Credits — {{amount}}', { amount: inr(selectedPack) })}\n </Button>\n\n <p className=\"flex items-center gap-1.5 text-[11px] text-text-secondary\">\n <ShieldCheck className=\"h-3.5 w-3.5\" />\n {t(\n 'healthybowl.wallet.buy.poweredBy',\n 'Powered by platform billing + Razorpay (UPI / card / netbanking). HealthyBowl stores no card data.'\n )}\n </p>\n </div>\n\n {/* Payout */}\n <div className=\"flex flex-col gap-3 rounded-lg border border-border-subtle bg-bg-surface p-4 shadow-sm\">\n <div className=\"flex items-center gap-2\">\n <Landmark className=\"h-4 w-4 text-text-secondary\" />\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.payout.title', 'Request Payout')}\n </h2>\n </div>\n <p className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.wallet.payout.blurb',\n 'Request a payout of your withdrawable credit balance to your linked bank account.'\n )}\n </p>\n <div className=\"rounded-lg bg-bg-sunken/40 p-3\">\n <p className=\"text-[11px] uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.wallet.payout.available', 'Withdrawable')}\n </p>\n <p className=\"text-2xl font-semibold tabular-nums text-text-primary\">{inr(withdrawable)}</p>\n </div>\n <Button\n variant=\"outline\"\n onClick={() => void handleRequestPayout()}\n disabled={payingOut || withdrawable <= 0 || !hasPayoutAccount}\n className=\"w-full\"\n >\n <ArrowDownToLine className=\"h-4 w-4\" />\n {payingOut\n ? t('healthybowl.wallet.payout.processing', 'Processing…')\n : t('healthybowl.wallet.payout.cta', 'Request Payout')}\n </Button>\n {!hasPayoutAccount && withdrawable > 0 && (\n <p className=\"text-[11px] text-status-warning-text\">\n {t(\n 'healthybowl.wallet.payout.noAccount',\n 'Add a payout (bank) account in billing settings to request a payout.'\n )}\n </p>\n )}\n {withdrawable <= 0 && (\n <p className=\"text-[11px] text-text-secondary\">\n {t('healthybowl.wallet.payout.nothing', 'You have no withdrawable credits yet.')}\n </p>\n )}\n </div>\n </div>\n\n {/* Recent transactions */}\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex items-center gap-2\">\n <Receipt className=\"h-4 w-4 text-text-secondary\" />\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.wallet.txns.title', 'Recent Transactions')}\n </h2>\n </div>\n {transactions.length === 0 ? (\n <EmptyState\n illustration=\"empty-files\"\n title={t('healthybowl.wallet.txns.empty.title', 'No transactions yet')}\n description={t(\n 'healthybowl.wallet.txns.empty.description',\n 'Your top-ups and payouts will appear here.'\n )}\n />\n ) : (\n <DataTable\n columns={columns}\n data={transactions}\n keyField=\"id\"\n pageSize={10}\n emptyMessage={t('healthybowl.wallet.txns.empty.title', 'No transactions yet')}\n />\n )}\n </div>\n </>\n )}\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA8BA,IAAM,IAAe;CAAC;CAAK;CAAM;CAAM;CAAK;AAM5C,SAAS,EAAY,GAA8F;AACjH,SAAQ,EAAI,QAAZ;EACE,KAAK,UAEH,QAAO,EAAI,SAAS,aAChB;GAAE,OAAO;GAAQ,SAAS;GAAW,GACrC;GAAE,OAAO;GAAa,SAAS;GAAW;EAChD,KAAK,UACH,QAAO;GAAE,OAAO;GAAc,SAAS;GAAW;EACpD,KAAK,SACH,QAAO;GAAE,OAAO;GAAU,SAAS;GAAS;EAC9C,KAAK,SACH,QAAO;GAAE,OAAO;GAAY,SAAS;GAAQ;EAC/C,QACE,QAAO;GAAE,OAAO,EAAI;GAAQ,SAAS;GAAQ;;;AAKnD,SAAS,EAAS,GAAwB,GAAgB;AACxD,KAAI,EAAI,gBAAiB,QAAO,EAAE,iCAAiC,iBAAiB;AACpF,SAAQ,EAAI,MAAZ;EACE,KAAK,WACH,QAAO,EAAE,mCAAmC,gBAAgB;EAC9D,KAAK,QACH,QAAO,EAAI,aACP,EAAE,kCAAkC,kCAAkC,EAAE,QAAQ,EAAI,YAAY,CAAC,GACjG,EAAE,gCAAgC,oBAAoB;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B,KAAK,CAAC;OAC7C,WAAU;iBAJZ,CAME,kBAAC,GAAD,EAAiB,WAAU,WAAY,CAAA,EACtC,IACG,EAAE,wCAAwC,cAAc,GACxD,EAAE,iCAAiC,iBAAiB,CACjD;;MACR,CAAC,KAAoB,IAAe,KACnC,kBAAC,KAAD;OAAG,WAAU;iBACV,EACC,uCACA,uEACD;OACC,CAAA;MAEL,KAAgB,KACf,kBAAC,KAAD;OAAG,WAAU;iBACV,EAAE,qCAAqC,wCAAwC;OAC9E,CAAA;MAEF;OACF;;GAGN,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,OAAD;KAAK,WAAU;eAAf,CACE,kBAAC,GAAD,EAAS,WAAU,+BAAgC,CAAA,EACnD,kBAAC,MAAD;MAAI,WAAU;gBACX,EAAE,iCAAiC,sBAAsB;MACvD,CAAA,CACD;QACL,EAAa,WAAW,IACvB,kBAAC,GAAD;KACE,cAAa;KACb,OAAO,EAAE,uCAAuC,sBAAsB;KACtE,aAAa,EACX,6CACA,6CACD;KACD,CAAA,GAEF,kBAAC,GAAD;KACW;KACT,MAAM;KACN,UAAS;KACT,UAAU;KACV,cAAc,EAAE,uCAAuC,sBAAsB;KAC7E,CAAA,CAEA;;GACL,EAAA,CAAA,GA9KH,kBAAC,GAAD;GACE,cAAa;GACb,OAAO,EAAE,sCAAsC,yBAAyB;GACxE,aAAa,EACX,4CACA,uIACD;GACD,CAAA,EA0KJ,kBAAC,GAAD;GAAwB;GAAQ,WAAW;GAAW,CAAA,CAC3C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.812.4",
3
+ "version": "2026.812.5",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [