@burdenoff/microfe-healthybowl 2026.812.3 → 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.
- package/dist/healthybowl/hooks/useCreditsWallet.js.map +1 -1
- package/dist/healthybowl/hooks/useSharedMarket.js +67 -2
- package/dist/healthybowl/hooks/useSharedMarket.js.map +1 -1
- package/dist/healthybowl/pages/marketplace/AuctionsView.js +170 -147
- package/dist/healthybowl/pages/marketplace/AuctionsView.js.map +1 -1
- package/dist/healthybowl/pages/marketplace/MarketplacePage.js +475 -472
- package/dist/healthybowl/pages/marketplace/MarketplacePage.js.map +1 -1
- package/dist/healthybowl/pages/marketplace/SharedMarketView.js +307 -137
- package/dist/healthybowl/pages/marketplace/SharedMarketView.js.map +1 -1
- package/dist/healthybowl/pages/wallet/CreditsWalletPage.js +5 -5
- package/dist/healthybowl/pages/wallet/CreditsWalletPage.js.map +1 -1
- package/package.json +1 -1
|
@@ -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,EAAO,IAAI,WAAW,EAAS;;AAsBrE,SAAgB,IAAqC;CACnD,IAAM,EAAE,qBAAkB,iBAAc,GAAgB,EAClD,CAAC,GAAO,KAAY,EAAsB;EAAE,GAAG;EAAa,SAAS;EAAM,CAAC,EAG5E,IAAU,SACP;EACL,SAAS;EACT,GAAI,IAAmB,EAAE,SAAS,GAAkB,GAAG,EAAE;EACzD,GAAI,IAAY,EAAE,cAAW,GAAG,EAAE;EACnC,GACD,CAAC,GAAkB,EAAU,CAC9B,EAGK,IAA0B,EAAY,YAA8D;EACxG,IAAM,IAAM,MAAM,EAAiE;GACjF,GAAG,GAAS;GACZ,OAAO;GACP,eAAe;GACf,gBAAgB;GACjB,CAAC;AACF,IAAW,EAAI,QAAQ,kCAAkC;EACzD,IAAM,KAAY,EAAI,MAAM,2BAA2B,EAAE,EAAE,QAAQ,MAA+B,EAAQ,GAAG,GAAI,EAC3G,IAAS,EAAS,MAAM,MAAM,EAAE,UAAU,IAAI,EAAS,MAAM,MAAM,EAAE,SAAS,IAAI,EAAS,MAAM;AACvG,SAAO;GAAE,IAAI,GAAQ,MAAM;GAAM,UAAU,GAAQ,YAAY;GAAkB;IAChF,CAAC,EAAQ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I,OAAU,MAAM,iDAAiD;EAC1E,IAAM,IACJ,EAAM,eAAe,MAAM,MAAM,EAAE,aAAa,EAAE,SAAS,IAC3D,EAAM,eAAe,MAAM,MAAM,EAAE,SAAS,IAC5C,EAAM,eAAe;AACvB,MAAI,CAAC,EACH,OAAU,MAAM,6EAA6E;EAE/F,IAAM,IAAM,MAAM,EAAyD;GACzE,GAAG,GAAS;GACZ,OAAO;GACP,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"}
|
|
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,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,EAAO,IAAI,WAAW,EAAS;;AAsBrE,SAAgB,IAAqC;CACnD,IAAM,EAAE,qBAAkB,iBAAc,GAAgB,EAClD,CAAC,GAAO,KAAY,EAAsB;EAAE,GAAG;EAAa,SAAS;EAAM,CAAC,EAG5E,IAAU,SACP;EACL,SAAS;EACT,GAAI,IAAmB,EAAE,SAAS,GAAkB,GAAG,EAAE;EACzD,GAAI,IAAY,EAAE,cAAW,GAAG,EAAE;EACnC,GACD,CAAC,GAAkB,EAAU,CAC9B,EAGK,IAA0B,EAAY,YAA8D;EACxG,IAAM,IAAM,MAAM,EAAiE;GACjF,GAAG,GAAS;GACZ,OAAO;GACP,eAAe;GACf,gBAAgB;GACjB,CAAC;AACF,IAAW,EAAI,QAAQ,kCAAkC;EACzD,IAAM,KAAY,EAAI,MAAM,2BA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Auctions($context: ContextInput!, $limit: Int) {
|
|
103
|
+
healthyBowlSharedMarketAuctions(context: $context, limit: $limit) {
|
|
104
|
+
id
|
|
105
|
+
productName
|
|
106
|
+
unit
|
|
107
|
+
seller
|
|
108
|
+
endTime
|
|
109
|
+
startingPrice
|
|
110
|
+
bidIncrement
|
|
111
|
+
currentBid
|
|
112
|
+
bidCount
|
|
113
|
+
status
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
`, m = r`
|
|
117
|
+
mutation HealthyBowlPlaceSharedBid($auctionId: ID!, $amount: Float!, $context: ContextInput!) {
|
|
118
|
+
placeHealthyBowlBid(auctionId: $auctionId, amount: $amount, context: $context) {
|
|
119
|
+
id
|
|
120
|
+
auctionId
|
|
121
|
+
bidderId
|
|
122
|
+
amount
|
|
123
|
+
createdAt
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
`;
|
|
127
|
+
function h(e) {
|
|
128
|
+
return e.bidCount > 0 ? e.currentBid + e.bidIncrement : e.startingPrice;
|
|
129
|
+
}
|
|
130
|
+
function g(r = {}) {
|
|
131
|
+
let { workspaceId: o } = e(), { data: s, loading: c, error: l, refetch: u } = a(p, {
|
|
132
|
+
variables: {
|
|
133
|
+
context: { workspaceId: o },
|
|
134
|
+
limit: r.limit ?? null
|
|
135
|
+
},
|
|
136
|
+
skip: !o,
|
|
137
|
+
fetchPolicy: "cache-and-network",
|
|
138
|
+
notifyOnNetworkStatusChange: !0
|
|
139
|
+
}), [d, { loading: f }] = i(m);
|
|
140
|
+
return {
|
|
141
|
+
auctions: n(() => s?.healthyBowlSharedMarketAuctions ?? [], [s]),
|
|
142
|
+
loading: c,
|
|
143
|
+
error: l,
|
|
144
|
+
refetch: u,
|
|
145
|
+
placeBid: t(async (e, t) => {
|
|
146
|
+
let n = null;
|
|
147
|
+
try {
|
|
148
|
+
let r = await d({ variables: {
|
|
149
|
+
auctionId: e,
|
|
150
|
+
amount: t,
|
|
151
|
+
context: { workspaceId: o }
|
|
152
|
+
} });
|
|
153
|
+
r.error && (n = r.error);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
n = e;
|
|
156
|
+
}
|
|
157
|
+
if (await u().catch(() => void 0), n) throw n;
|
|
158
|
+
}, [
|
|
159
|
+
d,
|
|
160
|
+
u,
|
|
161
|
+
o
|
|
162
|
+
]),
|
|
163
|
+
placing: f
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function _() {
|
|
102
167
|
let { workspaceId: n } = e(), r = { workspaceId: n }, [a, { loading: o }] = i(s);
|
|
103
168
|
return {
|
|
104
169
|
setListingShared: t(async (e, t) => (await a({ variables: {
|
|
@@ -110,6 +175,6 @@ function p() {
|
|
|
110
175
|
};
|
|
111
176
|
}
|
|
112
177
|
//#endregion
|
|
113
|
-
export { u as useCreateSharedMarketOrders, d as useIncomingOrders,
|
|
178
|
+
export { h as minNextBid, u as useCreateSharedMarketOrders, d as useIncomingOrders, _ as useSetListingShared, g as useSharedMarketAuctions, f as useSharedMarketListings };
|
|
114
179
|
|
|
115
180
|
//# sourceMappingURL=useSharedMarket.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSharedMarket.js","names":[],"sources":["../../../src/healthybowl/hooks/useSharedMarket.ts"],"sourcesContent":["/**\n * Shared cross-farm marketplace (roadmap #6, acceptance D-1).\n *\n * `MarketplaceProduct` is workspace-scoped, so a buyer normally only ever sees their own farm's\n * listings. A farm OPTS IN per listing (`setHealthyBowlListingShared`) and the shared read then\n * returns listings from EVERY farm that has opted in — a narrowed projection\n * (`SharedMarketListing`) that carries the selling farm's identity, which is the entire point of a\n * cross-farm view.\n *\n * The offline codegen doesn't type these operations (they post-date the checked-in SDL), so —\n * mirroring the raw-gql pattern used for Auctions (`useAuctions`) and Irrigation (`useIrrigation`)\n * — they are hand-written `gql` documents executed directly against the live gateway. Every op\n * carries the workspace `context`.\n * @module healthybowl\n */\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n/** A listing some farm has published to the shared cross-farm market. */\nexport interface SharedMarketListing {\n id: string;\n name: string;\n category: string;\n price: number;\n unit: string;\n stock: number;\n organicCertified: boolean;\n image?: string | null;\n description: string;\n /** The selling farm — what makes a cross-farm view legible. */\n seller?: string | null;\n sellerRating?: number | null;\n location?: string | null;\n rating: number;\n}\n\n/** Server-side filters for the shared-market read. */\nexport interface SharedMarketFilters {\n /** Exact category match; pass null/undefined (or 'All') for every category. */\n category?: string | null;\n /** Free-text match on name / description / seller. */\n search?: string | null;\n limit?: number | null;\n}\n\nconst SHARED_LISTING_FIELDS = `\n id\n name\n category\n price\n unit\n stock\n organicCertified\n image\n description\n seller\n sellerRating\n location\n rating\n`;\n\nconst SHARED_LISTINGS_QUERY = gql`\n query HealthyBowlSharedMarketListings($context: ContextInput!, $category: String, $search: String, $limit: Int) {\n healthyBowlSharedMarketListings(context: $context, category: $category, search: $search, limit: $limit) {\n ${SHARED_LISTING_FIELDS}\n }\n }\n`;\n\nconst SET_LISTING_SHARED = gql`\n mutation SetHealthyBowlListingShared($id: ID!, $shared: Boolean!, $context: ContextInput!) {\n setHealthyBowlListingShared(id: $id, shared: $shared, context: $context) {\n id\n name\n }\n }\n`;\n\ninterface SharedListingsQueryData {\n healthyBowlSharedMarketListings: SharedMarketListing[];\n}\n\ninterface SetListingSharedData {\n setHealthyBowlListingShared: { id: string; name: string };\n}\n\n/**\n * Loads the shared cross-farm listings. Filters are passed to the server (not applied client-side)\n * so the buyer searches every farm's catalogue, not just the page they happen to have loaded.\n *\n * `sharedListingIds` is the set of listing ids currently visible in the shared market. The\n * fixed-price tab uses it to show whether one of the farm's OWN listings is published — the\n * `MarketplaceProduct` type deliberately exposes no `sharedMarket` field, so this is the only\n * server-truth available. Caveat: the shared read excludes out-of-stock listings, so a published\n * listing with zero stock reads as unpublished until it is restocked; a toggle performed in-session\n * overrides that (see `MarketplacePage`).\n */\n/**\n * BOFF-6205 — place a shared-market order, fanning out into ONE ORDER PER SELLING FARM.\n *\n * A shared-market cart can mix produce from several farms. The server resolves each line to the farm\n * that published it and creates one order per farm, so each seller gets its own order, its own total\n * and its own fulfilment — a single row could not represent that.\n */\nconst CREATE_SHARED_ORDERS = gql`\n mutation HbCreateSharedMarketOrders($input: CreateMarketplaceOrderInput!) {\n createHealthyBowlSharedMarketOrders(input: $input) {\n id\n orderNumber\n total\n status\n sellerWorkspaceId\n }\n }\n`;\n\n/** BOFF-6205 — orders placed AGAINST this farm by a buyer in another workspace. */\nconst INCOMING_ORDERS = gql`\n query HbIncomingOrders($context: ContextInput!, $status: String, $limit: Int) {\n healthyBowlIncomingOrders(context: $context, status: $status, limit: $limit) {\n id\n orderNumber\n buyerId\n total\n status\n paymentStatus\n date\n sellerWorkspaceId\n items {\n productName\n quantity\n price\n unit\n }\n }\n }\n`;\n\nexport interface SharedMarketOrder {\n id: string;\n orderNumber: string;\n total: number;\n status: string;\n sellerWorkspaceId: string | null;\n}\n\n/** Place a cross-farm order. Returns one order per selling farm. */\nexport function useCreateSharedMarketOrders() {\n const { workspaceId } = useHealthyBowl();\n const [mutate, { loading }] = useMutation(CREATE_SHARED_ORDERS);\n\n const placeSharedOrders = useCallback(\n async (input: Record<string, unknown>): Promise<SharedMarketOrder[]> => {\n const res = await mutate({ variables: { input: { ...input, context: { workspaceId } } } });\n if (res.error) throw res.error;\n return (\n (res.data as { createHealthyBowlSharedMarketOrders: SharedMarketOrder[] } | undefined)\n ?.createHealthyBowlSharedMarketOrders ?? []\n );\n },\n [mutate, workspaceId]\n );\n\n return { placeSharedOrders, placing: loading };\n}\n\n/**\n * Orders other farms have placed against this one.\n *\n * ★ Deliberately does NOT fall back to a placeholder workspace id the way the read-only hooks do.\n * `healthyBowlIncomingOrders` filters on `sellerWorkspaceId = <caller>`, so querying with a\n * placeholder returns an empty list that is indistinguishable from \"nobody has ordered from you\" —\n * the UI would state, as fact, that a farm has no orders when we simply do not know which farm it\n * is. Instead the query is skipped and `workspaceReady` is false, so the caller can say so.\n */\nexport function useIncomingOrders(options: { status?: string | null; skip?: boolean } = {}) {\n const { workspaceId } = useHealthyBowl();\n const workspaceReady = Boolean(workspaceId);\n const { data, loading, error, refetch } = useQuery(INCOMING_ORDERS, {\n variables: { context: { workspaceId }, status: options.status ?? null, limit: 50 },\n fetchPolicy: 'cache-and-network',\n skip: options.skip === true || !workspaceReady,\n });\n return {\n incomingOrders:\n (data as { healthyBowlIncomingOrders?: Record<string, unknown>[] } | undefined)?.healthyBowlIncomingOrders ?? [],\n loading,\n error,\n refetch,\n workspaceReady,\n };\n}\n\nexport function useSharedMarketListings(filters: SharedMarketFilters = {}) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const category = filters.category && filters.category !== 'All' ? filters.category : null;\n const search = filters.search?.trim() ? filters.search.trim() : null;\n const limit = filters.limit ?? null;\n\n const { data, loading, error, refetch } = useQuery<SharedListingsQueryData>(SHARED_LISTINGS_QUERY, {\n variables: { context, category, search, limit },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n const listings = useMemo(() => data?.healthyBowlSharedMarketListings ?? [], [data]);\n const sharedListingIds = useMemo(() => new Set(listings.map((l) => l.id)), [listings]);\n\n return { listings, sharedListingIds, loading, error, refetch };\n}\n\n/**\n * Publish / unpublish one of the farm's OWN listings to the shared cross-farm market.\n * Workspace-scoped server-side: a farm can only ever change the flag on its own listings.\n */\nexport function useSetListingShared() {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const [mutate, { loading }] = useMutation<SetListingSharedData>(SET_LISTING_SHARED);\n\n const setListingShared = useCallback(\n async (id: string, shared: boolean) => {\n const res = await mutate({ variables: { id, shared, context } });\n return res.data?.setHealthyBowlListingShared;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [mutate, workspaceId]\n );\n\n return { setListingShared, saving: loading };\n}\n"],"mappings":";;;;;AA+DA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;EACP,aAAa;EACb,6BAA6B;EAC9B,CAAC,EAEI,IAAW,QAAc,GAAM,mCAAmC,EAAE,EAAE,CAAC,EAAK,CAAC;AAGnF,QAAO;EAAE;EAAU,kBAFM,QAAc,IAAI,IAAI,EAAS,KAAK,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,EAAS,CAAC;EAEjD;EAAS;EAAO;EAAS;;AAOhE,SAAgB,IAAsB;CACpC,IAAM,EAAE,mBAAgB,GAAgB,EAClC,IAAU,EAAE,gBAAa,EACzB,CAAC,GAAQ,EAAE,gBAAa,EAAkC,EAAmB;AAWnF,QAAO;EAAE,kBATgB,EACvB,OAAO,GAAY,OACL,MAAM,EAAO,EAAE,WAAW;GAAE;GAAI;GAAQ;GAAS,EAAE,CAAC,EACrD,MAAM,6BAGnB,CAAC,GAAQ,EAAY,CACtB;EAE0B,QAAQ;EAAS"}
|
|
1
|
+
{"version":3,"file":"useSharedMarket.js","names":[],"sources":["../../../src/healthybowl/hooks/useSharedMarket.ts"],"sourcesContent":["/**\n * Shared cross-farm marketplace (roadmap #6, acceptance D-1).\n *\n * `MarketplaceProduct` is workspace-scoped, so a buyer normally only ever sees their own farm's\n * listings. A farm OPTS IN per listing (`setHealthyBowlListingShared`) and the shared read then\n * returns listings from EVERY farm that has opted in — a narrowed projection\n * (`SharedMarketListing`) that carries the selling farm's identity, which is the entire point of a\n * cross-farm view.\n *\n * The offline codegen doesn't type these operations (they post-date the checked-in SDL), so —\n * mirroring the raw-gql pattern used for Auctions (`useAuctions`) and Irrigation (`useIrrigation`)\n * — they are hand-written `gql` documents executed directly against the live gateway. Every op\n * carries the workspace `context`.\n * @module healthybowl\n */\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n/** A listing some farm has published to the shared cross-farm market. */\nexport interface SharedMarketListing {\n id: string;\n name: string;\n category: string;\n price: number;\n unit: string;\n stock: number;\n organicCertified: boolean;\n image?: string | null;\n description: string;\n /** The selling farm — what makes a cross-farm view legible. */\n seller?: string | null;\n sellerRating?: number | null;\n location?: string | null;\n rating: number;\n}\n\n/** Server-side filters for the shared-market read. */\nexport interface SharedMarketFilters {\n /** Exact category match; pass null/undefined (or 'All') for every category. */\n category?: string | null;\n /** Free-text match on name / description / seller. */\n search?: string | null;\n limit?: number | null;\n}\n\nconst SHARED_LISTING_FIELDS = `\n id\n name\n category\n price\n unit\n stock\n organicCertified\n image\n description\n seller\n sellerRating\n location\n rating\n`;\n\nconst SHARED_LISTINGS_QUERY = gql`\n query HealthyBowlSharedMarketListings($context: ContextInput!, $category: String, $search: String, $limit: Int) {\n healthyBowlSharedMarketListings(context: $context, category: $category, search: $search, limit: $limit) {\n ${SHARED_LISTING_FIELDS}\n }\n }\n`;\n\nconst SET_LISTING_SHARED = gql`\n mutation SetHealthyBowlListingShared($id: ID!, $shared: Boolean!, $context: ContextInput!) {\n setHealthyBowlListingShared(id: $id, shared: $shared, context: $context) {\n id\n name\n }\n }\n`;\n\ninterface SharedListingsQueryData {\n healthyBowlSharedMarketListings: SharedMarketListing[];\n}\n\ninterface SetListingSharedData {\n setHealthyBowlListingShared: { id: string; name: string };\n}\n\n/**\n * Loads the shared cross-farm listings. Filters are passed to the server (not applied client-side)\n * so the buyer searches every farm's catalogue, not just the page they happen to have loaded.\n *\n * `sharedListingIds` is the set of listing ids currently visible in the shared market. The\n * fixed-price tab uses it to show whether one of the farm's OWN listings is published — the\n * `MarketplaceProduct` type deliberately exposes no `sharedMarket` field, so this is the only\n * server-truth available. Caveat: the shared read excludes out-of-stock listings, so a published\n * listing with zero stock reads as unpublished until it is restocked; a toggle performed in-session\n * overrides that (see `MarketplacePage`).\n */\n/**\n * BOFF-6205 — place a shared-market order, fanning out into ONE ORDER PER SELLING FARM.\n *\n * A shared-market cart can mix produce from several farms. The server resolves each line to the farm\n * that published it and creates one order per farm, so each seller gets its own order, its own total\n * and its own fulfilment — a single row could not represent that.\n */\nconst CREATE_SHARED_ORDERS = gql`\n mutation HbCreateSharedMarketOrders($input: CreateMarketplaceOrderInput!) {\n createHealthyBowlSharedMarketOrders(input: $input) {\n id\n orderNumber\n total\n status\n sellerWorkspaceId\n }\n }\n`;\n\n/** BOFF-6205 — orders placed AGAINST this farm by a buyer in another workspace. */\nconst INCOMING_ORDERS = gql`\n query HbIncomingOrders($context: ContextInput!, $status: String, $limit: Int) {\n healthyBowlIncomingOrders(context: $context, status: $status, limit: $limit) {\n id\n orderNumber\n buyerId\n total\n status\n paymentStatus\n date\n sellerWorkspaceId\n items {\n productName\n quantity\n price\n unit\n }\n }\n }\n`;\n\nexport interface SharedMarketOrder {\n id: string;\n orderNumber: string;\n total: number;\n status: string;\n sellerWorkspaceId: string | null;\n}\n\n/** Place a cross-farm order. Returns one order per selling farm. */\nexport function useCreateSharedMarketOrders() {\n const { workspaceId } = useHealthyBowl();\n const [mutate, { loading }] = useMutation(CREATE_SHARED_ORDERS);\n\n const placeSharedOrders = useCallback(\n async (input: Record<string, unknown>): Promise<SharedMarketOrder[]> => {\n const res = await mutate({ variables: { input: { ...input, context: { workspaceId } } } });\n if (res.error) throw res.error;\n return (\n (res.data as { createHealthyBowlSharedMarketOrders: SharedMarketOrder[] } | undefined)\n ?.createHealthyBowlSharedMarketOrders ?? []\n );\n },\n [mutate, workspaceId]\n );\n\n return { placeSharedOrders, placing: loading };\n}\n\n/**\n * Orders other farms have placed against this one.\n *\n * ★ Deliberately does NOT fall back to a placeholder workspace id the way the read-only hooks do.\n * `healthyBowlIncomingOrders` filters on `sellerWorkspaceId = <caller>`, so querying with a\n * placeholder returns an empty list that is indistinguishable from \"nobody has ordered from you\" —\n * the UI would state, as fact, that a farm has no orders when we simply do not know which farm it\n * is. Instead the query is skipped and `workspaceReady` is false, so the caller can say so.\n */\nexport function useIncomingOrders(options: { status?: string | null; skip?: boolean } = {}) {\n const { workspaceId } = useHealthyBowl();\n const workspaceReady = Boolean(workspaceId);\n const { data, loading, error, refetch } = useQuery(INCOMING_ORDERS, {\n variables: { context: { workspaceId }, status: options.status ?? null, limit: 50 },\n fetchPolicy: 'cache-and-network',\n skip: options.skip === true || !workspaceReady,\n });\n return {\n incomingOrders:\n (data as { healthyBowlIncomingOrders?: Record<string, unknown>[] } | undefined)?.healthyBowlIncomingOrders ?? [],\n loading,\n error,\n refetch,\n workspaceReady,\n };\n}\n\nexport function useSharedMarketListings(filters: SharedMarketFilters = {}) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const category = filters.category && filters.category !== 'All' ? filters.category : null;\n const search = filters.search?.trim() ? filters.search.trim() : null;\n const limit = filters.limit ?? null;\n\n const { data, loading, error, refetch } = useQuery<SharedListingsQueryData>(SHARED_LISTINGS_QUERY, {\n variables: { context, category, search, limit },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n const listings = useMemo(() => data?.healthyBowlSharedMarketListings ?? [], [data]);\n const sharedListingIds = useMemo(() => new Set(listings.map((l) => l.id)), [listings]);\n\n return { listings, sharedListingIds, loading, error, refetch };\n}\n\n/**\n * A live auction another farm has published to the shared cross-farm market (BOFF-6206).\n *\n * A narrow projection: it carries what a cross-farm bidder needs — the product, the selling farm, the\n * close time and the CURRENT high bid. It never exposes the reserve price or rival bidder identities.\n */\nexport interface SharedMarketAuction {\n id: string;\n productName: string;\n unit: string;\n /** The selling farm — what makes a cross-farm view legible. */\n seller?: string | null;\n /** Auction close time as an ISO-8601 string. */\n endTime: string;\n startingPrice: number;\n bidIncrement: number;\n /** The current high bid, or startingPrice when nobody has bid yet. Never the reserve. */\n currentBid: number;\n bidCount: number;\n status: string;\n}\n\nconst SHARED_AUCTIONS_QUERY = gql`\n query HealthyBowlSharedMarketAuctions($context: ContextInput!, $limit: Int) {\n healthyBowlSharedMarketAuctions(context: $context, limit: $limit) {\n id\n productName\n unit\n seller\n endTime\n startingPrice\n bidIncrement\n currentBid\n bidCount\n status\n }\n }\n`;\n\nconst PLACE_SHARED_BID = gql`\n mutation HealthyBowlPlaceSharedBid($auctionId: ID!, $amount: Float!, $context: ContextInput!) {\n placeHealthyBowlBid(auctionId: $auctionId, amount: $amount, context: $context) {\n id\n auctionId\n bidderId\n amount\n createdAt\n }\n }\n`;\n\ninterface SharedAuctionsQueryData {\n healthyBowlSharedMarketAuctions: SharedMarketAuction[];\n}\n\n/** The minimum acceptable next bid: startingPrice with no bids, else the current high + increment. */\nexport function minNextBid(\n auction: Pick<SharedMarketAuction, 'currentBid' | 'bidIncrement' | 'bidCount' | 'startingPrice'>\n): number {\n return auction.bidCount > 0 ? auction.currentBid + auction.bidIncrement : auction.startingPrice;\n}\n\n/**\n * Live auctions on shared listings from EVERY farm (BOFF-6206), plus cross-farm bid placement.\n *\n * The read is cross-workspace by design (`healthyBowlSharedMarketAuctions` runs unscoped server-side).\n * `placeBid` reuses the ordinary `placeHealthyBowlBid` mutation carrying the caller's own workspace\n * `context`; the server pins the seller's workspace, so a Farm B bid becomes the new high bid inside\n * Farm A's own auction. On success the shared list is refetched so the Current Bid updates in place.\n */\nexport function useSharedMarketAuctions(options: { limit?: number | null } = {}) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n\n const { data, loading, error, refetch } = useQuery<SharedAuctionsQueryData>(SHARED_AUCTIONS_QUERY, {\n variables: { context, limit: options.limit ?? null },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n const [placeBidMutation, { loading: placing }] = useMutation(PLACE_SHARED_BID);\n\n const auctions = useMemo(() => data?.healthyBowlSharedMarketAuctions ?? [], [data]);\n\n const placeBid = useCallback(\n async (auctionId: string, amount: number) => {\n // This Apollo Client version's mutate resolves to a MutateResult whose GraphQL/network failure\n // is `error` (singular ApolloError) — not `errors`. Capture it so the caller's toast reports the\n // real rejection (e.g. \"Bid too low\"). Mirrors the shipped useCreateSharedMarketOrders.\n let bidError: unknown = null;\n try {\n // Build the context inline from workspaceId (its only ingredient) so the callback's deps are\n // honest and no eslint-disable is needed — the outer `context` object is a new ref each render.\n const res = await placeBidMutation({ variables: { auctionId, amount, context: { workspaceId } } });\n if (res.error) bidError = res.error;\n } catch (err) {\n bidError = err;\n }\n // Refresh either way — a rejection usually means a rival just raised the high bid, so the buyer\n // must see the new current bid, not fly blind. But this refresh is BEST-EFFORT: a refetch failure\n // must never turn a bid that actually landed into an apparent failure (nor swallow a real reject).\n await refetch().catch(() => undefined);\n if (bidError) throw bidError;\n },\n [placeBidMutation, refetch, workspaceId]\n );\n\n return { auctions, loading, error, refetch, placeBid, placing };\n}\n\n/**\n * Publish / unpublish one of the farm's OWN listings to the shared cross-farm market.\n * Workspace-scoped server-side: a farm can only ever change the flag on its own listings.\n */\nexport function useSetListingShared() {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const [mutate, { loading }] = useMutation<SetListingSharedData>(SET_LISTING_SHARED);\n\n const setListingShared = useCallback(\n async (id: string, shared: boolean) => {\n const res = await mutate({ variables: { id, shared, context } });\n return res.data?.setHealthyBowlListingShared;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [mutate, workspaceId]\n );\n\n return { setListingShared, saving: loading };\n}\n"],"mappings":";;;;;AA+DA,IAAM,IAAwB,CAAG;;;QAhBH,qJAmBA;;;GAKxB,IAAqB,CAAG;;;;;;;GAmCxB,IAAuB,CAAG;;;;;;;;;;GAa1B,IAAkB,CAAG;;;;;;;;;;;;;;;;;;;;AA8B3B,SAAgB,IAA8B;CAC5C,IAAM,EAAE,mBAAgB,GAAgB,EAClC,CAAC,GAAQ,EAAE,gBAAa,EAAY,EAAqB;AAc/D,QAAO;EAAE,mBAZiB,EACxB,OAAO,MAAiE;GACtE,IAAM,IAAM,MAAM,EAAO,EAAE,WAAW,EAAE,OAAO;IAAE,GAAG;IAAO,SAAS,EAAE,gBAAa;IAAE,EAAE,EAAE,CAAC;AAC1F,OAAI,EAAI,MAAO,OAAM,EAAI;AACzB,UACG,E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