@burdenoff/microfe-healthybowl 2026.812.2 → 2026.812.4

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.
@@ -26,6 +26,7 @@ var i = n`
26
26
  conceptionRatePct
27
27
  servicesPerConception
28
28
  pregnancyLossPct
29
+ pregnancyLossUnavailableReason
29
30
  meanCalvingIntervalDays
30
31
  medianCalvingIntervalDays
31
32
  damsWithInterval
@@ -1 +1 @@
1
- {"version":3,"file":"useHealthyBowlFertility.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlFertility.ts"],"sourcesContent":["/**\n * Fertility analytics — data hook (BOFF-6008).\n *\n * The fourth livestock analytics slice. Growth says how fast animals gain, feed says what that gain\n * cost, herd statistics says what the herd is made of — and this says whether it is actually\n * breeding. It shares the window and granularity contract with all three, so every livestock chart\n * describes the same period.\n *\n * The backend shipped on 2026-08-11 and had no UI at all until this hook, so nothing in the product\n * could reach it: a farmer could not see a single fertility number.\n *\n * The document is declared inline with `gql` for the same reason as its three siblings — codegen\n * validates against the committed `graphql/wspace.graphql` snapshot, which does not carry this\n * query. Types mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/livestock-depth.gql`.\n *\n * ⚠️ Two payload contracts the UI must not flatten:\n * - `calvingIntervalUnavailableReason` non-null means the interval is WRONG, not merely missing.\n * An undated delivery merges two births into one gap and overstates it. Render the reason, never\n * a number — `calvingIntervalDisplay` in `utils/fertility` enforces it.\n * - A null rate means unmeasured; `0` means measured and zero. Four services and nothing in calf\n * is `0`, and it is the most urgent thing this card can say. Never collapse the two.\n *\n * ★ Unlike its three siblings this hook does NOT fall back to a placeholder workspace id. Querying\n * a workspace that is not the user's returns an empty result, which this card would render as\n * \"No breeding records yet\" — a confident false statement about someone's farm. The query is\n * skipped until the workspace is known and `workspaceReady` says so, matching the fix made to\n * `useSharedMarket` for the same reason.\n */\n\nimport { useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport type { GrowthGranularity } from './useHealthyBowlLivestockGrowth';\nimport type { DueSoonRow, FertilityBucket } from '../utils/fertility';\n\nexport type { DueSoonRow, FertilityBucket };\n\nexport interface LivestockFertility {\n /** True when the backend hit its row cap — every figure below covers only part of the herd. */\n truncated: boolean;\n periodLabel: string;\n granularity: GrowthGranularity;\n\n services: number;\n conceived: number;\n /** Null = nothing was served. `0` = served and nothing conceived. Never conflate them. */\n conceptionRatePct: number | null;\n servicesPerConception: number | null;\n /** Share of CONFIRMED pregnancies that later failed — not of all services. */\n pregnancyLossPct: number | null;\n\n meanCalvingIntervalDays: number | null;\n medianCalvingIntervalDays: number | null;\n damsWithInterval: number;\n /** Non-null means the interval could not be computed honestly, and says why. */\n calvingIntervalUnavailableReason: string | null;\n\n deliveries: number;\n deliveriesWithCounts: number;\n meanOffspringBorn: number | null;\n meanOffspringLive: number | null;\n /** Null where live counts were never recorded — an unrecorded count is not a total loss. */\n perinatalMortalityPct: number | null;\n\n damsWithFirstCalving: number;\n meanAgeAtFirstCalvingDays: number | null;\n medianAgeAtFirstCalvingDays: number | null;\n\n dueSoon: DueSoonRow[];\n trend: FertilityBucket[];\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\nconst GET_FERTILITY = gql`\n query HealthyBowlLivestockFertility(\n $context: ContextInput!\n $groupId: ID\n $from: String\n $to: String\n $granularity: HealthyBowlGrowthGranularity\n ) {\n healthyBowlLivestockFertility(\n context: $context\n groupId: $groupId\n from: $from\n to: $to\n granularity: $granularity\n ) {\n truncated\n periodLabel\n granularity\n services\n conceived\n conceptionRatePct\n servicesPerConception\n pregnancyLossPct\n meanCalvingIntervalDays\n medianCalvingIntervalDays\n damsWithInterval\n calvingIntervalUnavailableReason\n deliveries\n deliveriesWithCounts\n meanOffspringBorn\n meanOffspringLive\n perinatalMortalityPct\n damsWithFirstCalving\n meanAgeAtFirstCalvingDays\n medianAgeAtFirstCalvingDays\n dueSoon {\n animalId\n expectedDeliveryDate\n daysUntilDue\n }\n trend {\n bucket\n services\n conceived\n conceptionRatePct\n deliveries\n }\n }\n }\n`;\n\nexport interface UseFertilityOptions {\n enabled?: boolean;\n groupId?: string | null;\n from?: string | null;\n to?: string | null;\n granularity?: GrowthGranularity;\n}\n\nexport function useHealthyBowlFertility(options: UseFertilityOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n // No placeholder id — see the module docstring. An empty result from someone else's workspace\n // would be rendered as a statement about this farm.\n const workspaceReady = Boolean(workspaceId);\n const ctx = useMemo<HbContext>(() => ({ workspaceId: workspaceId || '' }), [workspaceId]);\n\n const { data, loading, error, refetch } = useQuery<\n { healthyBowlLivestockFertility: LivestockFertility },\n {\n context: HbContext;\n groupId: string | null;\n from: string | null;\n to: string | null;\n granularity: GrowthGranularity;\n }\n >(GET_FERTILITY, {\n variables: {\n context: ctx,\n groupId: options.groupId ?? null,\n from: options.from ?? null,\n to: options.to ?? null,\n granularity: options.granularity ?? 'MONTH',\n },\n fetchPolicy: 'cache-and-network',\n skip: options.enabled === false || !workspaceReady,\n });\n\n const fertility = data?.healthyBowlLivestockFertility ?? null;\n\n return {\n fertility,\n truncated: fertility?.truncated ?? false,\n dueSoon: fertility?.dueSoon ?? [],\n trend: fertility?.trend ?? [],\n /** False until the workspace is known — the caller must not claim \"no records\" before then. */\n workspaceReady,\n loading,\n error,\n refetch,\n };\n}\n"],"mappings":";;;;;AA6EA,IAAM,IAAgB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DzB,SAAgB,EAAwB,IAA+B,EAAE,EAAE;CACzE,IAAM,EAAE,mBAAgB,GAAgB,EAGlC,IAAiB,EAAQ,GAGzB,EAAE,SAAM,YAAS,UAAO,eAAY,EASxC,GAAe;EACf,WAAW;GACT,SAbQ,SAA0B,EAAE,aAAa,KAAe,IAAI,GAAG,CAAC,EAAY,CAAC;GAcrF,SAAS,EAAQ,WAAW;GAC5B,MAAM,EAAQ,QAAQ;GACtB,IAAI,EAAQ,MAAM;GAClB,aAAa,EAAQ,eAAe;GACrC;EACD,aAAa;EACb,MAAM,EAAQ,YAAY,MAAS,CAAC;EACrC,CAAC,EAEI,IAAY,GAAM,iCAAiC;AAEzD,QAAO;EACL;EACA,WAAW,GAAW,aAAa;EACnC,SAAS,GAAW,WAAW,EAAE;EACjC,OAAO,GAAW,SAAS,EAAE;EAE7B;EACA;EACA;EACA;EACD"}
1
+ {"version":3,"file":"useHealthyBowlFertility.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlFertility.ts"],"sourcesContent":["/**\n * Fertility analytics — data hook (BOFF-6008).\n *\n * The fourth livestock analytics slice. Growth says how fast animals gain, feed says what that gain\n * cost, herd statistics says what the herd is made of — and this says whether it is actually\n * breeding. It shares the window and granularity contract with all three, so every livestock chart\n * describes the same period.\n *\n * The backend shipped on 2026-08-11 and had no UI at all until this hook, so nothing in the product\n * could reach it: a farmer could not see a single fertility number.\n *\n * The document is declared inline with `gql` for the same reason as its three siblings — codegen\n * validates against the committed `graphql/wspace.graphql` snapshot, which does not carry this\n * query. Types mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/livestock-depth.gql`.\n *\n * ⚠️ Two payload contracts the UI must not flatten:\n * - `calvingIntervalUnavailableReason` non-null means the interval is WRONG, not merely missing.\n * An undated delivery merges two births into one gap and overstates it. Render the reason, never\n * a number — `calvingIntervalDisplay` in `utils/fertility` enforces it.\n * - A null rate means unmeasured; `0` means measured and zero. Four services and nothing in calf\n * is `0`, and it is the most urgent thing this card can say. Never collapse the two.\n *\n * ★ Unlike its three siblings this hook does NOT fall back to a placeholder workspace id. Querying\n * a workspace that is not the user's returns an empty result, which this card would render as\n * \"No breeding records yet\" — a confident false statement about someone's farm. The query is\n * skipped until the workspace is known and `workspaceReady` says so, matching the fix made to\n * `useSharedMarket` for the same reason.\n */\n\nimport { useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport type { GrowthGranularity } from './useHealthyBowlLivestockGrowth';\nimport type { DueSoonRow, FertilityBucket } from '../utils/fertility';\n\nexport type { DueSoonRow, FertilityBucket };\n\nexport interface LivestockFertility {\n /** True when the backend hit its row cap — every figure below covers only part of the herd. */\n truncated: boolean;\n periodLabel: string;\n granularity: GrowthGranularity;\n\n services: number;\n conceived: number;\n /** Null = nothing was served. `0` = served and nothing conceived. Never conflate them. */\n conceptionRatePct: number | null;\n servicesPerConception: number | null;\n /** Share of CONFIRMED pregnancies that later failed — not of all services. */\n pregnancyLossPct: number | null;\n /** Non-null means loss could not be computed honestly, and says why. Always set today. */\n pregnancyLossUnavailableReason: string | null;\n\n meanCalvingIntervalDays: number | null;\n medianCalvingIntervalDays: number | null;\n damsWithInterval: number;\n /** Non-null means the interval could not be computed honestly, and says why. */\n calvingIntervalUnavailableReason: string | null;\n\n deliveries: number;\n deliveriesWithCounts: number;\n meanOffspringBorn: number | null;\n meanOffspringLive: number | null;\n /** Null where live counts were never recorded — an unrecorded count is not a total loss. */\n perinatalMortalityPct: number | null;\n\n damsWithFirstCalving: number;\n meanAgeAtFirstCalvingDays: number | null;\n medianAgeAtFirstCalvingDays: number | null;\n\n dueSoon: DueSoonRow[];\n trend: FertilityBucket[];\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\nconst GET_FERTILITY = gql`\n query HealthyBowlLivestockFertility(\n $context: ContextInput!\n $groupId: ID\n $from: String\n $to: String\n $granularity: HealthyBowlGrowthGranularity\n ) {\n healthyBowlLivestockFertility(\n context: $context\n groupId: $groupId\n from: $from\n to: $to\n granularity: $granularity\n ) {\n truncated\n periodLabel\n granularity\n services\n conceived\n conceptionRatePct\n servicesPerConception\n pregnancyLossPct\n pregnancyLossUnavailableReason\n meanCalvingIntervalDays\n medianCalvingIntervalDays\n damsWithInterval\n calvingIntervalUnavailableReason\n deliveries\n deliveriesWithCounts\n meanOffspringBorn\n meanOffspringLive\n perinatalMortalityPct\n damsWithFirstCalving\n meanAgeAtFirstCalvingDays\n medianAgeAtFirstCalvingDays\n dueSoon {\n animalId\n expectedDeliveryDate\n daysUntilDue\n }\n trend {\n bucket\n services\n conceived\n conceptionRatePct\n deliveries\n }\n }\n }\n`;\n\nexport interface UseFertilityOptions {\n enabled?: boolean;\n groupId?: string | null;\n from?: string | null;\n to?: string | null;\n granularity?: GrowthGranularity;\n}\n\nexport function useHealthyBowlFertility(options: UseFertilityOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n // No placeholder id — see the module docstring. An empty result from someone else's workspace\n // would be rendered as a statement about this farm.\n const workspaceReady = Boolean(workspaceId);\n const ctx = useMemo<HbContext>(() => ({ workspaceId: workspaceId || '' }), [workspaceId]);\n\n const { data, loading, error, refetch } = useQuery<\n { healthyBowlLivestockFertility: LivestockFertility },\n {\n context: HbContext;\n groupId: string | null;\n from: string | null;\n to: string | null;\n granularity: GrowthGranularity;\n }\n >(GET_FERTILITY, {\n variables: {\n context: ctx,\n groupId: options.groupId ?? null,\n from: options.from ?? null,\n to: options.to ?? null,\n granularity: options.granularity ?? 'MONTH',\n },\n fetchPolicy: 'cache-and-network',\n skip: options.enabled === false || !workspaceReady,\n });\n\n const fertility = data?.healthyBowlLivestockFertility ?? null;\n\n return {\n fertility,\n truncated: fertility?.truncated ?? false,\n dueSoon: fertility?.dueSoon ?? [],\n trend: fertility?.trend ?? [],\n /** False until the workspace is known — the caller must not claim \"no records\" before then. */\n workspaceReady,\n loading,\n error,\n refetch,\n };\n}\n"],"mappings":";;;;;AA+EA,IAAM,IAAgB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DzB,SAAgB,EAAwB,IAA+B,EAAE,EAAE;CACzE,IAAM,EAAE,mBAAgB,GAAgB,EAGlC,IAAiB,EAAQ,GAGzB,EAAE,SAAM,YAAS,UAAO,eAAY,EASxC,GAAe;EACf,WAAW;GACT,SAbQ,SAA0B,EAAE,aAAa,KAAe,IAAI,GAAG,CAAC,EAAY,CAAC;GAcrF,SAAS,EAAQ,WAAW;GAC5B,MAAM,EAAQ,QAAQ;GACtB,IAAI,EAAQ,MAAM;GAClB,aAAa,EAAQ,eAAe;GACrC;EACD,aAAa;EACb,MAAM,EAAQ,YAAY,MAAS,CAAC;EACrC,CAAC,EAEI,IAAY,GAAM,iCAAiC;AAEzD,QAAO;EACL;EACA,WAAW,GAAW,aAAa;EACnC,SAAS,GAAW,WAAW,EAAE;EACjC,OAAO,GAAW,SAAS,EAAE;EAE7B;EACA;EACA;EACA;EACD"}
@@ -98,7 +98,72 @@ function f(t = {}) {
98
98
  refetch: l
99
99
  };
100
100
  }
101
- function p() {
101
+ var p = r`
102
+ query HealthyBowlSharedMarketAuctions($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, p as useSetListingShared, f as useSharedMarketListings };
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,IAAM,IAAwB,CAAG;;;QAhBH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9B,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,EAAI,MACD,uCAAuC,EAAE;KAGjD,CAAC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