@burdenoff/microfe-healthybowl 2026.812.18 → 2026.812.19
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/useHealthyBowlFertility.js +2 -0
- package/dist/healthybowl/hooks/useHealthyBowlFertility.js.map +1 -1
- package/dist/healthybowl/pages/livestock/FertilityCard.js +8 -8
- package/dist/healthybowl/pages/livestock/FertilityCard.js.map +1 -1
- package/dist/healthybowl/utils/fertility.js +6 -2
- package/dist/healthybowl/utils/fertility.js.map +1 -1
- package/package.json +1 -1
|
@@ -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 /** 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 /** Deliveries that recorded how many were born — the denominator for `meanOffspringBorn`. */\n deliveriesWithCounts: number;\n meanOffspringBorn: number | null;\n /**\n * Deliveries that recorded how many were born ALIVE — the denominator for `meanOffspringLive`.\n *\n * ★ When this is smaller than `deliveriesWithCounts` the two averages are over different sets of\n * deliveries; render the live one against `meanOffspringBornWhereLiveKnown`, never beside\n * `meanOffspringBorn` as though they were a pair (BOFF-6281).\n */\n deliveriesWithLiveCounts: number;\n /** Null where live counts were never recorded — an unrecorded count is not a total loss. */\n meanOffspringLive: number | null;\n /** Mean born over the same subset as `meanOffspringLive`, which it is always <= of. */\n meanOffspringBornWhereLiveKnown: 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 deliveriesWithLiveCounts\n meanOffspringLive\n meanOffspringBornWhereLiveKnown\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":";;;;;AA2FA,IAAM,IAAgB,CAAG
|
|
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 /** Deliveries that recorded how many were born — the denominator for `meanOffspringBorn`. */\n deliveriesWithCounts: number;\n meanOffspringBorn: number | null;\n /**\n * Deliveries that recorded how many were born ALIVE — the denominator for `meanOffspringLive`.\n *\n * ★ When this is smaller than `deliveriesWithCounts` the two averages are over different sets of\n * deliveries; render the live one against `meanOffspringBornWhereLiveKnown`, never beside\n * `meanOffspringBorn` as though they were a pair (BOFF-6281).\n */\n deliveriesWithLiveCounts: number;\n /** Null where live counts were never recorded — an unrecorded count is not a total loss. */\n meanOffspringLive: number | null;\n /** Mean born over the same subset as `meanOffspringLive`, which it is always <= of. */\n meanOffspringBornWhereLiveKnown: 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 deliveriesWithLiveCounts\n meanOffspringLive\n meanOffspringBornWhereLiveKnown\n perinatalMortalityPct\n damsWithFirstCalving\n meanAgeAtFirstCalvingDays\n medianAgeAtFirstCalvingDays\n dueSoon {\n animalId\n tagNumber\n name\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":";;;;;AA2FA,IAAM,IAAgB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEzB,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"}
|
|
@@ -12,7 +12,7 @@ import { YAxis as u } from "../../../node_modules/recharts/es6/cartesian/YAxis.j
|
|
|
12
12
|
import { ComposedChart as d } from "../../../node_modules/recharts/es6/chart/ComposedChart.js";
|
|
13
13
|
import { downloadCsv as f } from "../../utils/download.js";
|
|
14
14
|
import { optionalMetric as p } from "../../utils/optionalMetric.js";
|
|
15
|
-
import { FERTILITY_CSV_HEADERS as
|
|
15
|
+
import { FERTILITY_CSV_HEADERS as m, calvingIntervalDisplay as ee, dueSoonLabel as h, dueSoonUrgency as g, dueSoonUrgencyText as te, fertilityCsvRows as _, hasFertilityData as v, litterLiveBaseDiffers as y, orderedDueSoon as b, orderedFertilityBuckets as x, pregnancyLossDisplay as S } from "../../utils/fertility.js";
|
|
16
16
|
import { useHealthyBowlFertility as C } from "../../hooks/useHealthyBowlFertility.js";
|
|
17
17
|
import { useMemo as w, useState as T } from "react";
|
|
18
18
|
import { useI18n as E } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
@@ -39,15 +39,15 @@ var A = [
|
|
|
39
39
|
damsWithInterval: V?.damsWithInterval,
|
|
40
40
|
dueSoonCount: Y.length,
|
|
41
41
|
trendCount: J.length
|
|
42
|
-
}), Z = V ?
|
|
43
|
-
V && f(`livestock-fertility-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`, [...
|
|
42
|
+
}), Z = V ? ee(V) : null, Q = V ? S(V) : null, $ = V ? y(V) : !1, ne = () => {
|
|
43
|
+
V && f(`livestock-fertility-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`, [...m], _({
|
|
44
44
|
services: V.services,
|
|
45
45
|
conceived: V.conceived,
|
|
46
46
|
conceptionRatePct: V.conceptionRatePct,
|
|
47
47
|
deliveries: V.deliveries,
|
|
48
48
|
trend: J
|
|
49
49
|
}));
|
|
50
|
-
},
|
|
50
|
+
}, re = /* @__PURE__ */ O("div", {
|
|
51
51
|
className: "flex items-center gap-1",
|
|
52
52
|
children: A.map((e) => /* @__PURE__ */ O("button", {
|
|
53
53
|
type: "button",
|
|
@@ -65,9 +65,9 @@ var A = [
|
|
|
65
65
|
to: z,
|
|
66
66
|
onFromChange: R,
|
|
67
67
|
onToChange: B,
|
|
68
|
-
onExportCsv:
|
|
68
|
+
onExportCsv: ne,
|
|
69
69
|
exportDisabled: !V || !X,
|
|
70
|
-
children:
|
|
70
|
+
children: re
|
|
71
71
|
}),
|
|
72
72
|
className: N,
|
|
73
73
|
children: q ? /* @__PURE__ */ k("div", {
|
|
@@ -365,12 +365,12 @@ var A = [
|
|
|
365
365
|
}) : /* @__PURE__ */ O("ul", {
|
|
366
366
|
className: "flex flex-col gap-1.5",
|
|
367
367
|
children: Y.map((e) => {
|
|
368
|
-
let t =
|
|
368
|
+
let t = g(e.daysUntilDue), n = te(t);
|
|
369
369
|
return /* @__PURE__ */ k("li", {
|
|
370
370
|
className: "flex flex-wrap items-baseline justify-between gap-2 text-xs",
|
|
371
371
|
children: [/* @__PURE__ */ O("span", {
|
|
372
372
|
className: "font-medium text-text-primary",
|
|
373
|
-
children: e
|
|
373
|
+
children: h(e)
|
|
374
374
|
}), /* @__PURE__ */ k("span", {
|
|
375
375
|
className: "flex items-baseline gap-2",
|
|
376
376
|
children: [/* @__PURE__ */ O("span", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FertilityCard.js","names":[],"sources":["../../../../src/healthybowl/pages/livestock/FertilityCard.tsx"],"sourcesContent":["/**\n * Fertility card (BOFF-6008).\n *\n * The fourth card beside growth, feed and herd statistics. Growth says how fast animals gain, feed\n * says what that gain cost, herd statistics says what the herd is made of — this says whether it is\n * actually breeding, which is the number a farmer culls on.\n *\n * The backend for this shipped without any UI, so until now no user of HealthyBowl could see a\n * single fertility figure.\n *\n * Deliberate choices:\n * - **The calving interval prints its reason, never a number, whenever the backend supplies one.**\n * A DELIVERED record with no delivery date merges two births into one gap and OVERSTATES the\n * interval — the direction that hides a fertility problem behind a figure reading as merely\n * mediocre. `calvingIntervalDisplay` owns that predicate and is unit-tested; the card cannot\n * reach the number when a reason exists. Same treatment as herd statistics gives mortality.\n * - **An unmeasured rate renders as an em dash; a measured zero renders as `0%`.** Four services\n * and nothing in calf is the most urgent thing this card can say, and it must not be flattened\n * into the same appearance as \"we have no breeding data\".\n * - **The empty state is decided by breeding ACTIVITY, not by a falsy rate** (`hasFertilityData`).\n * Deciding it on `conceptionRatePct` would print \"No breeding records yet\" over a barren herd.\n * - **Two y-axes on the trend, unlike the herd-turnover chart's one.** There, entries and exits\n * were both counts of animals and shared a scale honestly. Here counts and a percentage have no\n * common scale, so the rate rides its own right-hand axis, fixed to 0–100 so a good month and a\n * bad month are comparable across reloads rather than rescaled to whatever happened.\n * - **Due-soon is a worklist, not a chart.** It answers \"who do I check on this week\", so it is\n * ordered soonest-first and banded by urgency, with a passed due date called out rather than\n * folded into \"later\".\n * - A query error is surfaced as an error, never as the empty state — \"no breeding records\" is a\n * statement about the farm and must not be shown when the truth is \"we could not load\".\n */\n\nimport { useMemo, useState, type FC } from 'react';\nimport { Bar, CartesianGrid, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { ChartCard } from '../../components/ChartCard';\nimport { AnalyticsControls } from '../../components/AnalyticsControls';\nimport { formatNumber } from '../../utils/helpers';\nimport { downloadCsv } from '../../utils/download';\nimport { NOT_MEASURED, optionalMetric } from '../../utils/optionalMetric';\nimport {\n calvingIntervalDisplay,\n dueSoonUrgency,\n dueSoonUrgencyText,\n fertilityCsvRows,\n FERTILITY_CSV_HEADERS,\n hasFertilityData,\n orderedDueSoon,\n orderedFertilityBuckets,\n litterLiveBaseDiffers,\n pregnancyLossDisplay,\n type DueSoonUrgency,\n} from '../../utils/fertility';\nimport { useHealthyBowlFertility } from '../../hooks/useHealthyBowlFertility';\nimport type { GrowthGranularity } from '../../hooks/useHealthyBowlLivestockGrowth';\n\nconst GRANULARITIES: GrowthGranularity[] = ['DAY', 'WEEK', 'MONTH'];\n\n/**\n * Urgency → text colour. Only OVERDUE and IMMINENT earn a status colour; the rest stay neutral.\n *\n * Keyed on the union rather than `string` so adding a band to `DueSoonUrgency` fails the build here\n * instead of silently rendering an unstyled row.\n */\nconst URGENCY_CLASS: Record<DueSoonUrgency, string> = {\n OVERDUE: 'text-status-error-text',\n IMMINENT: 'text-status-warning-text',\n SOON: 'text-text-primary',\n LATER: 'text-text-secondary',\n};\n\ninterface FertilityCardProps {\n groupId?: string | null;\n className?: string;\n}\n\nexport const FertilityCard: FC<FertilityCardProps> = ({ groupId = null, className }) => {\n const { t } = useI18n();\n const [granularity, setGranularity] = useState<GrowthGranularity>('MONTH');\n const [from, setFrom] = useState('');\n const [to, setTo] = useState('');\n const { fertility, dueSoon, trend, truncated, workspaceReady, loading, error } = useHealthyBowlFertility({\n groupId,\n granularity,\n from: from || null,\n to: to || null,\n });\n\n const trendData = useMemo(() => orderedFertilityBuckets(trend), [trend]);\n const dueSoonRows = useMemo(() => orderedDueSoon(dueSoon), [dueSoon]);\n\n const hasData = hasFertilityData({\n services: fertility?.services,\n deliveries: fertility?.deliveries,\n damsWithInterval: fertility?.damsWithInterval,\n dueSoonCount: dueSoonRows.length,\n trendCount: trendData.length,\n });\n\n const interval = fertility ? calvingIntervalDisplay(fertility) : null;\n const loss = fertility ? pregnancyLossDisplay(fertility) : null;\n const liveBaseDiffers = fertility ? litterLiveBaseDiffers(fertility) : false;\n\n const handleExportCsv = () => {\n if (!fertility) return;\n downloadCsv(\n `livestock-fertility-${new Date().toISOString().slice(0, 10)}.csv`,\n [...FERTILITY_CSV_HEADERS],\n fertilityCsvRows({\n services: fertility.services,\n conceived: fertility.conceived,\n conceptionRatePct: fertility.conceptionRatePct,\n deliveries: fertility.deliveries,\n trend: trendData,\n })\n );\n };\n\n const granularityToggle = (\n <div className=\"flex items-center gap-1\">\n {GRANULARITIES.map((g) => (\n <button\n key={g}\n type=\"button\"\n onClick={() => setGranularity(g)}\n aria-pressed={granularity === g}\n className={`min-h-[32px] rounded-md px-2 py-1 text-xs transition-colors ${\n granularity === g\n ? 'bg-action-primary-bg text-action-primary-text'\n : 'text-text-secondary hover:bg-bg-sunken/50'\n }`}\n >\n {t(`healthybowl.livestock.fertility.granularity.${g.toLowerCase()}`, g.charAt(0) + g.slice(1).toLowerCase())}\n </button>\n ))}\n </div>\n );\n\n return (\n <ChartCard\n title={t('healthybowl.livestock.fertility.title', 'Fertility')}\n description={t(\n 'healthybowl.livestock.fertility.description',\n 'Whether the herd is actually breeding — conception, calving interval, litter size and who is due.'\n )}\n actions={\n <AnalyticsControls\n from={from}\n to={to}\n onFromChange={setFrom}\n onToChange={setTo}\n onExportCsv={handleExportCsv}\n exportDisabled={!fertility || !hasData}\n >\n {granularityToggle}\n </AnalyticsControls>\n }\n className={className}\n >\n {error ? (\n <div className=\"py-8 text-center\">\n <p className=\"text-sm text-text-primary\">\n {t('healthybowl.livestock.fertility.error.title', 'Could not load fertility analytics')}\n </p>\n <p className=\"mt-1 text-xs text-text-secondary\">{error.message}</p>\n </div>\n ) : !workspaceReady || (loading && !hasData) ? (\n <p className=\"py-8 text-center text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.loading', 'Loading fertility analytics…')}\n </p>\n ) : !hasData ? (\n <div className=\"py-8 text-center\">\n <p className=\"text-sm text-text-primary\">\n {t('healthybowl.livestock.fertility.empty.title', 'No breeding records yet')}\n </p>\n <p className=\"mt-1 text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.empty.hint',\n 'Record a mating on the Breeding page, then set its outcome — delivery date and offspring — to see conception, calving interval and litter size here.'\n )}\n </p>\n </div>\n ) : (\n <>\n {truncated && (\n <p className=\"mb-3 rounded-md bg-bg-sunken/60 px-3 py-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.truncated',\n 'This herd has more breeding records than one view can load, so every figure below covers only part of it. Narrow the date range or filter by group for an exact figure.'\n )}\n </p>\n )}\n\n {/* Headline — conception is what a farmer checks first. */}\n <dl className=\"mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4\">\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.conceptionRate', 'Conception rate')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.conceptionRatePct, { decimals: 1, unit: '%' })}\n </dd>\n <dd className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.ofServices', '{{c}} of {{s}} services', {\n c: String(fertility?.conceived ?? 0),\n s: String(fertility?.services ?? 0),\n })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.servicesPerConception', 'Services per conception')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.servicesPerConception, { decimals: 1 })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.calvingInterval', 'Mean calving interval')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {/* Never reachable when a reason exists — see calvingIntervalDisplay. */}\n {interval?.available\n ? t('healthybowl.livestock.fertility.summary.days', '{{n}} days', {\n n: formatNumber(interval.meanDays),\n })\n : NOT_MEASURED}\n </dd>\n {interval?.available && interval.medianDays !== null && (\n <dd className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.median', 'median {{n}}', {\n n: optionalMetric(interval.medianDays, { decimals: 0 }),\n })}\n </dd>\n )}\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.pregnancyLoss', 'Pregnancy loss')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {/* Unreachable while a reason exists — the raw figure is a structural 0, not a\n measurement, and printing it would read as a herd that lost nothing. */}\n {loss?.available ? optionalMetric(loss.ratePct, { decimals: 1, unit: '%' }) : NOT_MEASURED}\n </dd>\n <dd className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.ofConfirmed', 'of confirmed pregnancies')}\n </dd>\n </div>\n </dl>\n\n {/* The reason IS the value in both of these — never a blank, and never a number. */}\n {interval && !interval.available && interval.reason && (\n <p className=\"mb-4 rounded-md bg-bg-sunken/60 px-3 py-2 text-xs text-text-secondary\">{interval.reason}</p>\n )}\n {loss && !loss.available && loss.reason && (\n <p className=\"mb-4 rounded-md bg-bg-sunken/60 px-3 py-2 text-xs text-text-secondary\">{loss.reason}</p>\n )}\n\n {/* Trend — counts as bars, rate as its own axis. */}\n <div className=\"border-t border-border-subtle pt-4\">\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.trend.title', 'Services and conceptions')}\n </h4>\n {trendData.length === 0 ? (\n <p className=\"py-4 text-center text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.trend.empty',\n 'No service in this period carries a mating date, so there is nothing to plot over time.'\n )}\n </p>\n ) : (\n <ResponsiveContainer width=\"100%\" height={220}>\n <ComposedChart data={trendData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>\n <CartesianGrid strokeDasharray=\"3 3\" stroke=\"var(--color-border)\" />\n <XAxis dataKey=\"bucket\" tick={{ fontSize: 11 }} stroke=\"var(--color-muted-foreground)\" />\n <YAxis\n yAxisId=\"count\"\n allowDecimals={false}\n tick={{ fontSize: 11 }}\n stroke=\"var(--color-muted-foreground)\"\n />\n {/* Fixed 0–100 so two periods are comparable, not rescaled to whatever happened. */}\n <YAxis\n yAxisId=\"rate\"\n orientation=\"right\"\n domain={[0, 100]}\n unit=\"%\"\n tick={{ fontSize: 11 }}\n stroke=\"var(--color-muted-foreground)\"\n />\n <Tooltip\n cursor={{ fill: 'var(--color-muted)', opacity: 0.2 }}\n contentStyle={{\n backgroundColor: 'var(--color-card)',\n border: '1px solid var(--color-border)',\n borderRadius: 8,\n fontSize: 12,\n }}\n labelStyle={{ color: 'var(--color-foreground)' }}\n formatter={(value: number | string, name: string) => [\n typeof value === 'number' ? formatNumber(value) : String(value ?? NOT_MEASURED),\n name,\n ]}\n />\n <Legend wrapperStyle={{ fontSize: 11 }} />\n <Bar\n yAxisId=\"count\"\n dataKey=\"services\"\n name={t('healthybowl.livestock.fertility.trend.services', 'Services')}\n fill=\"var(--color-chart-1)\"\n radius={[4, 4, 0, 0]}\n />\n <Bar\n yAxisId=\"count\"\n dataKey=\"conceived\"\n name={t('healthybowl.livestock.fertility.trend.conceived', 'Conceived')}\n fill=\"var(--color-chart-2)\"\n radius={[4, 4, 0, 0]}\n />\n <Line\n yAxisId=\"rate\"\n type=\"monotone\"\n dataKey=\"conceptionRatePct\"\n name={t('healthybowl.livestock.fertility.trend.rate', 'Conception rate %')}\n stroke=\"var(--color-chart-3)\"\n strokeWidth={2}\n dot={false}\n connectNulls={false}\n />\n </ComposedChart>\n </ResponsiveContainer>\n )}\n </div>\n\n {/* Litter and first calving. */}\n <div className=\"mt-4 grid grid-cols-1 gap-4 border-t border-border-subtle pt-4 sm:grid-cols-2\">\n <div>\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.title', 'Litter size')}\n </h4>\n <dl className=\"grid grid-cols-2 gap-3\">\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.born', 'Mean born')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.meanOffspringBorn, { decimals: 1 })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.live', 'Mean born alive')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.meanOffspringLive, { decimals: 1 })}\n {/*\n ★ BOFF-6281. Survival is recorded independently of the born count, so this\n average can be over fewer deliveries than \"Mean born\" beside it — which is how\n the card once showed 2.0 born and 3.0 born alive. When the two groups differ,\n the live figure is shown against the born figure FOR THE SAME DELIVERIES, the\n only number it can honestly be read against.\n */}\n {liveBaseDiffers ? (\n <span className=\"ml-1 text-xs font-normal text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.liveBase', 'of {{born}} born', {\n born: optionalMetric(fertility?.meanOffspringBornWhereLiveKnown, { decimals: 1 }),\n })}\n </span>\n ) : null}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.perinatal', 'Perinatal mortality')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.perinatalMortalityPct, { decimals: 1, unit: '%' })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.deliveries', 'Deliveries')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {formatNumber(fertility?.deliveries ?? 0)}\n </dd>\n </div>\n </dl>\n {/* The denominator caveat, as animalsWithoutAge is for the age chart. */}\n <p className=\"mt-2 text-xs text-text-secondary\">\n {liveBaseDiffers\n ? t(\n 'healthybowl.livestock.fertility.litter.coverageSplit',\n '{{counted}} of {{total}} deliveries recorded how many were born, and {{live}} of those also recorded how many survived. Each average is of its own group, so they are not a pair.',\n {\n counted: String(fertility?.deliveriesWithCounts ?? 0),\n total: String(fertility?.deliveries ?? 0),\n live: String(fertility?.deliveriesWithLiveCounts ?? 0),\n }\n )\n : t(\n 'healthybowl.livestock.fertility.litter.coverage',\n '{{counted}} of {{total}} deliveries recorded how many were born — the averages are of those.',\n {\n counted: String(fertility?.deliveriesWithCounts ?? 0),\n total: String(fertility?.deliveries ?? 0),\n }\n )}\n </p>\n </div>\n\n <div>\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.title', 'Age at first calving')}\n </h4>\n <dl className=\"grid grid-cols-2 gap-3\">\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.mean', 'Mean')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {fertility?.meanAgeAtFirstCalvingDays !== null && fertility?.meanAgeAtFirstCalvingDays !== undefined\n ? t('healthybowl.livestock.fertility.summary.days', '{{n}} days', {\n n: formatNumber(fertility.meanAgeAtFirstCalvingDays),\n })\n : NOT_MEASURED}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.median', 'Median')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.medianAgeAtFirstCalvingDays, { decimals: 0 })}\n </dd>\n </div>\n <div className=\"col-span-2\">\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.dams', 'Dams with a first calving')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {formatNumber(fertility?.damsWithFirstCalving ?? 0)}\n <span className=\"ms-2 text-xs font-normal text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.intervalDams', '· {{n}} with an interval', {\n n: String(fertility?.damsWithInterval ?? 0),\n })}\n </span>\n </dd>\n </div>\n </dl>\n <p className=\"mt-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.firstCalving.coverage',\n 'Only dams whose own date of birth is recorded can contribute — an unknown birth date makes the age unknowable.'\n )}\n </p>\n </div>\n </div>\n\n {/* Due soon — a worklist, soonest first. */}\n <div className=\"mt-4 border-t border-border-subtle pt-4\">\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.due.title', 'Due soon, and overdue')}\n </h4>\n {dueSoonRows.length === 0 ? (\n <p className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.due.empty',\n 'No open pregnancy is due in the next 30 days, and none is overdue.'\n )}\n </p>\n ) : (\n <ul className=\"flex flex-col gap-1.5\">\n {dueSoonRows.map((row) => {\n const urgency = dueSoonUrgency(row.daysUntilDue);\n const label = dueSoonUrgencyText(urgency);\n return (\n <li\n key={`${row.animalId}:${row.expectedDeliveryDate}`}\n className=\"flex flex-wrap items-baseline justify-between gap-2 text-xs\"\n >\n <span className=\"font-medium text-text-primary\">{row.animalId}</span>\n <span className=\"flex items-baseline gap-2\">\n <span className=\"tabular-nums text-text-secondary\">{row.expectedDeliveryDate}</span>\n <span className={`tabular-nums ${URGENCY_CLASS[urgency]}`}>\n {t(label.key, label.defaultValue)}\n {/* BOFF-6280 — an overdue row must say BY HOW MUCH. \"Overdue\" alone reads\n the same at three days as at three weeks, and those call for very\n different action. `daysUntilDue` is negative here, so it is negated\n for display rather than shown as \"-19d\". */}\n {/* Only when the count is a real number. `dueSoonUrgency` deliberately\n bands a non-finite value as OVERDUE rather than dropping the row, so\n the day count has to tolerate one too — otherwise the defence that\n keeps the row visible renders \"(by NaNd)\" next to it. */}\n {Number.isFinite(row.daysUntilDue) && (\n <span className=\"text-text-secondary\">\n {' '}\n {urgency === 'OVERDUE'\n ? t('healthybowl.livestock.fertility.due.byDays', '(by {{n}}d)', {\n n: String(Math.abs(row.daysUntilDue)),\n })\n : t('healthybowl.livestock.fertility.due.inDays', '({{n}}d)', {\n n: String(row.daysUntilDue),\n })}\n </span>\n )}\n </span>\n </span>\n </li>\n );\n })}\n </ul>\n )}\n </div>\n </>\n )}\n </ChartCard>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwDA,IAAM,IAAqC;CAAC;CAAO;CAAQ;CAAQ,EAQ7D,IAAgD;CACpD,SAAS;CACT,UAAU;CACV,MAAM;CACN,OAAO;CACR,EAOY,KAAyC,EAAE,aAAU,MAAM,mBAAgB;CACtF,IAAM,EAAE,SAAM,GAAS,EACjB,CAAC,GAAa,KAAkB,EAA4B,QAAQ,EACpE,CAAC,GAAM,KAAW,EAAS,GAAG,EAC9B,CAAC,GAAI,KAAS,EAAS,GAAG,EAC1B,EAAE,cAAW,YAAS,UAAO,cAAW,mBAAgB,YAAS,aAAU,EAAwB;EACvG;EACA;EACA,MAAM,KAAQ;EACd,IAAI,KAAM;EACX,CAAC,EAEI,IAAY,QAAc,EAAwB,EAAM,EAAE,CAAC,EAAM,CAAC,EAClE,IAAc,QAAc,EAAe,EAAQ,EAAE,CAAC,EAAQ,CAAC,EAE/D,IAAU,EAAiB;EAC/B,UAAU,GAAW;EACrB,YAAY,GAAW;EACvB,kBAAkB,GAAW;EAC7B,cAAc,EAAY;EAC1B,YAAY,EAAU;EACvB,CAAC,EAEI,IAAW,IAAY,EAAuB,EAAU,GAA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C,OAAO,SAAS,EAAI,aAAa,IAChC,kBAAC,QAAD;UAAM,WAAU;oBAAhB,CACG,KACA,MAAY,YACT,EAAE,8CAA8C,eAAe,EAC7D,GAAG,OAAO,KAAK,IAAI,EAAI,aAAa,CAAC,EACtC,CAAC,GACF,EAAE,8CAA8C,YAAY,EAC1D,GAAG,OAAO,EAAI,aAAa,EAC5B,CAAC,CACD;YAEJ;WACF;UACJ;SA9BE,GAAG,EAAI,SAAS,GAAG,EAAI,uBA8BzB;OAEP;KACC,CAAA,CAEH;;GACL,EAAA,CAAA,GAzVH,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,KAAD;IAAG,WAAU;cACV,EAAE,+CAA+C,0BAA0B;IAC1E,CAAA,EACJ,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,8CACA,uJACD;IACC,CAAA,CACA;;EAiVE,CAAA"}
|
|
1
|
+
{"version":3,"file":"FertilityCard.js","names":[],"sources":["../../../../src/healthybowl/pages/livestock/FertilityCard.tsx"],"sourcesContent":["/**\n * Fertility card (BOFF-6008).\n *\n * The fourth card beside growth, feed and herd statistics. Growth says how fast animals gain, feed\n * says what that gain cost, herd statistics says what the herd is made of — this says whether it is\n * actually breeding, which is the number a farmer culls on.\n *\n * The backend for this shipped without any UI, so until now no user of HealthyBowl could see a\n * single fertility figure.\n *\n * Deliberate choices:\n * - **The calving interval prints its reason, never a number, whenever the backend supplies one.**\n * A DELIVERED record with no delivery date merges two births into one gap and OVERSTATES the\n * interval — the direction that hides a fertility problem behind a figure reading as merely\n * mediocre. `calvingIntervalDisplay` owns that predicate and is unit-tested; the card cannot\n * reach the number when a reason exists. Same treatment as herd statistics gives mortality.\n * - **An unmeasured rate renders as an em dash; a measured zero renders as `0%`.** Four services\n * and nothing in calf is the most urgent thing this card can say, and it must not be flattened\n * into the same appearance as \"we have no breeding data\".\n * - **The empty state is decided by breeding ACTIVITY, not by a falsy rate** (`hasFertilityData`).\n * Deciding it on `conceptionRatePct` would print \"No breeding records yet\" over a barren herd.\n * - **Two y-axes on the trend, unlike the herd-turnover chart's one.** There, entries and exits\n * were both counts of animals and shared a scale honestly. Here counts and a percentage have no\n * common scale, so the rate rides its own right-hand axis, fixed to 0–100 so a good month and a\n * bad month are comparable across reloads rather than rescaled to whatever happened.\n * - **Due-soon is a worklist, not a chart.** It answers \"who do I check on this week\", so it is\n * ordered soonest-first and banded by urgency, with a passed due date called out rather than\n * folded into \"later\".\n * - A query error is surfaced as an error, never as the empty state — \"no breeding records\" is a\n * statement about the farm and must not be shown when the truth is \"we could not load\".\n */\n\nimport { useMemo, useState, type FC } from 'react';\nimport { Bar, CartesianGrid, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { ChartCard } from '../../components/ChartCard';\nimport { AnalyticsControls } from '../../components/AnalyticsControls';\nimport { formatNumber } from '../../utils/helpers';\nimport { downloadCsv } from '../../utils/download';\nimport { NOT_MEASURED, optionalMetric } from '../../utils/optionalMetric';\nimport {\n calvingIntervalDisplay,\n dueSoonLabel,\n dueSoonUrgency,\n dueSoonUrgencyText,\n fertilityCsvRows,\n FERTILITY_CSV_HEADERS,\n hasFertilityData,\n orderedDueSoon,\n orderedFertilityBuckets,\n litterLiveBaseDiffers,\n pregnancyLossDisplay,\n type DueSoonUrgency,\n} from '../../utils/fertility';\nimport { useHealthyBowlFertility } from '../../hooks/useHealthyBowlFertility';\nimport type { GrowthGranularity } from '../../hooks/useHealthyBowlLivestockGrowth';\n\nconst GRANULARITIES: GrowthGranularity[] = ['DAY', 'WEEK', 'MONTH'];\n\n/**\n * Urgency → text colour. Only OVERDUE and IMMINENT earn a status colour; the rest stay neutral.\n *\n * Keyed on the union rather than `string` so adding a band to `DueSoonUrgency` fails the build here\n * instead of silently rendering an unstyled row.\n */\nconst URGENCY_CLASS: Record<DueSoonUrgency, string> = {\n OVERDUE: 'text-status-error-text',\n IMMINENT: 'text-status-warning-text',\n SOON: 'text-text-primary',\n LATER: 'text-text-secondary',\n};\n\ninterface FertilityCardProps {\n groupId?: string | null;\n className?: string;\n}\n\nexport const FertilityCard: FC<FertilityCardProps> = ({ groupId = null, className }) => {\n const { t } = useI18n();\n const [granularity, setGranularity] = useState<GrowthGranularity>('MONTH');\n const [from, setFrom] = useState('');\n const [to, setTo] = useState('');\n const { fertility, dueSoon, trend, truncated, workspaceReady, loading, error } = useHealthyBowlFertility({\n groupId,\n granularity,\n from: from || null,\n to: to || null,\n });\n\n const trendData = useMemo(() => orderedFertilityBuckets(trend), [trend]);\n const dueSoonRows = useMemo(() => orderedDueSoon(dueSoon), [dueSoon]);\n\n const hasData = hasFertilityData({\n services: fertility?.services,\n deliveries: fertility?.deliveries,\n damsWithInterval: fertility?.damsWithInterval,\n dueSoonCount: dueSoonRows.length,\n trendCount: trendData.length,\n });\n\n const interval = fertility ? calvingIntervalDisplay(fertility) : null;\n const loss = fertility ? pregnancyLossDisplay(fertility) : null;\n const liveBaseDiffers = fertility ? litterLiveBaseDiffers(fertility) : false;\n\n const handleExportCsv = () => {\n if (!fertility) return;\n downloadCsv(\n `livestock-fertility-${new Date().toISOString().slice(0, 10)}.csv`,\n [...FERTILITY_CSV_HEADERS],\n fertilityCsvRows({\n services: fertility.services,\n conceived: fertility.conceived,\n conceptionRatePct: fertility.conceptionRatePct,\n deliveries: fertility.deliveries,\n trend: trendData,\n })\n );\n };\n\n const granularityToggle = (\n <div className=\"flex items-center gap-1\">\n {GRANULARITIES.map((g) => (\n <button\n key={g}\n type=\"button\"\n onClick={() => setGranularity(g)}\n aria-pressed={granularity === g}\n className={`min-h-[32px] rounded-md px-2 py-1 text-xs transition-colors ${\n granularity === g\n ? 'bg-action-primary-bg text-action-primary-text'\n : 'text-text-secondary hover:bg-bg-sunken/50'\n }`}\n >\n {t(`healthybowl.livestock.fertility.granularity.${g.toLowerCase()}`, g.charAt(0) + g.slice(1).toLowerCase())}\n </button>\n ))}\n </div>\n );\n\n return (\n <ChartCard\n title={t('healthybowl.livestock.fertility.title', 'Fertility')}\n description={t(\n 'healthybowl.livestock.fertility.description',\n 'Whether the herd is actually breeding — conception, calving interval, litter size and who is due.'\n )}\n actions={\n <AnalyticsControls\n from={from}\n to={to}\n onFromChange={setFrom}\n onToChange={setTo}\n onExportCsv={handleExportCsv}\n exportDisabled={!fertility || !hasData}\n >\n {granularityToggle}\n </AnalyticsControls>\n }\n className={className}\n >\n {error ? (\n <div className=\"py-8 text-center\">\n <p className=\"text-sm text-text-primary\">\n {t('healthybowl.livestock.fertility.error.title', 'Could not load fertility analytics')}\n </p>\n <p className=\"mt-1 text-xs text-text-secondary\">{error.message}</p>\n </div>\n ) : !workspaceReady || (loading && !hasData) ? (\n <p className=\"py-8 text-center text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.loading', 'Loading fertility analytics…')}\n </p>\n ) : !hasData ? (\n <div className=\"py-8 text-center\">\n <p className=\"text-sm text-text-primary\">\n {t('healthybowl.livestock.fertility.empty.title', 'No breeding records yet')}\n </p>\n <p className=\"mt-1 text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.empty.hint',\n 'Record a mating on the Breeding page, then set its outcome — delivery date and offspring — to see conception, calving interval and litter size here.'\n )}\n </p>\n </div>\n ) : (\n <>\n {truncated && (\n <p className=\"mb-3 rounded-md bg-bg-sunken/60 px-3 py-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.truncated',\n 'This herd has more breeding records than one view can load, so every figure below covers only part of it. Narrow the date range or filter by group for an exact figure.'\n )}\n </p>\n )}\n\n {/* Headline — conception is what a farmer checks first. */}\n <dl className=\"mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4\">\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.conceptionRate', 'Conception rate')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.conceptionRatePct, { decimals: 1, unit: '%' })}\n </dd>\n <dd className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.ofServices', '{{c}} of {{s}} services', {\n c: String(fertility?.conceived ?? 0),\n s: String(fertility?.services ?? 0),\n })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.servicesPerConception', 'Services per conception')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.servicesPerConception, { decimals: 1 })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.calvingInterval', 'Mean calving interval')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {/* Never reachable when a reason exists — see calvingIntervalDisplay. */}\n {interval?.available\n ? t('healthybowl.livestock.fertility.summary.days', '{{n}} days', {\n n: formatNumber(interval.meanDays),\n })\n : NOT_MEASURED}\n </dd>\n {interval?.available && interval.medianDays !== null && (\n <dd className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.median', 'median {{n}}', {\n n: optionalMetric(interval.medianDays, { decimals: 0 }),\n })}\n </dd>\n )}\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.pregnancyLoss', 'Pregnancy loss')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {/* Unreachable while a reason exists — the raw figure is a structural 0, not a\n measurement, and printing it would read as a herd that lost nothing. */}\n {loss?.available ? optionalMetric(loss.ratePct, { decimals: 1, unit: '%' }) : NOT_MEASURED}\n </dd>\n <dd className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.summary.ofConfirmed', 'of confirmed pregnancies')}\n </dd>\n </div>\n </dl>\n\n {/* The reason IS the value in both of these — never a blank, and never a number. */}\n {interval && !interval.available && interval.reason && (\n <p className=\"mb-4 rounded-md bg-bg-sunken/60 px-3 py-2 text-xs text-text-secondary\">{interval.reason}</p>\n )}\n {loss && !loss.available && loss.reason && (\n <p className=\"mb-4 rounded-md bg-bg-sunken/60 px-3 py-2 text-xs text-text-secondary\">{loss.reason}</p>\n )}\n\n {/* Trend — counts as bars, rate as its own axis. */}\n <div className=\"border-t border-border-subtle pt-4\">\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.trend.title', 'Services and conceptions')}\n </h4>\n {trendData.length === 0 ? (\n <p className=\"py-4 text-center text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.trend.empty',\n 'No service in this period carries a mating date, so there is nothing to plot over time.'\n )}\n </p>\n ) : (\n <ResponsiveContainer width=\"100%\" height={220}>\n <ComposedChart data={trendData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>\n <CartesianGrid strokeDasharray=\"3 3\" stroke=\"var(--color-border)\" />\n <XAxis dataKey=\"bucket\" tick={{ fontSize: 11 }} stroke=\"var(--color-muted-foreground)\" />\n <YAxis\n yAxisId=\"count\"\n allowDecimals={false}\n tick={{ fontSize: 11 }}\n stroke=\"var(--color-muted-foreground)\"\n />\n {/* Fixed 0–100 so two periods are comparable, not rescaled to whatever happened. */}\n <YAxis\n yAxisId=\"rate\"\n orientation=\"right\"\n domain={[0, 100]}\n unit=\"%\"\n tick={{ fontSize: 11 }}\n stroke=\"var(--color-muted-foreground)\"\n />\n <Tooltip\n cursor={{ fill: 'var(--color-muted)', opacity: 0.2 }}\n contentStyle={{\n backgroundColor: 'var(--color-card)',\n border: '1px solid var(--color-border)',\n borderRadius: 8,\n fontSize: 12,\n }}\n labelStyle={{ color: 'var(--color-foreground)' }}\n formatter={(value: number | string, name: string) => [\n typeof value === 'number' ? formatNumber(value) : String(value ?? NOT_MEASURED),\n name,\n ]}\n />\n <Legend wrapperStyle={{ fontSize: 11 }} />\n <Bar\n yAxisId=\"count\"\n dataKey=\"services\"\n name={t('healthybowl.livestock.fertility.trend.services', 'Services')}\n fill=\"var(--color-chart-1)\"\n radius={[4, 4, 0, 0]}\n />\n <Bar\n yAxisId=\"count\"\n dataKey=\"conceived\"\n name={t('healthybowl.livestock.fertility.trend.conceived', 'Conceived')}\n fill=\"var(--color-chart-2)\"\n radius={[4, 4, 0, 0]}\n />\n <Line\n yAxisId=\"rate\"\n type=\"monotone\"\n dataKey=\"conceptionRatePct\"\n name={t('healthybowl.livestock.fertility.trend.rate', 'Conception rate %')}\n stroke=\"var(--color-chart-3)\"\n strokeWidth={2}\n dot={false}\n connectNulls={false}\n />\n </ComposedChart>\n </ResponsiveContainer>\n )}\n </div>\n\n {/* Litter and first calving. */}\n <div className=\"mt-4 grid grid-cols-1 gap-4 border-t border-border-subtle pt-4 sm:grid-cols-2\">\n <div>\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.title', 'Litter size')}\n </h4>\n <dl className=\"grid grid-cols-2 gap-3\">\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.born', 'Mean born')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.meanOffspringBorn, { decimals: 1 })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.live', 'Mean born alive')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.meanOffspringLive, { decimals: 1 })}\n {/*\n ★ BOFF-6281. Survival is recorded independently of the born count, so this\n average can be over fewer deliveries than \"Mean born\" beside it — which is how\n the card once showed 2.0 born and 3.0 born alive. When the two groups differ,\n the live figure is shown against the born figure FOR THE SAME DELIVERIES, the\n only number it can honestly be read against.\n */}\n {liveBaseDiffers ? (\n <span className=\"ml-1 text-xs font-normal text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.liveBase', 'of {{born}} born', {\n born: optionalMetric(fertility?.meanOffspringBornWhereLiveKnown, { decimals: 1 }),\n })}\n </span>\n ) : null}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.perinatal', 'Perinatal mortality')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.perinatalMortalityPct, { decimals: 1, unit: '%' })}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.litter.deliveries', 'Deliveries')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {formatNumber(fertility?.deliveries ?? 0)}\n </dd>\n </div>\n </dl>\n {/* The denominator caveat, as animalsWithoutAge is for the age chart. */}\n <p className=\"mt-2 text-xs text-text-secondary\">\n {liveBaseDiffers\n ? t(\n 'healthybowl.livestock.fertility.litter.coverageSplit',\n '{{counted}} of {{total}} deliveries recorded how many were born, and {{live}} of those also recorded how many survived. Each average is of its own group, so they are not a pair.',\n {\n counted: String(fertility?.deliveriesWithCounts ?? 0),\n total: String(fertility?.deliveries ?? 0),\n live: String(fertility?.deliveriesWithLiveCounts ?? 0),\n }\n )\n : t(\n 'healthybowl.livestock.fertility.litter.coverage',\n '{{counted}} of {{total}} deliveries recorded how many were born — the averages are of those.',\n {\n counted: String(fertility?.deliveriesWithCounts ?? 0),\n total: String(fertility?.deliveries ?? 0),\n }\n )}\n </p>\n </div>\n\n <div>\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.title', 'Age at first calving')}\n </h4>\n <dl className=\"grid grid-cols-2 gap-3\">\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.mean', 'Mean')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {fertility?.meanAgeAtFirstCalvingDays !== null && fertility?.meanAgeAtFirstCalvingDays !== undefined\n ? t('healthybowl.livestock.fertility.summary.days', '{{n}} days', {\n n: formatNumber(fertility.meanAgeAtFirstCalvingDays),\n })\n : NOT_MEASURED}\n </dd>\n </div>\n <div>\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.median', 'Median')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {optionalMetric(fertility?.medianAgeAtFirstCalvingDays, { decimals: 0 })}\n </dd>\n </div>\n <div className=\"col-span-2\">\n <dt className=\"text-xs text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.dams', 'Dams with a first calving')}\n </dt>\n <dd className=\"text-sm font-medium tabular-nums text-text-primary\">\n {formatNumber(fertility?.damsWithFirstCalving ?? 0)}\n <span className=\"ms-2 text-xs font-normal text-text-secondary\">\n {t('healthybowl.livestock.fertility.firstCalving.intervalDams', '· {{n}} with an interval', {\n n: String(fertility?.damsWithInterval ?? 0),\n })}\n </span>\n </dd>\n </div>\n </dl>\n <p className=\"mt-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.firstCalving.coverage',\n 'Only dams whose own date of birth is recorded can contribute — an unknown birth date makes the age unknowable.'\n )}\n </p>\n </div>\n </div>\n\n {/* Due soon — a worklist, soonest first. */}\n <div className=\"mt-4 border-t border-border-subtle pt-4\">\n <h4 className=\"mb-2 text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.livestock.fertility.due.title', 'Due soon, and overdue')}\n </h4>\n {dueSoonRows.length === 0 ? (\n <p className=\"text-xs text-text-secondary\">\n {t(\n 'healthybowl.livestock.fertility.due.empty',\n 'No open pregnancy is due in the next 30 days, and none is overdue.'\n )}\n </p>\n ) : (\n <ul className=\"flex flex-col gap-1.5\">\n {dueSoonRows.map((row) => {\n const urgency = dueSoonUrgency(row.daysUntilDue);\n const label = dueSoonUrgencyText(urgency);\n return (\n <li\n key={`${row.animalId}:${row.expectedDeliveryDate}`}\n className=\"flex flex-wrap items-baseline justify-between gap-2 text-xs\"\n >\n {/* BOFF-6283 — this used to render the raw UUID. The key keeps the id, since\n two animals can share a tag; only the LABEL changes. */}\n <span className=\"font-medium text-text-primary\">{dueSoonLabel(row)}</span>\n <span className=\"flex items-baseline gap-2\">\n <span className=\"tabular-nums text-text-secondary\">{row.expectedDeliveryDate}</span>\n <span className={`tabular-nums ${URGENCY_CLASS[urgency]}`}>\n {t(label.key, label.defaultValue)}\n {/* BOFF-6280 — an overdue row must say BY HOW MUCH. \"Overdue\" alone reads\n the same at three days as at three weeks, and those call for very\n different action. `daysUntilDue` is negative here, so it is negated\n for display rather than shown as \"-19d\". */}\n {/* Only when the count is a real number. `dueSoonUrgency` deliberately\n bands a non-finite value as OVERDUE rather than dropping the row, so\n the day count has to tolerate one too — otherwise the defence that\n keeps the row visible renders \"(by NaNd)\" next to it. */}\n {Number.isFinite(row.daysUntilDue) && (\n <span className=\"text-text-secondary\">\n {' '}\n {urgency === 'OVERDUE'\n ? t('healthybowl.livestock.fertility.due.byDays', '(by {{n}}d)', {\n n: String(Math.abs(row.daysUntilDue)),\n })\n : t('healthybowl.livestock.fertility.due.inDays', '({{n}}d)', {\n n: String(row.daysUntilDue),\n })}\n </span>\n )}\n </span>\n </span>\n </li>\n );\n })}\n </ul>\n )}\n </div>\n </>\n )}\n </ChartCard>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyDA,IAAM,IAAqC;CAAC;CAAO;CAAQ;CAAQ,EAQ7D,IAAgD;CACpD,SAAS;CACT,UAAU;CACV,MAAM;CACN,OAAO;CACR,EAOY,KAAyC,EAAE,aAAU,MAAM,mBAAgB;CACtF,IAAM,EAAE,SAAM,GAAS,EACjB,CAAC,GAAa,KAAkB,EAA4B,QAAQ,EACpE,CAAC,GAAM,KAAW,EAAS,GAAG,EAC9B,CAAC,GAAI,KAAS,EAAS,GAAG,EAC1B,EAAE,cAAW,YAAS,UAAO,cAAW,mBAAgB,YAAS,aAAU,EAAwB;EACvG;EACA;EACA,MAAM,KAAQ;EACd,IAAI,KAAM;EACX,C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AAC,MAAD;OAEE,WAAU;iBAFZ,CAME,kBAAC,QAAD;QAAM,WAAU;kBAAiC,EAAa,EAAI;QAAQ,CAAA,EAC1E,kBAAC,QAAD;QAAM,WAAU;kBAAhB,CACE,kBAAC,QAAD;SAAM,WAAU;mBAAoC,EAAI;SAA4B,CAAA,EACpF,kBAAC,QAAD;SAAM,WAAW,gBAAgB,EAAc;mBAA/C,CACG,EAAE,EAAM,KAAK,EAAM,aAAa,EAShC,OAAO,SAAS,EAAI,aAAa,IAChC,kBAAC,QAAD;UAAM,WAAU;oBAAhB,CACG,KACA,MAAY,YACT,EAAE,8CAA8C,eAAe,EAC7D,GAAG,OAAO,KAAK,IAAI,EAAI,aAAa,CAAC,EACtC,CAAC,GACF,EAAE,8CAA8C,YAAY,EAC1D,GAAG,OAAO,EAAI,aAAa,EAC5B,CAAC,CACD;YAEJ;WACF;UACJ;SAhCE,GAAG,EAAI,SAAS,GAAG,EAAI,uBAgCzB;OAEP;KACC,CAAA,CAEH;;GACL,EAAA,CAAA,GA3VH,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,KAAD;IAAG,WAAU;cACV,EAAE,+CAA+C,0BAA0B;IAC1E,CAAA,EACJ,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,8CACA,uJACD;IACC,CAAA,CACA;;EAmVE,CAAA"}
|
|
@@ -70,6 +70,10 @@ function s(e) {
|
|
|
70
70
|
return !Number.isFinite(e) || e < 0 ? "OVERDUE" : e <= 7 ? "IMMINENT" : e <= 14 ? "SOON" : "LATER";
|
|
71
71
|
}
|
|
72
72
|
function c(e) {
|
|
73
|
+
let t = e.tagNumber?.trim(), n = e.name?.trim();
|
|
74
|
+
return t && n ? `${t} · ${n}` : t || n || e.animalId;
|
|
75
|
+
}
|
|
76
|
+
function l(e) {
|
|
73
77
|
switch (e) {
|
|
74
78
|
case "OVERDUE": return {
|
|
75
79
|
key: "healthybowl.livestock.fertility.due.overdue",
|
|
@@ -89,11 +93,11 @@ function c(e) {
|
|
|
89
93
|
};
|
|
90
94
|
}
|
|
91
95
|
}
|
|
92
|
-
function
|
|
96
|
+
function u(e) {
|
|
93
97
|
let t = (e) => Number.isFinite(e) ? e : -Infinity;
|
|
94
98
|
return [...e].sort((e, n) => t(e.daysUntilDue) - t(n.daysUntilDue));
|
|
95
99
|
}
|
|
96
100
|
//#endregion
|
|
97
|
-
export { a as FERTILITY_CSV_HEADERS, t as calvingIntervalDisplay, s as dueSoonUrgency,
|
|
101
|
+
export { a as FERTILITY_CSV_HEADERS, t as calvingIntervalDisplay, c as dueSoonLabel, s as dueSoonUrgency, l as dueSoonUrgencyText, o as fertilityCsvRows, e as hasFertilityData, r as litterLiveBaseDiffers, u as orderedDueSoon, i as orderedFertilityBuckets, n as pregnancyLossDisplay };
|
|
98
102
|
|
|
99
103
|
//# sourceMappingURL=fertility.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fertility.js","names":[],"sources":["../../../src/healthybowl/utils/fertility.ts"],"sourcesContent":["/**\n * Fertility vocabulary and the caveats that travel with it (BOFF-6008).\n *\n * `healthyBowlLivestockFertility` is the fourth livestock analytics slice, beside growth, feed and\n * herd statistics. Its payload carries three contracts that are easy to break in JSX, so they live\n * here as pure functions and are unit-tested rather than left to the component:\n *\n * 1. **An unmeasured rate is not a zero, but a measured zero IS a zero.** The backend returns\n * `conceptionRatePct: null` when nothing was served, and `0` when services were served and\n * none conceived. Those are opposite facts about a herd — \"we have no breeding data\" versus\n * \"nothing is getting pregnant\" — and the second is the alarming one a farmer must see. So the\n * empty state is decided by whether any breeding activity exists at all\n * ({@link hasFertilityData}), never by whether a rate happens to be falsy.\n * 2. **The calving interval is withheld, with a reason, rather than guessed.** A DELIVERED record\n * with no delivery date merges two births into one gap and OVERSTATES the interval — the\n * direction that hides a fertility problem behind a number reading as merely mediocre. A farmer\n * culls animals on these figures. {@link calvingIntervalDisplay} forces the caller to render\n * the backend's sentence instead of a number, exactly as `mortalityDisplay` does for mortality.\n * 3. **The CSV must carry what the card shows.** {@link fertilityCsvRows} emits the window total as\n * its own labelled row, so the headline conception rate a reader checks first is in the export\n * rather than only derivable by re-aggregating the buckets.\n *\n * Strings are `{ key, defaultValue }` pairs, not finished text — this module is pure and tested in\n * the repo's `node` vitest environment, so callers pass them to their own `t()`.\n *\n * @module healthybowl\n */\n\nimport type { TranslatableText } from './grazing';\n\nexport type { TranslatableText };\n\n/** One bucket of the fertility trend, mirroring `HealthyBowlFertilityBucket`. */\nexport interface FertilityBucket {\n /** Bucket start, YYYY-MM-DD, keyed on the MATING date. */\n bucket: string;\n services: number;\n conceived: number;\n conceptionRatePct: number | null;\n deliveries: number;\n}\n\n/** A pregnancy due within the horizon, mirroring `HealthyBowlDueSoon`. */\nexport interface DueSoonRow {\n animalId: string;\n expectedDeliveryDate: string;\n daysUntilDue: number;\n}\n\n// ── 1. the empty state ────────────────────────────────────────────────────────\n\n/** The fields {@link hasFertilityData} needs. Deliberately not the whole payload. */\nexport interface FertilityPresence {\n services: number | null | undefined;\n deliveries: number | null | undefined;\n damsWithInterval: number | null | undefined;\n dueSoonCount: number;\n trendCount: number;\n}\n\n/**\n * Whether this workspace has any breeding activity to describe.\n *\n * ★ Decided on ACTIVITY, never on a rate. `conceptionRatePct === 0` is a real and serious\n * measurement — four services and nothing in calf — and showing \"No breeding records yet\" over the\n * top of it would tell a farmer their herd is fine when it is barren. Conversely a workspace that\n * has genuinely recorded nothing must not be shown `0%`, which reads as the same disaster.\n *\n * Deliveries are counted separately from services because a delivery whose mating fell outside the\n * window is still evidence the herd breeds; so are dams with a computable interval, and so is a\n * pregnancy due next week.\n */\nexport function hasFertilityData(input: FertilityPresence): boolean {\n const positive = (n: number | null | undefined): boolean => typeof n === 'number' && n > 0;\n return (\n positive(input.services) ||\n positive(input.deliveries) ||\n positive(input.damsWithInterval) ||\n input.dueSoonCount > 0 ||\n input.trendCount > 0\n );\n}\n\n// ── 2. the calving-interval disclosure ────────────────────────────────────────\n\nexport type CalvingIntervalDisplay =\n { available: true; meanDays: number; medianDays: number | null } | { available: false; reason: string | null };\n\n/**\n * Whether a calving interval can honestly be shown, and if not, why.\n *\n * Mirrors `mortalityDisplay`. The backend supplies the sentence precisely so the UI does not have\n * to invent one or, far worse, print the inflated figure. `reason` non-null is authoritative even\n * if a mean somehow arrived alongside it: the guard exists because the number is WRONG, not merely\n * absent, and a caller that preferred the number would defeat the whole guard.\n */\nexport function calvingIntervalDisplay(summary: {\n meanCalvingIntervalDays: number | null;\n medianCalvingIntervalDays: number | null;\n calvingIntervalUnavailableReason: string | null;\n}): CalvingIntervalDisplay {\n const reason = summary.calvingIntervalUnavailableReason?.trim();\n if (reason && reason.length > 0) return { available: false, reason };\n const mean = summary.meanCalvingIntervalDays;\n if (typeof mean !== 'number' || !Number.isFinite(mean)) return { available: false, reason: null };\n const median = summary.medianCalvingIntervalDays;\n return {\n available: true,\n meanDays: mean,\n medianDays: typeof median === 'number' && Number.isFinite(median) ? median : null,\n };\n}\n\n// ── 2b. the pregnancy-loss disclosure ─────────────────────────────────────────\n\nexport type PregnancyLossDisplay = { available: true; ratePct: number } | { available: false; reason: string | null };\n\n/**\n * Whether a pregnancy-loss rate can honestly be shown, and if not, why.\n *\n * Same shape and same reasoning as {@link calvingIntervalDisplay}. Today the backend ALWAYS\n * withholds this: telling a lost pregnancy apart from a service that never took requires knowing it\n * was confirmed first, and `pregnancyConfirmed` has no write path in the product — so the raw ratio\n * is structurally 0 on every herd, including one losing every calf it confirmed. `optionalMetric`\n * would have printed that 0 as a measurement, indistinguishable from a genuinely perfect record.\n */\nexport function pregnancyLossDisplay(summary: {\n pregnancyLossPct: number | null;\n pregnancyLossUnavailableReason: string | null;\n}): PregnancyLossDisplay {\n const reason = summary.pregnancyLossUnavailableReason?.trim();\n if (reason && reason.length > 0) return { available: false, reason };\n const rate = summary.pregnancyLossPct;\n if (typeof rate !== 'number' || !Number.isFinite(rate)) return { available: false, reason: null };\n return { available: true, ratePct: rate };\n}\n\n/**\n * Whether the live-born average is computed over FEWER deliveries than the born average, so the two\n * must not be shown as a comparable pair (BOFF-6281).\n *\n * How many were born and how many of those lived are recorded independently, so a herd can easily\n * have a born count on every delivery and a survival count on one of them. Each average is right on\n * its own terms, but side by side they once read \"Mean born 2.0 / Mean born alive 3.0\" — impossible\n * arithmetic that discredits every other figure on the card. When this returns true the card shows\n * the live average against `meanOffspringBornWhereLiveKnown`, its own group's born figure.\n *\n * False when coverage is equal, so a fully-recorded herd renders exactly as it did before.\n */\nexport function litterLiveBaseDiffers(summary: {\n deliveriesWithCounts: number;\n deliveriesWithLiveCounts: number;\n meanOffspringBornWhereLiveKnown: number | null;\n}): boolean {\n const base = summary.meanOffspringBornWhereLiveKnown;\n // Nothing to compare against: the live average is absent too, and the cell shows a dash.\n if (typeof base !== 'number' || !Number.isFinite(base)) return false;\n if (summary.deliveriesWithLiveCounts <= 0) return false;\n return summary.deliveriesWithLiveCounts < summary.deliveriesWithCounts;\n}\n\n// ── 3. trend + export ─────────────────────────────────────────────────────────\n\n/** Buckets in chronological order. The backend already sorts; this makes the chart independent. */\nexport function orderedFertilityBuckets(buckets: readonly FertilityBucket[]): FertilityBucket[] {\n return [...buckets].sort((a, b) => a.bucket.localeCompare(b.bucket));\n}\n\nexport interface FertilityCsvInput {\n services: number;\n conceived: number;\n conceptionRatePct: number | null;\n deliveries: number;\n trend: readonly FertilityBucket[];\n}\n\n/** Column order for {@link fertilityCsvRows}. Exported so the card and the test cannot drift. */\nexport const FERTILITY_CSV_HEADERS = ['Period', 'Services', 'Conceived', 'Conception rate %', 'Deliveries'] as const;\n\n/**\n * CSV rows for the fertility card: the window total first, then each bucket.\n *\n * The total leads because it is the figure the card headlines and the one a reader checks first.\n *\n * The total is computed by the backend over the same window-scoped services the buckets are built\n * from, so it should agree with their sum. It is emitted anyway rather than left to be re-derived:\n * a reader opening the export wants the headline rate without adding up twelve rows, and a\n * disagreement — were the two ever to drift apart — is then visible instead of silent.\n *\n * An unmeasured rate exports as an empty cell, never as `0` — a spreadsheet will average a zero.\n */\nexport function fertilityCsvRows(input: FertilityCsvInput): (string | number)[][] {\n const pct = (v: number | null): string | number => (typeof v === 'number' && Number.isFinite(v) ? v : '');\n return [\n ['Total (all services in window)', input.services, input.conceived, pct(input.conceptionRatePct), input.deliveries],\n ...orderedFertilityBuckets(input.trend).map((b) => [\n b.bucket,\n b.services,\n b.conceived,\n pct(b.conceptionRatePct),\n b.deliveries,\n ]),\n ];\n}\n\n// ── due-soon ──────────────────────────────────────────────────────────────────\n\n/**\n * How urgently a pregnancy needs attention.\n *\n * Purely a presentation band; the backend already excludes DELIVERED and FAILED records, so every\n * row here is a pregnancy still open. `OVERDUE` is a real, routine case: since BOFF-6280 the backend\n * returns rows up to 30 days past term with a NEGATIVE `daysUntilDue`, having previously filtered\n * them out of the query entirely. A due date that has passed is precisely the row a farmer most\n * needs to see, so it bands first rather than falling into \"later\".\n */\nexport type DueSoonUrgency = 'OVERDUE' | 'IMMINENT' | 'SOON' | 'LATER';\n\nexport function dueSoonUrgency(daysUntilDue: number): DueSoonUrgency {\n if (!Number.isFinite(daysUntilDue) || daysUntilDue < 0) return 'OVERDUE';\n if (daysUntilDue <= 7) return 'IMMINENT';\n if (daysUntilDue <= 14) return 'SOON';\n return 'LATER';\n}\n\n/** Label for a due-soon row's urgency, for the caller's `t()`. */\nexport function dueSoonUrgencyText(urgency: DueSoonUrgency): TranslatableText {\n switch (urgency) {\n case 'OVERDUE':\n return { key: 'healthybowl.livestock.fertility.due.overdue', defaultValue: 'Overdue' };\n case 'IMMINENT':\n return { key: 'healthybowl.livestock.fertility.due.imminent', defaultValue: 'Within a week' };\n case 'SOON':\n return { key: 'healthybowl.livestock.fertility.due.soon', defaultValue: 'Within a fortnight' };\n default:\n return { key: 'healthybowl.livestock.fertility.due.later', defaultValue: 'Later this month' };\n }\n}\n\n/**\n * Soonest first — the ordering a farmer plans around.\n *\n * A non-finite `daysUntilDue` sorts to the TOP, not to wherever the comparator happens to leave it.\n * {@link dueSoonUrgency} already labels such a row `OVERDUE`, so leaving the sort to return `NaN`\n * would print \"Overdue\" against a row sitting arbitrarily in the middle of the list — the one row\n * that most needs to be first, placed by chance.\n */\nexport function orderedDueSoon(rows: readonly DueSoonRow[]): DueSoonRow[] {\n const rank = (n: number): number => (Number.isFinite(n) ? n : Number.NEGATIVE_INFINITY);\n return [...rows].sort((a, b) => rank(a.daysUntilDue) - rank(b.daysUntilDue));\n}\n"],"mappings":";AAwEA,SAAgB,EAAiB,GAAmC;CAClE,IAAM,KAAY,MAA0C,OAAO,KAAM,YAAY,IAAI;AACzF,QACE,EAAS,EAAM,SAAS,IACxB,EAAS,EAAM,WAAW,IAC1B,EAAS,EAAM,iBAAiB,IAChC,EAAM,eAAe,KACrB,EAAM,aAAa;;AAiBvB,SAAgB,EAAuB,GAIZ;CACzB,IAAM,IAAS,EAAQ,kCAAkC,MAAM;AAC/D,KAAI,KAAU,EAAO,SAAS,EAAG,QAAO;EAAE,WAAW;EAAO;EAAQ;CACpE,IAAM,IAAO,EAAQ;AACrB,KAAI,OAAO,KAAS,YAAY,CAAC,OAAO,SAAS,EAAK,CAAE,QAAO;EAAE,WAAW;EAAO,QAAQ;EAAM;CACjG,IAAM,IAAS,EAAQ;AACvB,QAAO;EACL,WAAW;EACX,UAAU;EACV,YAAY,OAAO,KAAW,YAAY,OAAO,SAAS,EAAO,GAAG,IAAS;EAC9E;;AAgBH,SAAgB,EAAqB,GAGZ;CACvB,IAAM,IAAS,EAAQ,gCAAgC,MAAM;AAC7D,KAAI,KAAU,EAAO,SAAS,EAAG,QAAO;EAAE,WAAW;EAAO;EAAQ;CACpE,IAAM,IAAO,EAAQ;AAErB,QADI,OAAO,KAAS,YAAY,CAAC,OAAO,SAAS,EAAK,GAAS;EAAE,WAAW;EAAO,QAAQ;EAAM,GAC1F;EAAE,WAAW;EAAM,SAAS;EAAM;;AAe3C,SAAgB,EAAsB,GAI1B;CACV,IAAM,IAAO,EAAQ;AAIrB,QAFI,OAAO,KA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../../../src/healthybowl/utils/fertility.ts"],"sourcesContent":["/**\n * Fertility vocabulary and the caveats that travel with it (BOFF-6008).\n *\n * `healthyBowlLivestockFertility` is the fourth livestock analytics slice, beside growth, feed and\n * herd statistics. Its payload carries three contracts that are easy to break in JSX, so they live\n * here as pure functions and are unit-tested rather than left to the component:\n *\n * 1. **An unmeasured rate is not a zero, but a measured zero IS a zero.** The backend returns\n * `conceptionRatePct: null` when nothing was served, and `0` when services were served and\n * none conceived. Those are opposite facts about a herd — \"we have no breeding data\" versus\n * \"nothing is getting pregnant\" — and the second is the alarming one a farmer must see. So the\n * empty state is decided by whether any breeding activity exists at all\n * ({@link hasFertilityData}), never by whether a rate happens to be falsy.\n * 2. **The calving interval is withheld, with a reason, rather than guessed.** A DELIVERED record\n * with no delivery date merges two births into one gap and OVERSTATES the interval — the\n * direction that hides a fertility problem behind a number reading as merely mediocre. A farmer\n * culls animals on these figures. {@link calvingIntervalDisplay} forces the caller to render\n * the backend's sentence instead of a number, exactly as `mortalityDisplay` does for mortality.\n * 3. **The CSV must carry what the card shows.** {@link fertilityCsvRows} emits the window total as\n * its own labelled row, so the headline conception rate a reader checks first is in the export\n * rather than only derivable by re-aggregating the buckets.\n *\n * Strings are `{ key, defaultValue }` pairs, not finished text — this module is pure and tested in\n * the repo's `node` vitest environment, so callers pass them to their own `t()`.\n *\n * @module healthybowl\n */\n\nimport type { TranslatableText } from './grazing';\n\nexport type { TranslatableText };\n\n/** One bucket of the fertility trend, mirroring `HealthyBowlFertilityBucket`. */\nexport interface FertilityBucket {\n /** Bucket start, YYYY-MM-DD, keyed on the MATING date. */\n bucket: string;\n services: number;\n conceived: number;\n conceptionRatePct: number | null;\n deliveries: number;\n}\n\n/** A pregnancy due within the horizon, mirroring `HealthyBowlDueSoon`. */\nexport interface DueSoonRow {\n animalId: string;\n /** What is written on the animal — the primary label. Null when she is untagged. */\n tagNumber?: string | null;\n name?: string | null;\n expectedDeliveryDate: string;\n daysUntilDue: number;\n}\n\n// ── 1. the empty state ────────────────────────────────────────────────────────\n\n/** The fields {@link hasFertilityData} needs. Deliberately not the whole payload. */\nexport interface FertilityPresence {\n services: number | null | undefined;\n deliveries: number | null | undefined;\n damsWithInterval: number | null | undefined;\n dueSoonCount: number;\n trendCount: number;\n}\n\n/**\n * Whether this workspace has any breeding activity to describe.\n *\n * ★ Decided on ACTIVITY, never on a rate. `conceptionRatePct === 0` is a real and serious\n * measurement — four services and nothing in calf — and showing \"No breeding records yet\" over the\n * top of it would tell a farmer their herd is fine when it is barren. Conversely a workspace that\n * has genuinely recorded nothing must not be shown `0%`, which reads as the same disaster.\n *\n * Deliveries are counted separately from services because a delivery whose mating fell outside the\n * window is still evidence the herd breeds; so are dams with a computable interval, and so is a\n * pregnancy due next week.\n */\nexport function hasFertilityData(input: FertilityPresence): boolean {\n const positive = (n: number | null | undefined): boolean => typeof n === 'number' && n > 0;\n return (\n positive(input.services) ||\n positive(input.deliveries) ||\n positive(input.damsWithInterval) ||\n input.dueSoonCount > 0 ||\n input.trendCount > 0\n );\n}\n\n// ── 2. the calving-interval disclosure ────────────────────────────────────────\n\nexport type CalvingIntervalDisplay =\n { available: true; meanDays: number; medianDays: number | null } | { available: false; reason: string | null };\n\n/**\n * Whether a calving interval can honestly be shown, and if not, why.\n *\n * Mirrors `mortalityDisplay`. The backend supplies the sentence precisely so the UI does not have\n * to invent one or, far worse, print the inflated figure. `reason` non-null is authoritative even\n * if a mean somehow arrived alongside it: the guard exists because the number is WRONG, not merely\n * absent, and a caller that preferred the number would defeat the whole guard.\n */\nexport function calvingIntervalDisplay(summary: {\n meanCalvingIntervalDays: number | null;\n medianCalvingIntervalDays: number | null;\n calvingIntervalUnavailableReason: string | null;\n}): CalvingIntervalDisplay {\n const reason = summary.calvingIntervalUnavailableReason?.trim();\n if (reason && reason.length > 0) return { available: false, reason };\n const mean = summary.meanCalvingIntervalDays;\n if (typeof mean !== 'number' || !Number.isFinite(mean)) return { available: false, reason: null };\n const median = summary.medianCalvingIntervalDays;\n return {\n available: true,\n meanDays: mean,\n medianDays: typeof median === 'number' && Number.isFinite(median) ? median : null,\n };\n}\n\n// ── 2b. the pregnancy-loss disclosure ─────────────────────────────────────────\n\nexport type PregnancyLossDisplay = { available: true; ratePct: number } | { available: false; reason: string | null };\n\n/**\n * Whether a pregnancy-loss rate can honestly be shown, and if not, why.\n *\n * Same shape and same reasoning as {@link calvingIntervalDisplay}. Today the backend ALWAYS\n * withholds this: telling a lost pregnancy apart from a service that never took requires knowing it\n * was confirmed first, and `pregnancyConfirmed` has no write path in the product — so the raw ratio\n * is structurally 0 on every herd, including one losing every calf it confirmed. `optionalMetric`\n * would have printed that 0 as a measurement, indistinguishable from a genuinely perfect record.\n */\nexport function pregnancyLossDisplay(summary: {\n pregnancyLossPct: number | null;\n pregnancyLossUnavailableReason: string | null;\n}): PregnancyLossDisplay {\n const reason = summary.pregnancyLossUnavailableReason?.trim();\n if (reason && reason.length > 0) return { available: false, reason };\n const rate = summary.pregnancyLossPct;\n if (typeof rate !== 'number' || !Number.isFinite(rate)) return { available: false, reason: null };\n return { available: true, ratePct: rate };\n}\n\n/**\n * Whether the live-born average is computed over FEWER deliveries than the born average, so the two\n * must not be shown as a comparable pair (BOFF-6281).\n *\n * How many were born and how many of those lived are recorded independently, so a herd can easily\n * have a born count on every delivery and a survival count on one of them. Each average is right on\n * its own terms, but side by side they once read \"Mean born 2.0 / Mean born alive 3.0\" — impossible\n * arithmetic that discredits every other figure on the card. When this returns true the card shows\n * the live average against `meanOffspringBornWhereLiveKnown`, its own group's born figure.\n *\n * False when coverage is equal, so a fully-recorded herd renders exactly as it did before.\n */\nexport function litterLiveBaseDiffers(summary: {\n deliveriesWithCounts: number;\n deliveriesWithLiveCounts: number;\n meanOffspringBornWhereLiveKnown: number | null;\n}): boolean {\n const base = summary.meanOffspringBornWhereLiveKnown;\n // Nothing to compare against: the live average is absent too, and the cell shows a dash.\n if (typeof base !== 'number' || !Number.isFinite(base)) return false;\n if (summary.deliveriesWithLiveCounts <= 0) return false;\n return summary.deliveriesWithLiveCounts < summary.deliveriesWithCounts;\n}\n\n// ── 3. trend + export ─────────────────────────────────────────────────────────\n\n/** Buckets in chronological order. The backend already sorts; this makes the chart independent. */\nexport function orderedFertilityBuckets(buckets: readonly FertilityBucket[]): FertilityBucket[] {\n return [...buckets].sort((a, b) => a.bucket.localeCompare(b.bucket));\n}\n\nexport interface FertilityCsvInput {\n services: number;\n conceived: number;\n conceptionRatePct: number | null;\n deliveries: number;\n trend: readonly FertilityBucket[];\n}\n\n/** Column order for {@link fertilityCsvRows}. Exported so the card and the test cannot drift. */\nexport const FERTILITY_CSV_HEADERS = ['Period', 'Services', 'Conceived', 'Conception rate %', 'Deliveries'] as const;\n\n/**\n * CSV rows for the fertility card: the window total first, then each bucket.\n *\n * The total leads because it is the figure the card headlines and the one a reader checks first.\n *\n * The total is computed by the backend over the same window-scoped services the buckets are built\n * from, so it should agree with their sum. It is emitted anyway rather than left to be re-derived:\n * a reader opening the export wants the headline rate without adding up twelve rows, and a\n * disagreement — were the two ever to drift apart — is then visible instead of silent.\n *\n * An unmeasured rate exports as an empty cell, never as `0` — a spreadsheet will average a zero.\n */\nexport function fertilityCsvRows(input: FertilityCsvInput): (string | number)[][] {\n const pct = (v: number | null): string | number => (typeof v === 'number' && Number.isFinite(v) ? v : '');\n return [\n ['Total (all services in window)', input.services, input.conceived, pct(input.conceptionRatePct), input.deliveries],\n ...orderedFertilityBuckets(input.trend).map((b) => [\n b.bucket,\n b.services,\n b.conceived,\n pct(b.conceptionRatePct),\n b.deliveries,\n ]),\n ];\n}\n\n// ── due-soon ──────────────────────────────────────────────────────────────────\n\n/**\n * How urgently a pregnancy needs attention.\n *\n * Purely a presentation band; the backend already excludes DELIVERED and FAILED records, so every\n * row here is a pregnancy still open. `OVERDUE` is a real, routine case: since BOFF-6280 the backend\n * returns rows up to 30 days past term with a NEGATIVE `daysUntilDue`, having previously filtered\n * them out of the query entirely. A due date that has passed is precisely the row a farmer most\n * needs to see, so it bands first rather than falling into \"later\".\n */\nexport type DueSoonUrgency = 'OVERDUE' | 'IMMINENT' | 'SOON' | 'LATER';\n\nexport function dueSoonUrgency(daysUntilDue: number): DueSoonUrgency {\n if (!Number.isFinite(daysUntilDue) || daysUntilDue < 0) return 'OVERDUE';\n if (daysUntilDue <= 7) return 'IMMINENT';\n if (daysUntilDue <= 14) return 'SOON';\n return 'LATER';\n}\n\n/**\n * How to name the animal on a due-soon row (BOFF-6283).\n *\n * The tag comes first: it is what is physically on the animal, so it is how she is actually found in\n * the shed. The name follows as `IN-0012 · Lakshmi`, matching the convention already used by the\n * animal picker and the herd table.\n *\n * Falls back through name, then the raw id — a row must never render blank, and before this the id\n * was ALL it rendered, so showing it in the degenerate case is no worse than the old behaviour and\n * still identifies the row uniquely.\n */\nexport function dueSoonLabel(row: Pick<DueSoonRow, 'animalId' | 'tagNumber' | 'name'>): string {\n const tag = row.tagNumber?.trim();\n const name = row.name?.trim();\n if (tag && name) return `${tag} · ${name}`;\n return tag || name || row.animalId;\n}\n\n/** Label for a due-soon row's urgency, for the caller's `t()`. */\nexport function dueSoonUrgencyText(urgency: DueSoonUrgency): TranslatableText {\n switch (urgency) {\n case 'OVERDUE':\n return { key: 'healthybowl.livestock.fertility.due.overdue', defaultValue: 'Overdue' };\n case 'IMMINENT':\n return { key: 'healthybowl.livestock.fertility.due.imminent', defaultValue: 'Within a week' };\n case 'SOON':\n return { key: 'healthybowl.livestock.fertility.due.soon', defaultValue: 'Within a fortnight' };\n default:\n return { key: 'healthybowl.livestock.fertility.due.later', defaultValue: 'Later this month' };\n }\n}\n\n/**\n * Soonest first — the ordering a farmer plans around.\n *\n * A non-finite `daysUntilDue` sorts to the TOP, not to wherever the comparator happens to leave it.\n * {@link dueSoonUrgency} already labels such a row `OVERDUE`, so leaving the sort to return `NaN`\n * would print \"Overdue\" against a row sitting arbitrarily in the middle of the list — the one row\n * that most needs to be first, placed by chance.\n */\nexport function orderedDueSoon(rows: readonly DueSoonRow[]): D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