@burdenoff/microfe-healthybowl 2026.812.18 → 2026.812.20
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/useHealthyBowlCompliance.js +1 -0
- package/dist/healthybowl/hooks/useHealthyBowlCompliance.js.map +1 -1
- package/dist/healthybowl/hooks/useHealthyBowlFertility.js +2 -0
- package/dist/healthybowl/hooks/useHealthyBowlFertility.js.map +1 -1
- package/dist/healthybowl/pages/compliance/ComplianceOverviewPage.js +5 -4
- package/dist/healthybowl/pages/compliance/ComplianceOverviewPage.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":"useHealthyBowlCompliance.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlCompliance.ts"],"sourcesContent":["/**\n * Certification & Compliance depth (NPOP / GLOBALG.A.P. / EUDR) + Internal Control System.\n * Roadmap 10 · BOFF-2882.\n *\n * Documents are declared inline with `gql` rather than as `src/operations/wspace/*.graphql`\n * files, because codegen validates operation documents against the committed\n * `graphql/wspace.graphql` snapshot — which is pulled from the gateway and so cannot know\n * about these fields until the subgraph is live in the supergraph. This is the same\n * escape hatch `useHealthyBowlData` already uses (see CREATE_COMPLIANCE_DOCUMENT_DOC).\n * Types below mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/compliance.gql`.\n *\n * Reads use `cache-and-network`; every write refetches the reads it invalidates, matching\n * the reconciliation contract in `useHealthyBowlData`.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\nconst FALLBACK_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001';\n\n// ── types (mirror compliance.gql) ──────────────────────────────────────────\n\nexport type FlagSeverity = 'INFO' | 'WARNING' | 'CRITICAL';\nexport type FlagStatus = 'OPEN' | 'ACKNOWLEDGED' | 'RESOLVED' | 'DISMISSED';\nexport type FlagType =\n 'BANNED_SUBSTANCE' | 'MRL_EXCEEDED' | 'CERT_EXPIRING' | 'CERT_EXPIRED' | 'INSPECTION_OVERDUE' | 'DOCUMENT_MISSING';\n\nexport type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH';\nexport type ChecklistStatus = 'MISSING' | 'UPLOADED' | 'UNDER_REVIEW' | 'APPROVED' | 'REJECTED' | 'NOT_APPLICABLE';\nexport type InspectionStatus = 'SCHEDULED' | 'DRAFT' | 'PASSED' | 'CONDITIONAL' | 'FAILED';\nexport type ChecklistResult = 'PASS' | 'FAIL' | 'NA';\n\nexport interface ComplianceFlag {\n id: string;\n type: FlagType;\n severity: FlagSeverity;\n status: FlagStatus;\n title: string;\n message: string;\n entityType: string;\n entityId: string | null;\n detectedAt: string;\n resolvedAt: string | null;\n resolvedBy: string | null;\n resolution: string | null;\n metadata: Record<string, unknown> | null;\n}\n\n/** The `Certification` type. */\nexport interface Certification {\n id: string;\n name: string;\n body: string;\n standard: string;\n standardCode: string | null;\n stage: string;\n icsGroupId: string | null;\n issueDate: string;\n expiryDate: string;\n status: string;\n scope: string[];\n daysToExpiry: number;\n expiringSoon: boolean;\n renewalStartedAt: string | null;\n}\n\n/** A `Certification` plus its computed checklist progress (dashboard standards row). */\nexport interface CertificationStandardProgress extends Certification {\n progressPercent: number;\n checklistTotal: number;\n checklistApproved: number;\n}\n\nexport interface IcsInspection {\n id: string;\n icsGroupId: string;\n growerId: string;\n inspectionDate: string;\n inspectorName: string;\n status: InspectionStatus;\n checklist: Array<{ key: string; label: string; result: ChecklistResult; note: string | null }> | null;\n notes: string | null;\n latitude: number | null;\n longitude: number | null;\n photoFileIds: string[];\n findingsCount: number;\n}\n\nexport interface IcsGrower {\n id: string;\n icsGroupId: string;\n memberCode: string;\n fullName: string;\n village: string;\n district: string | null;\n mobile: string | null;\n primaryCrop: string | null;\n plotAreaHectares: number | null;\n conversionStatus: string;\n riskLevel: RiskLevel;\n latitude: number | null;\n longitude: number | null;\n plots: unknown;\n active: boolean;\n lastInspectionDate: string | null;\n lastInspectionStatus: InspectionStatus | null;\n nextInspectionDate: string | null;\n inspectionOverdue: boolean;\n inspectionCount: number;\n}\n\nexport interface IcsGroupSummary {\n id: string;\n name: string;\n code: string;\n registrationNumber: string | null;\n contactPerson: string | null;\n contactPhone: string | null;\n description: string | null;\n status: string;\n certificationId: string | null;\n createdAt: string;\n growerCount: number;\n highRiskCount: number;\n inspectionsOverdue: number;\n totalPlotAreaHectares: number;\n}\n\nexport interface IcsRollup {\n totalGroups: number;\n totalGrowers: number;\n lowRisk: number;\n mediumRisk: number;\n highRisk: number;\n inspectionsPassed: number;\n inspectionsFailed: number;\n inspectionsConditional: number;\n inspectionsScheduled: number;\n inspectionsOverdue: number;\n growersNeverInspected: number;\n totalPlotAreaHectares: number;\n}\n\nexport interface ComplianceOverview {\n activeCertifications: number;\n expiringCertifications: number;\n expiredCertifications: number;\n icsMemberGrowers: number;\n openAuditFindings: number;\n openFlags: number;\n criticalFlags: number;\n standards: CertificationStandardProgress[];\n expiringSoon: CertificationStandardProgress[];\n flags: ComplianceFlag[];\n upcomingInspections: IcsInspection[];\n updatedAt: string;\n}\n\nexport interface StandardTemplateItem {\n code: string;\n label: string;\n description: string;\n required: boolean;\n orderIndex: number;\n}\n\nexport interface StandardTemplate {\n code: string;\n name: string;\n fullName: string;\n issuerHint: string;\n description: string;\n items: StandardTemplateItem[];\n}\n\nexport interface ChecklistItem {\n id: string;\n code: string;\n label: string;\n description: string | null;\n required: boolean;\n status: ChecklistStatus;\n documentId: string | null;\n orderIndex: number;\n completedAt: string | null;\n}\n\nexport interface CertificationDetail {\n certification: Certification;\n standard: StandardTemplate | null;\n checklistItems: ChecklistItem[];\n documents: Array<{\n id: string;\n name: string;\n type: string;\n status: string;\n uploadedDate: string;\n fileId: string | null;\n fileName: string | null;\n fileUrl: string | null;\n }>;\n progressPercent: number;\n requiredCount: number;\n approvedCount: number;\n missingCount: number;\n}\n\nexport interface SubstanceRule {\n id: string;\n substanceName: string;\n activeIngredient: string | null;\n casNumber: string | null;\n standardCode: string | null;\n prohibited: boolean;\n mrlMgPerKg: number | null;\n cropScope: string | null;\n source: string;\n notes: string | null;\n builtin: boolean;\n}\n\nexport interface ResidueTest {\n id: string;\n traceBatchId: string | null;\n cropId: string | null;\n substanceName: string;\n measuredMgPerKg: number;\n testedAt: string;\n laboratory: string | null;\n reportFileId: string | null;\n notes: string | null;\n}\n\nexport interface CertificateOfOrigin {\n id: string;\n certificateNumber: string;\n traceBatchId: string;\n issuedDate: string;\n exporterName: string;\n consigneeName: string | null;\n destinationCountry: string | null;\n productDescription: string;\n quantity: number;\n unit: string;\n hsCode: string | null;\n originCountry: string;\n originRegion: string | null;\n certificationIds: string[];\n declaration: string;\n status: string;\n fileId: string | null;\n fileName: string | null;\n}\n\nexport interface ScanResult {\n scannedAt: string;\n newFlags: number;\n totalOpenFlags: number;\n certificationsExpiring: number;\n certificationsExpired: number;\n bannedSubstanceFlags: number;\n mrlFlags: number;\n overdueInspections: number;\n missingDocuments: number;\n notificationsSent: number;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\n// ── documents ──────────────────────────────────────────────────────────────\n\n/** Fields on the `Certification` type itself. */\nconst CERT_FIELDS = `\n id\n name\n body\n standard\n standardCode\n stage\n icsGroupId\n issueDate\n expiryDate\n status\n scope\n daysToExpiry\n expiringSoon\n renewalStartedAt\n`;\n\n/**\n * `CertificationStandardProgress` = Certification + the computed checklist progress.\n * These extra fields exist ONLY on that type, not on `Certification` — selecting them\n * inside `CertificationDetail.certification` is a validation error.\n */\nconst CERT_PROGRESS_FIELDS = `\n ${CERT_FIELDS}\n progressPercent\n checklistTotal\n checklistApproved\n`;\n\nconst FLAG_FIELDS = `\n id\n type\n severity\n status\n title\n message\n entityType\n entityId\n detectedAt\n resolvedAt\n resolvedBy\n resolution\n metadata\n`;\n\nconst INSPECTION_FIELDS = `\n id\n icsGroupId\n growerId\n inspectionDate\n inspectorName\n status\n checklist\n notes\n latitude\n longitude\n photoFileIds\n findingsCount\n`;\n\nconst GROWER_FIELDS = `\n id\n icsGroupId\n memberCode\n fullName\n village\n district\n mobile\n primaryCrop\n plotAreaHectares\n conversionStatus\n riskLevel\n latitude\n longitude\n plots\n active\n lastInspectionDate\n lastInspectionStatus\n nextInspectionDate\n inspectionOverdue\n inspectionCount\n`;\n\nconst ROLLUP_FIELDS = `\n totalGroups\n totalGrowers\n lowRisk\n mediumRisk\n highRisk\n inspectionsPassed\n inspectionsFailed\n inspectionsConditional\n inspectionsScheduled\n inspectionsOverdue\n growersNeverInspected\n totalPlotAreaHectares\n`;\n\nconst CERT_DETAIL_FIELDS = `\n certification { ${CERT_FIELDS} }\n standard { code name fullName issuerHint description items { code label description required orderIndex } }\n checklistItems { id code label description required status documentId orderIndex completedAt }\n documents { id name type status uploadedDate fileId fileName fileUrl }\n progressPercent\n requiredCount\n approvedCount\n missingCount\n`;\n\nconst GET_OVERVIEW = gql`\n query GetHealthyBowlComplianceOverview($context: ContextInput!) {\n getHealthyBowlComplianceOverview(context: $context) {\n activeCertifications\n expiringCertifications\n expiredCertifications\n icsMemberGrowers\n openAuditFindings\n openFlags\n criticalFlags\n standards { ${CERT_PROGRESS_FIELDS} }\n expiringSoon { ${CERT_PROGRESS_FIELDS} }\n flags { ${FLAG_FIELDS} }\n upcomingInspections { ${INSPECTION_FIELDS} }\n updatedAt\n }\n }\n`;\n\nconst GET_ICS_DATA = gql`\n query GetHealthyBowlIcsData($context: ContextInput!) {\n getHealthyBowlIcsData(context: $context) {\n groups {\n id name code registrationNumber contactPerson contactPhone description status certificationId createdAt\n growerCount highRiskCount inspectionsOverdue totalPlotAreaHectares\n }\n growers { ${GROWER_FIELDS} }\n inspections { ${INSPECTION_FIELDS} }\n rollup { ${ROLLUP_FIELDS} }\n }\n }\n`;\n\nconst GET_ICS_GROUP_DETAIL = gql`\n query GetHealthyBowlIcsGroupDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlIcsGroupDetail(id: $id, context: $context) {\n group { id name code registrationNumber contactPerson contactPhone description status certificationId createdAt }\n certification { id name standard standardCode stage status expiryDate daysToExpiry expiringSoon }\n growers { ${GROWER_FIELDS} }\n inspections { ${INSPECTION_FIELDS} }\n rollup { ${ROLLUP_FIELDS} }\n }\n }\n`;\n\nconst GET_ICS_GROWER_DETAIL = gql`\n query GetHealthyBowlIcsGrowerDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlIcsGrowerDetail(id: $id, context: $context) {\n grower { ${GROWER_FIELDS} }\n group { id name code status certificationId createdAt }\n inspections { ${INSPECTION_FIELDS} }\n }\n }\n`;\n\nconst GET_STANDARDS = gql`\n query GetHealthyBowlCertificationStandards($context: ContextInput!) {\n getHealthyBowlCertificationStandards(context: $context) {\n code\n name\n fullName\n issuerHint\n description\n items {\n code\n label\n description\n required\n orderIndex\n }\n }\n }\n`;\n\nconst GET_CERT_DETAIL = gql`\n query GetHealthyBowlCertificationDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlCertificationDetail(id: $id, context: $context) { ${CERT_DETAIL_FIELDS} }\n }\n`;\n\nconst GET_FLAGS = gql`\n query GetHealthyBowlComplianceFlags($context: ContextInput!, $status: String, $type: String) {\n getHealthyBowlComplianceFlags(context: $context, status: $status, type: $type) { ${FLAG_FIELDS} }\n }\n`;\n\nconst GET_SUBSTANCE_RULES = gql`\n query GetHealthyBowlSubstanceRules($context: ContextInput!) {\n getHealthyBowlSubstanceRules(context: $context) {\n id\n substanceName\n activeIngredient\n casNumber\n standardCode\n prohibited\n mrlMgPerKg\n cropScope\n source\n notes\n builtin\n }\n }\n`;\n\nconst GET_RESIDUE_TESTS = gql`\n query GetHealthyBowlResidueTests($context: ContextInput!) {\n getHealthyBowlResidueTests(context: $context) {\n id\n traceBatchId\n cropId\n substanceName\n measuredMgPerKg\n testedAt\n laboratory\n reportFileId\n notes\n }\n }\n`;\n\nconst GET_COOS = gql`\n query GetHealthyBowlCertificatesOfOrigin($context: ContextInput!) {\n getHealthyBowlCertificatesOfOrigin(context: $context) {\n id\n certificateNumber\n traceBatchId\n issuedDate\n exporterName\n consigneeName\n destinationCountry\n productDescription\n quantity\n unit\n hsCode\n originCountry\n originRegion\n certificationIds\n declaration\n status\n fileId\n fileName\n }\n }\n`;\n\nconst GET_COO_PDF = gql`\n query GetHealthyBowlCertificateOfOriginPdf($id: ID!, $context: ContextInput!) {\n getHealthyBowlCertificateOfOriginPdf(id: $id, context: $context) {\n id\n certificateNumber\n fileName\n contentType\n pdfBase64\n }\n }\n`;\n\nconst CREATE_ICS_GROUP = gql`\n mutation CreateHealthyBowlIcsGroup($input: CreateIcsGroupInput!) {\n createHealthyBowlIcsGroup(input: $input) {\n id\n name\n code\n status\n }\n }\n`;\nconst UPDATE_ICS_GROUP = gql`\n mutation UpdateHealthyBowlIcsGroup($input: UpdateIcsGroupInput!) {\n updateHealthyBowlIcsGroup(input: $input) {\n id\n name\n code\n status\n }\n }\n`;\nconst DELETE_ICS_GROUP = gql`\n mutation DeleteHealthyBowlIcsGroup($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlIcsGroup(id: $id, context: $context)\n }\n`;\nconst CREATE_ICS_GROWER = gql`\n mutation CreateHealthyBowlIcsGrower($input: CreateIcsGrowerInput!) {\n createHealthyBowlIcsGrower(input: $input) {\n id\n fullName\n riskLevel\n }\n }\n`;\nconst UPDATE_ICS_GROWER = gql`\n mutation UpdateHealthyBowlIcsGrower($input: UpdateIcsGrowerInput!) {\n updateHealthyBowlIcsGrower(input: $input) {\n id\n fullName\n riskLevel\n }\n }\n`;\nconst DELETE_ICS_GROWER = gql`\n mutation DeleteHealthyBowlIcsGrower($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlIcsGrower(id: $id, context: $context)\n }\n`;\nconst SCHEDULE_INSPECTION = gql`\n mutation ScheduleHealthyBowlIcsInspection($input: ScheduleIcsInspectionInput!) {\n scheduleHealthyBowlIcsInspection(input: $input) {\n id\n status\n inspectionDate\n }\n }\n`;\nconst RECORD_INSPECTION = gql`\n mutation RecordHealthyBowlIcsInspection($input: RecordIcsInspectionInput!) {\n recordHealthyBowlIcsInspection(input: $input) {\n id\n status\n findingsCount\n }\n }\n`;\nconst APPLY_STANDARD = gql`\n mutation ApplyHealthyBowlCertificationStandard($input: ApplyCertificationStandardInput!) {\n applyHealthyBowlCertificationStandard(input: $input) {\n progressPercent\n requiredCount\n approvedCount\n missingCount\n }\n }\n`;\nconst UPDATE_CHECKLIST_ITEM = gql`\n mutation UpdateHealthyBowlCertificationChecklistItem($input: UpdateChecklistItemInput!) {\n updateHealthyBowlCertificationChecklistItem(input: $input) {\n progressPercent\n approvedCount\n missingCount\n }\n }\n`;\nconst START_RENEWAL = gql`\n mutation StartHealthyBowlCertificationRenewal($id: ID!, $context: ContextInput!) {\n startHealthyBowlCertificationRenewal(id: $id, context: $context) {\n id\n status\n stage\n renewalStartedAt\n }\n }\n`;\nconst RUN_SCAN = gql`\n mutation RunHealthyBowlComplianceScan($context: ContextInput!) {\n runHealthyBowlComplianceScan(context: $context) {\n scannedAt\n newFlags\n totalOpenFlags\n certificationsExpiring\n certificationsExpired\n bannedSubstanceFlags\n mrlFlags\n overdueInspections\n missingDocuments\n notificationsSent\n }\n }\n`;\nconst ACK_FLAG = gql`\n mutation AcknowledgeHealthyBowlComplianceFlag($id: ID!, $context: ContextInput!) {\n acknowledgeHealthyBowlComplianceFlag(id: $id, context: $context) {\n id\n status\n }\n }\n`;\nconst RESOLVE_FLAG = gql`\n mutation ResolveHealthyBowlComplianceFlag($input: ResolveComplianceFlagInput!) {\n resolveHealthyBowlComplianceFlag(input: $input) {\n id\n status\n resolution\n }\n }\n`;\nconst DISMISS_FLAG = gql`\n mutation DismissHealthyBowlComplianceFlag($input: DismissComplianceFlagInput!) {\n dismissHealthyBowlComplianceFlag(input: $input) {\n id\n status\n resolution\n }\n }\n`;\nconst CREATE_SUBSTANCE_RULE = gql`\n mutation CreateHealthyBowlSubstanceRule($input: CreateComplianceSubstanceRuleInput!) {\n createHealthyBowlSubstanceRule(input: $input) {\n id\n substanceName\n }\n }\n`;\nconst DELETE_SUBSTANCE_RULE = gql`\n mutation DeleteHealthyBowlSubstanceRule($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlSubstanceRule(id: $id, context: $context)\n }\n`;\nconst CREATE_RESIDUE_TEST = gql`\n mutation CreateHealthyBowlResidueTest($input: CreateComplianceResidueTestInput!) {\n createHealthyBowlResidueTest(input: $input) {\n id\n substanceName\n measuredMgPerKg\n }\n }\n`;\nconst DELETE_RESIDUE_TEST = gql`\n mutation DeleteHealthyBowlResidueTest($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlResidueTest(id: $id, context: $context)\n }\n`;\nconst GENERATE_COO = gql`\n mutation GenerateHealthyBowlCertificateOfOrigin($input: GenerateCertificateOfOriginInput!) {\n generateHealthyBowlCertificateOfOrigin(input: $input) {\n id\n certificateNumber\n status\n }\n }\n`;\nconst ATTACH_COO_FILE = gql`\n mutation AttachHealthyBowlCertificateOfOriginFile($input: AttachCertificateOfOriginFileInput!) {\n attachHealthyBowlCertificateOfOriginFile(input: $input) {\n id\n fileId\n fileName\n }\n }\n`;\nconst REVOKE_COO = gql`\n mutation RevokeHealthyBowlCertificateOfOrigin($id: ID!, $context: ContextInput!) {\n revokeHealthyBowlCertificateOfOrigin(id: $id, context: $context) {\n id\n status\n }\n }\n`;\n\n// ── hook ───────────────────────────────────────────────────────────────────\n\nexport interface UseComplianceOptions {\n /** Skip the ICS / rules / residue / CoO reads on pages that only need the overview. */\n skipSecondary?: boolean;\n}\n\nexport function useHealthyBowlCompliance(options: UseComplianceOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const ctx = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n const skip = options.skipSecondary === true;\n\n const overviewQuery = useQuery<{ getHealthyBowlComplianceOverview: ComplianceOverview }, { context: HbContext }>(\n GET_OVERVIEW,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network' }\n );\n\n const icsQuery = useQuery<\n {\n getHealthyBowlIcsData: {\n groups: IcsGroupSummary[];\n growers: IcsGrower[];\n inspections: IcsInspection[];\n rollup: IcsRollup;\n };\n },\n { context: HbContext }\n >(GET_ICS_DATA, { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip });\n\n const standardsQuery = useQuery<{ getHealthyBowlCertificationStandards: StandardTemplate[] }, { context: HbContext }>(\n GET_STANDARDS,\n { variables: { context: ctx }, fetchPolicy: 'cache-first', skip }\n );\n\n const rulesQuery = useQuery<{ getHealthyBowlSubstanceRules: SubstanceRule[] }, { context: HbContext }>(\n GET_SUBSTANCE_RULES,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const residueQuery = useQuery<{ getHealthyBowlResidueTests: ResidueTest[] }, { context: HbContext }>(\n GET_RESIDUE_TESTS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const cooQuery = useQuery<{ getHealthyBowlCertificatesOfOrigin: CertificateOfOrigin[] }, { context: HbContext }>(\n GET_COOS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const flagsQuery = useQuery<\n { getHealthyBowlComplianceFlags: ComplianceFlag[] },\n { context: HbContext; status?: string | null; type?: string | null }\n >(GET_FLAGS, { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip });\n\n const refetchOverview = overviewQuery.refetch;\n const refetchIcs = icsQuery.refetch;\n const refetchFlags = flagsQuery.refetch;\n const refetchRules = rulesQuery.refetch;\n const refetchResidue = residueQuery.refetch;\n const refetchCoos = cooQuery.refetch;\n\n /** Reconcile the reads a write invalidates. Non-fatal: the next load reconciles anyway. */\n const reconcile = useCallback(async (...refetchers: Array<() => Promise<unknown>>) => {\n await Promise.all(\n refetchers.map((run) =>\n run().catch(() => {\n /* non-fatal */\n })\n )\n );\n }, []);\n\n const [createIcsGroupMutation] = useMutation(CREATE_ICS_GROUP);\n const [updateIcsGroupMutation] = useMutation(UPDATE_ICS_GROUP);\n const [deleteIcsGroupMutation] = useMutation(DELETE_ICS_GROUP);\n const [createIcsGrowerMutation] = useMutation(CREATE_ICS_GROWER);\n const [updateIcsGrowerMutation] = useMutation(UPDATE_ICS_GROWER);\n const [deleteIcsGrowerMutation] = useMutation(DELETE_ICS_GROWER);\n const [scheduleInspectionMutation] = useMutation(SCHEDULE_INSPECTION);\n const [recordInspectionMutation] = useMutation(RECORD_INSPECTION);\n const [applyStandardMutation] = useMutation(APPLY_STANDARD);\n const [updateChecklistItemMutation] = useMutation(UPDATE_CHECKLIST_ITEM);\n const [startRenewalMutation] = useMutation(START_RENEWAL);\n // Typed: these two are the only mutations whose response payload a caller reads back.\n const [runScanMutation] = useMutation<{ runHealthyBowlComplianceScan: ScanResult }, { context: HbContext }>(RUN_SCAN);\n const [ackFlagMutation] = useMutation(ACK_FLAG);\n const [resolveFlagMutation] = useMutation(RESOLVE_FLAG);\n const [dismissFlagMutation] = useMutation(DISMISS_FLAG);\n const [createSubstanceRuleMutation] = useMutation(CREATE_SUBSTANCE_RULE);\n const [deleteSubstanceRuleMutation] = useMutation(DELETE_SUBSTANCE_RULE);\n const [createResidueTestMutation] = useMutation(CREATE_RESIDUE_TEST);\n const [deleteResidueTestMutation] = useMutation(DELETE_RESIDUE_TEST);\n const [generateCooMutation] = useMutation<\n { generateHealthyBowlCertificateOfOrigin: { id: string; certificateNumber: string; status: string } },\n { input: Record<string, unknown> }\n >(GENERATE_COO);\n const [attachCooFileMutation] = useMutation(ATTACH_COO_FILE);\n const [revokeCooMutation] = useMutation(REVOKE_COO);\n\n /**\n * Fire a mutation, surface its error, then reconcile the reads it invalidates.\n * Returns `unknown` because the callers below ignore the payload; the two mutations\n * whose payload IS read (runScan, generateCertificateOfOrigin) are typed and called directly.\n */\n const run = useCallback(\n async (\n mutate: (opts: { variables: Record<string, unknown> }) => Promise<{ data?: unknown; error?: unknown }>,\n variables: Record<string, unknown>,\n after: Array<() => Promise<unknown>>\n ): Promise<unknown> => {\n const res = await mutate({ variables });\n if (res.error) {\n throw res.error instanceof Error ? res.error : new Error(String(res.error));\n }\n await reconcile(...after);\n return res.data;\n },\n [reconcile]\n );\n\n const withCtx = useCallback((input: Record<string, unknown>) => ({ ...input, context: ctx }), [ctx]);\n\n return {\n overview: overviewQuery.data?.getHealthyBowlComplianceOverview ?? null,\n ics: icsQuery.data?.getHealthyBowlIcsData ?? null,\n standards: standardsQuery.data?.getHealthyBowlCertificationStandards ?? [],\n substanceRules: rulesQuery.data?.getHealthyBowlSubstanceRules ?? [],\n residueTests: residueQuery.data?.getHealthyBowlResidueTests ?? [],\n certificatesOfOrigin: cooQuery.data?.getHealthyBowlCertificatesOfOrigin ?? [],\n flags: flagsQuery.data?.getHealthyBowlComplianceFlags ?? [],\n\n loading: {\n overview: overviewQuery.loading,\n ics: icsQuery.loading,\n standards: standardsQuery.loading,\n rules: rulesQuery.loading,\n residue: residueQuery.loading,\n coos: cooQuery.loading,\n flags: flagsQuery.loading,\n },\n errors: {\n overview: overviewQuery.error,\n ics: icsQuery.error,\n standards: standardsQuery.error,\n rules: rulesQuery.error,\n residue: residueQuery.error,\n coos: cooQuery.error,\n flags: flagsQuery.error,\n },\n\n refetchAll: useCallback(\n () => reconcile(refetchOverview, refetchIcs, refetchFlags, refetchRules, refetchResidue, refetchCoos),\n [reconcile, refetchOverview, refetchIcs, refetchFlags, refetchRules, refetchResidue, refetchCoos]\n ),\n\n // ICS\n createIcsGroup: useCallback(\n (input: Record<string, unknown>) =>\n run(createIcsGroupMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, createIcsGroupMutation, withCtx, refetchIcs, refetchOverview]\n ),\n updateIcsGroup: useCallback(\n (input: Record<string, unknown>) => run(updateIcsGroupMutation, { input: withCtx(input) }, [refetchIcs]),\n [run, updateIcsGroupMutation, withCtx, refetchIcs]\n ),\n deleteIcsGroup: useCallback(\n (id: string) => run(deleteIcsGroupMutation, { id, context: ctx }, [refetchIcs, refetchOverview]),\n [run, deleteIcsGroupMutation, ctx, refetchIcs, refetchOverview]\n ),\n createIcsGrower: useCallback(\n (input: Record<string, unknown>) =>\n run(createIcsGrowerMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, createIcsGrowerMutation, withCtx, refetchIcs, refetchOverview]\n ),\n updateIcsGrower: useCallback(\n (input: Record<string, unknown>) => run(updateIcsGrowerMutation, { input: withCtx(input) }, [refetchIcs]),\n [run, updateIcsGrowerMutation, withCtx, refetchIcs]\n ),\n deleteIcsGrower: useCallback(\n (id: string) => run(deleteIcsGrowerMutation, { id, context: ctx }, [refetchIcs, refetchOverview]),\n [run, deleteIcsGrowerMutation, ctx, refetchIcs, refetchOverview]\n ),\n scheduleInspection: useCallback(\n (input: Record<string, unknown>) =>\n run(scheduleInspectionMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, scheduleInspectionMutation, withCtx, refetchIcs, refetchOverview]\n ),\n recordInspection: useCallback(\n (input: Record<string, unknown>) =>\n run(recordInspectionMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview, refetchFlags]),\n [run, recordInspectionMutation, withCtx, refetchIcs, refetchOverview, refetchFlags]\n ),\n\n // Standards\n applyStandard: useCallback(\n (certificationId: string, standardCode?: string) =>\n run(applyStandardMutation, { input: withCtx({ certificationId, ...(standardCode ? { standardCode } : {}) }) }, [\n refetchOverview,\n ]),\n [run, applyStandardMutation, withCtx, refetchOverview]\n ),\n updateChecklistItem: useCallback(\n (id: string, status: ChecklistStatus, documentId?: string | null) =>\n run(\n updateChecklistItemMutation,\n { input: withCtx({ id, status, ...(documentId !== undefined ? { documentId } : {}) }) },\n [refetchOverview, refetchFlags]\n ),\n [run, updateChecklistItemMutation, withCtx, refetchOverview, refetchFlags]\n ),\n\n // Lifecycle\n startRenewal: useCallback(\n (id: string) => run(startRenewalMutation, { id, context: ctx }, [refetchOverview, refetchFlags]),\n [run, startRenewalMutation, ctx, refetchOverview, refetchFlags]\n ),\n runScan: useCallback(async (): Promise<ScanResult | null> => {\n const res = await runScanMutation({ variables: { context: ctx } });\n if (res.error) throw res.error;\n await reconcile(refetchOverview, refetchFlags, refetchIcs);\n return res.data?.runHealthyBowlComplianceScan ?? null;\n }, [runScanMutation, ctx, reconcile, refetchOverview, refetchFlags, refetchIcs]),\n\n // Flags\n acknowledgeFlag: useCallback(\n (id: string) => run(ackFlagMutation, { id, context: ctx }, [refetchFlags, refetchOverview]),\n [run, ackFlagMutation, ctx, refetchFlags, refetchOverview]\n ),\n resolveFlag: useCallback(\n (id: string, resolution: string) =>\n run(resolveFlagMutation, { input: withCtx({ id, resolution }) }, [refetchFlags, refetchOverview]),\n [run, resolveFlagMutation, withCtx, refetchFlags, refetchOverview]\n ),\n dismissFlag: useCallback(\n (id: string, reason: string) =>\n run(dismissFlagMutation, { input: withCtx({ id, reason }) }, [refetchFlags, refetchOverview]),\n [run, dismissFlagMutation, withCtx, refetchFlags, refetchOverview]\n ),\n\n // Substances / residue\n createSubstanceRule: useCallback(\n (input: Record<string, unknown>) => run(createSubstanceRuleMutation, { input: withCtx(input) }, [refetchRules]),\n [run, createSubstanceRuleMutation, withCtx, refetchRules]\n ),\n deleteSubstanceRule: useCallback(\n (id: string) => run(deleteSubstanceRuleMutation, { id, context: ctx }, [refetchRules]),\n [run, deleteSubstanceRuleMutation, ctx, refetchRules]\n ),\n createResidueTest: useCallback(\n (input: Record<string, unknown>) =>\n run(createResidueTestMutation, { input: withCtx(input) }, [refetchResidue, refetchFlags, refetchOverview]),\n [run, createResidueTestMutation, withCtx, refetchResidue, refetchFlags, refetchOverview]\n ),\n deleteResidueTest: useCallback(\n (id: string) => run(deleteResidueTestMutation, { id, context: ctx }, [refetchResidue]),\n [run, deleteResidueTestMutation, ctx, refetchResidue]\n ),\n\n // Certificate of Origin\n generateCertificateOfOrigin: useCallback(\n async (\n input: Record<string, unknown>\n ): Promise<{ id: string; certificateNumber: string; status: string } | null> => {\n const res = await generateCooMutation({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile(refetchCoos);\n return res.data?.generateHealthyBowlCertificateOfOrigin ?? null;\n },\n [generateCooMutation, withCtx, reconcile, refetchCoos]\n ),\n attachCertificateOfOriginFile: useCallback(\n (id: string, fileId: string, fileName?: string) =>\n run(attachCooFileMutation, { input: withCtx({ id, fileId, ...(fileName ? { fileName } : {}) }) }, [\n refetchCoos,\n ]),\n [run, attachCooFileMutation, withCtx, refetchCoos]\n ),\n revokeCertificateOfOrigin: useCallback(\n (id: string) => run(revokeCooMutation, { id, context: ctx }, [refetchCoos]),\n [run, revokeCooMutation, ctx, refetchCoos]\n ),\n\n /** Documents for the pages that need a one-off query (detail views, PDF download). */\n documents: { GET_CERT_DETAIL, GET_ICS_GROUP_DETAIL, GET_ICS_GROWER_DETAIL, GET_COO_PDF },\n context: ctx,\n };\n}\n\nexport { GET_CERT_DETAIL, GET_ICS_GROUP_DETAIL, GET_ICS_GROWER_DETAIL, GET_COO_PDF, GET_FLAGS };\n\nexport interface IcsGroupDetailData {\n getHealthyBowlIcsGroupDetail: {\n group: IcsGroupSummary;\n certification: Pick<\n Certification,\n 'id' | 'name' | 'standard' | 'standardCode' | 'stage' | 'status' | 'expiryDate' | 'daysToExpiry' | 'expiringSoon'\n > | null;\n growers: IcsGrower[];\n inspections: IcsInspection[];\n rollup: IcsRollup;\n };\n}\n\nexport interface IcsGrowerDetailData {\n getHealthyBowlIcsGrowerDetail: {\n grower: IcsGrower;\n group: IcsGroupSummary;\n inspections: IcsInspection[];\n };\n}\n\nexport interface CertificationDetailData {\n getHealthyBowlCertificationDetail: CertificationDetail;\n}\n\nexport interface CooPdfData {\n getHealthyBowlCertificateOfOriginPdf: {\n id: string;\n certificateNumber: string;\n fileName: string;\n contentType: string;\n pdfBase64: string;\n };\n}\n"],"mappings":";;;;;AAoBA,IAAM,KAAwB,wCAgQxB,IAAc,iLAsBd,IAAuB;IACzB,EAAY;;;;GAMV,IAAc,4JAgBd,IAAoB,mKAepB,IAAgB,iTAuBhB,IAAgB,8OAehB,IAAqB;oBACP,EAAY;;;;;;;;GAU1B,KAAe,CAAG;;;;;;;;;;oBAUJ,EAAqB;uBAClB,EAAqB;gBAC5B,EAAY;8BACE,EAAkB;;;;GAM1C,KAAe,CAAG;;;;;;;kBAON,EAAc;sBACV,EAAkB;iBACvB,EAAc;;;GAKzB,IAAuB,CAAG;;;;;kBAKd,EAAc;sBACV,EAAkB;iBACvB,EAAc;;;GAKzB,IAAwB,CAAG;;;iBAGhB,EAAc;;sBAET,EAAkB;;;GAKlC,KAAgB,CAAG;;;;;;;;;;;;;;;;;GAmBnB,IAAkB,CAAG;;sEAE2C,EAAmB;;GAInF,KAAY,CAAG;;uFAEkE,EAAY;;GAI7F,KAAsB,CAAG;;;;;;;;;;;;;;;;GAkBzB,KAAoB,CAAG;;;;;;;;;;;;;;GAgBvB,KAAW,CAAG;;;;;;;;;;;;;;;;;;;;;;;GAyBd,IAAc,CAAG;;;;;;;;;;GAYjB,KAAmB,CAAG;;;;;;;;;GAUtB,KAAmB,CAAG;;;;;;;;;GAUtB,KAAmB,CAAG;;;;GAKtB,IAAoB,CAAG;;;;;;;;GASvB,KAAoB,CAAG;;;;;;;;GASvB,IAAoB,CAAG;;;;GAKvB,KAAsB,CAAG;;;;;;;;GASzB,KAAoB,CAAG;;;;;;;;GASvB,KAAiB,CAAG;;;;;;;;;GAUpB,KAAwB,CAAG;;;;;;;;GAS3B,KAAgB,CAAG;;;;;;;;;GAUnB,KAAW,CAAG;;;;;;;;;;;;;;;GAgBd,KAAW,CAAG;;;;;;;GAQd,KAAe,CAAG;;;;;;;;GASlB,KAAe,CAAG;;;;;;;;GAS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AAO,OAAM,EAAI;AAEzB,UADA,MAAM,EAAU,EAAY,EACrB,EAAI,MAAM,0CAA0C;KAE7D;GAAC;GAAqB;GAAS;GAAW;GAAY,CACvD;EACD,+BAA+B,GAC5B,GAAY,GAAgB,MAC3B,EAAI,GAAuB,EAAE,OAAO,EAAQ;GAAE;GAAI;GAAQ,GAAI,IAAW,EAAE,aAAU,GAAG,EAAE;GAAG,CAAC,EAAE,EAAE,CAChG,EACD,CAAC,EACJ;GAAC;GAAK;GAAuB;GAAS;GAAY,CACnD;EACD,2BAA2B,GACxB,MAAe,EAAI,GAAmB;GAAE;GAAI,SAAS;GAAK,EAAE,CAAC,EAAY,CAAC,EAC3E;GAAC;GAAK;GAAmB;GAAK;GAAY,CAC3C;EAGD,WAAW;GAAE;GAAiB;GAAsB;GAAuB;GAAa;EACxF,SAAS;EACV"}
|
|
1
|
+
{"version":3,"file":"useHealthyBowlCompliance.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlCompliance.ts"],"sourcesContent":["/**\n * Certification & Compliance depth (NPOP / GLOBALG.A.P. / EUDR) + Internal Control System.\n * Roadmap 10 · BOFF-2882.\n *\n * Documents are declared inline with `gql` rather than as `src/operations/wspace/*.graphql`\n * files, because codegen validates operation documents against the committed\n * `graphql/wspace.graphql` snapshot — which is pulled from the gateway and so cannot know\n * about these fields until the subgraph is live in the supergraph. This is the same\n * escape hatch `useHealthyBowlData` already uses (see CREATE_COMPLIANCE_DOCUMENT_DOC).\n * Types below mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/compliance.gql`.\n *\n * Reads use `cache-and-network`; every write refetches the reads it invalidates, matching\n * the reconciliation contract in `useHealthyBowlData`.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\nconst FALLBACK_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001';\n\n// ── types (mirror compliance.gql) ──────────────────────────────────────────\n\nexport type FlagSeverity = 'INFO' | 'WARNING' | 'CRITICAL';\nexport type FlagStatus = 'OPEN' | 'ACKNOWLEDGED' | 'RESOLVED' | 'DISMISSED';\nexport type FlagType =\n 'BANNED_SUBSTANCE' | 'MRL_EXCEEDED' | 'CERT_EXPIRING' | 'CERT_EXPIRED' | 'INSPECTION_OVERDUE' | 'DOCUMENT_MISSING';\n\nexport type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH';\nexport type ChecklistStatus = 'MISSING' | 'UPLOADED' | 'UNDER_REVIEW' | 'APPROVED' | 'REJECTED' | 'NOT_APPLICABLE';\nexport type InspectionStatus = 'SCHEDULED' | 'DRAFT' | 'PASSED' | 'CONDITIONAL' | 'FAILED';\nexport type ChecklistResult = 'PASS' | 'FAIL' | 'NA';\n\nexport interface ComplianceFlag {\n id: string;\n type: FlagType;\n severity: FlagSeverity;\n status: FlagStatus;\n title: string;\n message: string;\n entityType: string;\n entityId: string | null;\n detectedAt: string;\n resolvedAt: string | null;\n resolvedBy: string | null;\n resolution: string | null;\n metadata: Record<string, unknown> | null;\n}\n\n/** The `Certification` type. */\nexport interface Certification {\n id: string;\n name: string;\n body: string;\n standard: string;\n standardCode: string | null;\n stage: string;\n icsGroupId: string | null;\n issueDate: string;\n expiryDate: string;\n status: string;\n scope: string[];\n daysToExpiry: number;\n expiringSoon: boolean;\n renewalStartedAt: string | null;\n}\n\n/** A `Certification` plus its computed checklist progress (dashboard standards row). */\nexport interface CertificationStandardProgress extends Certification {\n progressPercent: number;\n checklistTotal: number;\n checklistApproved: number;\n}\n\nexport interface IcsInspection {\n id: string;\n icsGroupId: string;\n growerId: string;\n inspectionDate: string;\n inspectorName: string;\n status: InspectionStatus;\n checklist: Array<{ key: string; label: string; result: ChecklistResult; note: string | null }> | null;\n notes: string | null;\n latitude: number | null;\n longitude: number | null;\n photoFileIds: string[];\n findingsCount: number;\n}\n\nexport interface IcsGrower {\n id: string;\n icsGroupId: string;\n memberCode: string;\n fullName: string;\n village: string;\n district: string | null;\n mobile: string | null;\n primaryCrop: string | null;\n plotAreaHectares: number | null;\n conversionStatus: string;\n riskLevel: RiskLevel;\n latitude: number | null;\n longitude: number | null;\n plots: unknown;\n active: boolean;\n lastInspectionDate: string | null;\n lastInspectionStatus: InspectionStatus | null;\n nextInspectionDate: string | null;\n inspectionOverdue: boolean;\n inspectionCount: number;\n}\n\nexport interface IcsGroupSummary {\n id: string;\n name: string;\n code: string;\n registrationNumber: string | null;\n contactPerson: string | null;\n contactPhone: string | null;\n description: string | null;\n status: string;\n certificationId: string | null;\n createdAt: string;\n growerCount: number;\n highRiskCount: number;\n inspectionsOverdue: number;\n totalPlotAreaHectares: number;\n}\n\nexport interface IcsRollup {\n totalGroups: number;\n totalGrowers: number;\n lowRisk: number;\n mediumRisk: number;\n highRisk: number;\n inspectionsPassed: number;\n inspectionsFailed: number;\n inspectionsConditional: number;\n inspectionsScheduled: number;\n inspectionsOverdue: number;\n growersNeverInspected: number;\n totalPlotAreaHectares: number;\n}\n\nexport interface ComplianceOverview {\n activeCertifications: number;\n expiringCertifications: number;\n expiredCertifications: number;\n icsMemberGrowers: number;\n openAuditFindings: number;\n openFlags: number;\n criticalFlags: number;\n standards: CertificationStandardProgress[];\n expiringSoon: CertificationStandardProgress[];\n flags: ComplianceFlag[];\n upcomingInspections: IcsInspection[];\n updatedAt: string;\n}\n\nexport interface StandardTemplateItem {\n code: string;\n label: string;\n description: string;\n required: boolean;\n orderIndex: number;\n}\n\nexport interface StandardTemplate {\n code: string;\n name: string;\n fullName: string;\n issuerHint: string;\n description: string;\n items: StandardTemplateItem[];\n}\n\nexport interface ChecklistItem {\n id: string;\n code: string;\n label: string;\n description: string | null;\n required: boolean;\n status: ChecklistStatus;\n documentId: string | null;\n orderIndex: number;\n completedAt: string | null;\n}\n\nexport interface CertificationDetail {\n certification: Certification;\n standard: StandardTemplate | null;\n checklistItems: ChecklistItem[];\n documents: Array<{\n id: string;\n name: string;\n type: string;\n status: string;\n uploadedDate: string;\n fileId: string | null;\n fileName: string | null;\n fileUrl: string | null;\n }>;\n progressPercent: number;\n requiredCount: number;\n approvedCount: number;\n missingCount: number;\n}\n\nexport interface SubstanceRule {\n id: string;\n substanceName: string;\n activeIngredient: string | null;\n casNumber: string | null;\n standardCode: string | null;\n prohibited: boolean;\n mrlMgPerKg: number | null;\n cropScope: string | null;\n source: string;\n notes: string | null;\n builtin: boolean;\n}\n\nexport interface ResidueTest {\n id: string;\n traceBatchId: string | null;\n cropId: string | null;\n substanceName: string;\n measuredMgPerKg: number;\n testedAt: string;\n laboratory: string | null;\n reportFileId: string | null;\n notes: string | null;\n}\n\nexport interface CertificateOfOrigin {\n id: string;\n certificateNumber: string;\n traceBatchId: string;\n issuedDate: string;\n exporterName: string;\n consigneeName: string | null;\n destinationCountry: string | null;\n productDescription: string;\n quantity: number;\n unit: string;\n hsCode: string | null;\n originCountry: string;\n originRegion: string | null;\n certificationIds: string[];\n declaration: string;\n status: string;\n fileId: string | null;\n fileName: string | null;\n}\n\nexport interface ScanResult {\n scannedAt: string;\n newFlags: number;\n totalOpenFlags: number;\n certificationsExpiring: number;\n certificationsExpired: number;\n bannedSubstanceFlags: number;\n mrlFlags: number;\n overdueInspections: number;\n missingDocuments: number;\n /** BOFF-6108: compliance documents cascaded to Expired by this run's certificate expiry. */\n documentsExpired: number;\n notificationsSent: number;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\n// ── documents ──────────────────────────────────────────────────────────────\n\n/** Fields on the `Certification` type itself. */\nconst CERT_FIELDS = `\n id\n name\n body\n standard\n standardCode\n stage\n icsGroupId\n issueDate\n expiryDate\n status\n scope\n daysToExpiry\n expiringSoon\n renewalStartedAt\n`;\n\n/**\n * `CertificationStandardProgress` = Certification + the computed checklist progress.\n * These extra fields exist ONLY on that type, not on `Certification` — selecting them\n * inside `CertificationDetail.certification` is a validation error.\n */\nconst CERT_PROGRESS_FIELDS = `\n ${CERT_FIELDS}\n progressPercent\n checklistTotal\n checklistApproved\n`;\n\nconst FLAG_FIELDS = `\n id\n type\n severity\n status\n title\n message\n entityType\n entityId\n detectedAt\n resolvedAt\n resolvedBy\n resolution\n metadata\n`;\n\nconst INSPECTION_FIELDS = `\n id\n icsGroupId\n growerId\n inspectionDate\n inspectorName\n status\n checklist\n notes\n latitude\n longitude\n photoFileIds\n findingsCount\n`;\n\nconst GROWER_FIELDS = `\n id\n icsGroupId\n memberCode\n fullName\n village\n district\n mobile\n primaryCrop\n plotAreaHectares\n conversionStatus\n riskLevel\n latitude\n longitude\n plots\n active\n lastInspectionDate\n lastInspectionStatus\n nextInspectionDate\n inspectionOverdue\n inspectionCount\n`;\n\nconst ROLLUP_FIELDS = `\n totalGroups\n totalGrowers\n lowRisk\n mediumRisk\n highRisk\n inspectionsPassed\n inspectionsFailed\n inspectionsConditional\n inspectionsScheduled\n inspectionsOverdue\n growersNeverInspected\n totalPlotAreaHectares\n`;\n\nconst CERT_DETAIL_FIELDS = `\n certification { ${CERT_FIELDS} }\n standard { code name fullName issuerHint description items { code label description required orderIndex } }\n checklistItems { id code label description required status documentId orderIndex completedAt }\n documents { id name type status uploadedDate fileId fileName fileUrl }\n progressPercent\n requiredCount\n approvedCount\n missingCount\n`;\n\nconst GET_OVERVIEW = gql`\n query GetHealthyBowlComplianceOverview($context: ContextInput!) {\n getHealthyBowlComplianceOverview(context: $context) {\n activeCertifications\n expiringCertifications\n expiredCertifications\n icsMemberGrowers\n openAuditFindings\n openFlags\n criticalFlags\n standards { ${CERT_PROGRESS_FIELDS} }\n expiringSoon { ${CERT_PROGRESS_FIELDS} }\n flags { ${FLAG_FIELDS} }\n upcomingInspections { ${INSPECTION_FIELDS} }\n updatedAt\n }\n }\n`;\n\nconst GET_ICS_DATA = gql`\n query GetHealthyBowlIcsData($context: ContextInput!) {\n getHealthyBowlIcsData(context: $context) {\n groups {\n id name code registrationNumber contactPerson contactPhone description status certificationId createdAt\n growerCount highRiskCount inspectionsOverdue totalPlotAreaHectares\n }\n growers { ${GROWER_FIELDS} }\n inspections { ${INSPECTION_FIELDS} }\n rollup { ${ROLLUP_FIELDS} }\n }\n }\n`;\n\nconst GET_ICS_GROUP_DETAIL = gql`\n query GetHealthyBowlIcsGroupDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlIcsGroupDetail(id: $id, context: $context) {\n group { id name code registrationNumber contactPerson contactPhone description status certificationId createdAt }\n certification { id name standard standardCode stage status expiryDate daysToExpiry expiringSoon }\n growers { ${GROWER_FIELDS} }\n inspections { ${INSPECTION_FIELDS} }\n rollup { ${ROLLUP_FIELDS} }\n }\n }\n`;\n\nconst GET_ICS_GROWER_DETAIL = gql`\n query GetHealthyBowlIcsGrowerDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlIcsGrowerDetail(id: $id, context: $context) {\n grower { ${GROWER_FIELDS} }\n group { id name code status certificationId createdAt }\n inspections { ${INSPECTION_FIELDS} }\n }\n }\n`;\n\nconst GET_STANDARDS = gql`\n query GetHealthyBowlCertificationStandards($context: ContextInput!) {\n getHealthyBowlCertificationStandards(context: $context) {\n code\n name\n fullName\n issuerHint\n description\n items {\n code\n label\n description\n required\n orderIndex\n }\n }\n }\n`;\n\nconst GET_CERT_DETAIL = gql`\n query GetHealthyBowlCertificationDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlCertificationDetail(id: $id, context: $context) { ${CERT_DETAIL_FIELDS} }\n }\n`;\n\nconst GET_FLAGS = gql`\n query GetHealthyBowlComplianceFlags($context: ContextInput!, $status: String, $type: String) {\n getHealthyBowlComplianceFlags(context: $context, status: $status, type: $type) { ${FLAG_FIELDS} }\n }\n`;\n\nconst GET_SUBSTANCE_RULES = gql`\n query GetHealthyBowlSubstanceRules($context: ContextInput!) {\n getHealthyBowlSubstanceRules(context: $context) {\n id\n substanceName\n activeIngredient\n casNumber\n standardCode\n prohibited\n mrlMgPerKg\n cropScope\n source\n notes\n builtin\n }\n }\n`;\n\nconst GET_RESIDUE_TESTS = gql`\n query GetHealthyBowlResidueTests($context: ContextInput!) {\n getHealthyBowlResidueTests(context: $context) {\n id\n traceBatchId\n cropId\n substanceName\n measuredMgPerKg\n testedAt\n laboratory\n reportFileId\n notes\n }\n }\n`;\n\nconst GET_COOS = gql`\n query GetHealthyBowlCertificatesOfOrigin($context: ContextInput!) {\n getHealthyBowlCertificatesOfOrigin(context: $context) {\n id\n certificateNumber\n traceBatchId\n issuedDate\n exporterName\n consigneeName\n destinationCountry\n productDescription\n quantity\n unit\n hsCode\n originCountry\n originRegion\n certificationIds\n declaration\n status\n fileId\n fileName\n }\n }\n`;\n\nconst GET_COO_PDF = gql`\n query GetHealthyBowlCertificateOfOriginPdf($id: ID!, $context: ContextInput!) {\n getHealthyBowlCertificateOfOriginPdf(id: $id, context: $context) {\n id\n certificateNumber\n fileName\n contentType\n pdfBase64\n }\n }\n`;\n\nconst CREATE_ICS_GROUP = gql`\n mutation CreateHealthyBowlIcsGroup($input: CreateIcsGroupInput!) {\n createHealthyBowlIcsGroup(input: $input) {\n id\n name\n code\n status\n }\n }\n`;\nconst UPDATE_ICS_GROUP = gql`\n mutation UpdateHealthyBowlIcsGroup($input: UpdateIcsGroupInput!) {\n updateHealthyBowlIcsGroup(input: $input) {\n id\n name\n code\n status\n }\n }\n`;\nconst DELETE_ICS_GROUP = gql`\n mutation DeleteHealthyBowlIcsGroup($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlIcsGroup(id: $id, context: $context)\n }\n`;\nconst CREATE_ICS_GROWER = gql`\n mutation CreateHealthyBowlIcsGrower($input: CreateIcsGrowerInput!) {\n createHealthyBowlIcsGrower(input: $input) {\n id\n fullName\n riskLevel\n }\n }\n`;\nconst UPDATE_ICS_GROWER = gql`\n mutation UpdateHealthyBowlIcsGrower($input: UpdateIcsGrowerInput!) {\n updateHealthyBowlIcsGrower(input: $input) {\n id\n fullName\n riskLevel\n }\n }\n`;\nconst DELETE_ICS_GROWER = gql`\n mutation DeleteHealthyBowlIcsGrower($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlIcsGrower(id: $id, context: $context)\n }\n`;\nconst SCHEDULE_INSPECTION = gql`\n mutation ScheduleHealthyBowlIcsInspection($input: ScheduleIcsInspectionInput!) {\n scheduleHealthyBowlIcsInspection(input: $input) {\n id\n status\n inspectionDate\n }\n }\n`;\nconst RECORD_INSPECTION = gql`\n mutation RecordHealthyBowlIcsInspection($input: RecordIcsInspectionInput!) {\n recordHealthyBowlIcsInspection(input: $input) {\n id\n status\n findingsCount\n }\n }\n`;\nconst APPLY_STANDARD = gql`\n mutation ApplyHealthyBowlCertificationStandard($input: ApplyCertificationStandardInput!) {\n applyHealthyBowlCertificationStandard(input: $input) {\n progressPercent\n requiredCount\n approvedCount\n missingCount\n }\n }\n`;\nconst UPDATE_CHECKLIST_ITEM = gql`\n mutation UpdateHealthyBowlCertificationChecklistItem($input: UpdateChecklistItemInput!) {\n updateHealthyBowlCertificationChecklistItem(input: $input) {\n progressPercent\n approvedCount\n missingCount\n }\n }\n`;\nconst START_RENEWAL = gql`\n mutation StartHealthyBowlCertificationRenewal($id: ID!, $context: ContextInput!) {\n startHealthyBowlCertificationRenewal(id: $id, context: $context) {\n id\n status\n stage\n renewalStartedAt\n }\n }\n`;\nconst RUN_SCAN = gql`\n mutation RunHealthyBowlComplianceScan($context: ContextInput!) {\n runHealthyBowlComplianceScan(context: $context) {\n scannedAt\n newFlags\n totalOpenFlags\n certificationsExpiring\n certificationsExpired\n bannedSubstanceFlags\n mrlFlags\n overdueInspections\n missingDocuments\n documentsExpired\n notificationsSent\n }\n }\n`;\nconst ACK_FLAG = gql`\n mutation AcknowledgeHealthyBowlComplianceFlag($id: ID!, $context: ContextInput!) {\n acknowledgeHealthyBowlComplianceFlag(id: $id, context: $context) {\n id\n status\n }\n }\n`;\nconst RESOLVE_FLAG = gql`\n mutation ResolveHealthyBowlComplianceFlag($input: ResolveComplianceFlagInput!) {\n resolveHealthyBowlComplianceFlag(input: $input) {\n id\n status\n resolution\n }\n }\n`;\nconst DISMISS_FLAG = gql`\n mutation DismissHealthyBowlComplianceFlag($input: DismissComplianceFlagInput!) {\n dismissHealthyBowlComplianceFlag(input: $input) {\n id\n status\n resolution\n }\n }\n`;\nconst CREATE_SUBSTANCE_RULE = gql`\n mutation CreateHealthyBowlSubstanceRule($input: CreateComplianceSubstanceRuleInput!) {\n createHealthyBowlSubstanceRule(input: $input) {\n id\n substanceName\n }\n }\n`;\nconst DELETE_SUBSTANCE_RULE = gql`\n mutation DeleteHealthyBowlSubstanceRule($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlSubstanceRule(id: $id, context: $context)\n }\n`;\nconst CREATE_RESIDUE_TEST = gql`\n mutation CreateHealthyBowlResidueTest($input: CreateComplianceResidueTestInput!) {\n createHealthyBowlResidueTest(input: $input) {\n id\n substanceName\n measuredMgPerKg\n }\n }\n`;\nconst DELETE_RESIDUE_TEST = gql`\n mutation DeleteHealthyBowlResidueTest($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlResidueTest(id: $id, context: $context)\n }\n`;\nconst GENERATE_COO = gql`\n mutation GenerateHealthyBowlCertificateOfOrigin($input: GenerateCertificateOfOriginInput!) {\n generateHealthyBowlCertificateOfOrigin(input: $input) {\n id\n certificateNumber\n status\n }\n }\n`;\nconst ATTACH_COO_FILE = gql`\n mutation AttachHealthyBowlCertificateOfOriginFile($input: AttachCertificateOfOriginFileInput!) {\n attachHealthyBowlCertificateOfOriginFile(input: $input) {\n id\n fileId\n fileName\n }\n }\n`;\nconst REVOKE_COO = gql`\n mutation RevokeHealthyBowlCertificateOfOrigin($id: ID!, $context: ContextInput!) {\n revokeHealthyBowlCertificateOfOrigin(id: $id, context: $context) {\n id\n status\n }\n }\n`;\n\n// ── hook ───────────────────────────────────────────────────────────────────\n\nexport interface UseComplianceOptions {\n /** Skip the ICS / rules / residue / CoO reads on pages that only need the overview. */\n skipSecondary?: boolean;\n}\n\nexport function useHealthyBowlCompliance(options: UseComplianceOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const ctx = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n const skip = options.skipSecondary === true;\n\n const overviewQuery = useQuery<{ getHealthyBowlComplianceOverview: ComplianceOverview }, { context: HbContext }>(\n GET_OVERVIEW,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network' }\n );\n\n const icsQuery = useQuery<\n {\n getHealthyBowlIcsData: {\n groups: IcsGroupSummary[];\n growers: IcsGrower[];\n inspections: IcsInspection[];\n rollup: IcsRollup;\n };\n },\n { context: HbContext }\n >(GET_ICS_DATA, { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip });\n\n const standardsQuery = useQuery<{ getHealthyBowlCertificationStandards: StandardTemplate[] }, { context: HbContext }>(\n GET_STANDARDS,\n { variables: { context: ctx }, fetchPolicy: 'cache-first', skip }\n );\n\n const rulesQuery = useQuery<{ getHealthyBowlSubstanceRules: SubstanceRule[] }, { context: HbContext }>(\n GET_SUBSTANCE_RULES,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const residueQuery = useQuery<{ getHealthyBowlResidueTests: ResidueTest[] }, { context: HbContext }>(\n GET_RESIDUE_TESTS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const cooQuery = useQuery<{ getHealthyBowlCertificatesOfOrigin: CertificateOfOrigin[] }, { context: HbContext }>(\n GET_COOS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const flagsQuery = useQuery<\n { getHealthyBowlComplianceFlags: ComplianceFlag[] },\n { context: HbContext; status?: string | null; type?: string | null }\n >(GET_FLAGS, { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip });\n\n const refetchOverview = overviewQuery.refetch;\n const refetchIcs = icsQuery.refetch;\n const refetchFlags = flagsQuery.refetch;\n const refetchRules = rulesQuery.refetch;\n const refetchResidue = residueQuery.refetch;\n const refetchCoos = cooQuery.refetch;\n\n /** Reconcile the reads a write invalidates. Non-fatal: the next load reconciles anyway. */\n const reconcile = useCallback(async (...refetchers: Array<() => Promise<unknown>>) => {\n await Promise.all(\n refetchers.map((run) =>\n run().catch(() => {\n /* non-fatal */\n })\n )\n );\n }, []);\n\n const [createIcsGroupMutation] = useMutation(CREATE_ICS_GROUP);\n const [updateIcsGroupMutation] = useMutation(UPDATE_ICS_GROUP);\n const [deleteIcsGroupMutation] = useMutation(DELETE_ICS_GROUP);\n const [createIcsGrowerMutation] = useMutation(CREATE_ICS_GROWER);\n const [updateIcsGrowerMutation] = useMutation(UPDATE_ICS_GROWER);\n const [deleteIcsGrowerMutation] = useMutation(DELETE_ICS_GROWER);\n const [scheduleInspectionMutation] = useMutation(SCHEDULE_INSPECTION);\n const [recordInspectionMutation] = useMutation(RECORD_INSPECTION);\n const [applyStandardMutation] = useMutation(APPLY_STANDARD);\n const [updateChecklistItemMutation] = useMutation(UPDATE_CHECKLIST_ITEM);\n const [startRenewalMutation] = useMutation(START_RENEWAL);\n // Typed: these two are the only mutations whose response payload a caller reads back.\n const [runScanMutation] = useMutation<{ runHealthyBowlComplianceScan: ScanResult }, { context: HbContext }>(RUN_SCAN);\n const [ackFlagMutation] = useMutation(ACK_FLAG);\n const [resolveFlagMutation] = useMutation(RESOLVE_FLAG);\n const [dismissFlagMutation] = useMutation(DISMISS_FLAG);\n const [createSubstanceRuleMutation] = useMutation(CREATE_SUBSTANCE_RULE);\n const [deleteSubstanceRuleMutation] = useMutation(DELETE_SUBSTANCE_RULE);\n const [createResidueTestMutation] = useMutation(CREATE_RESIDUE_TEST);\n const [deleteResidueTestMutation] = useMutation(DELETE_RESIDUE_TEST);\n const [generateCooMutation] = useMutation<\n { generateHealthyBowlCertificateOfOrigin: { id: string; certificateNumber: string; status: string } },\n { input: Record<string, unknown> }\n >(GENERATE_COO);\n const [attachCooFileMutation] = useMutation(ATTACH_COO_FILE);\n const [revokeCooMutation] = useMutation(REVOKE_COO);\n\n /**\n * Fire a mutation, surface its error, then reconcile the reads it invalidates.\n * Returns `unknown` because the callers below ignore the payload; the two mutations\n * whose payload IS read (runScan, generateCertificateOfOrigin) are typed and called directly.\n */\n const run = useCallback(\n async (\n mutate: (opts: { variables: Record<string, unknown> }) => Promise<{ data?: unknown; error?: unknown }>,\n variables: Record<string, unknown>,\n after: Array<() => Promise<unknown>>\n ): Promise<unknown> => {\n const res = await mutate({ variables });\n if (res.error) {\n throw res.error instanceof Error ? res.error : new Error(String(res.error));\n }\n await reconcile(...after);\n return res.data;\n },\n [reconcile]\n );\n\n const withCtx = useCallback((input: Record<string, unknown>) => ({ ...input, context: ctx }), [ctx]);\n\n return {\n overview: overviewQuery.data?.getHealthyBowlComplianceOverview ?? null,\n ics: icsQuery.data?.getHealthyBowlIcsData ?? null,\n standards: standardsQuery.data?.getHealthyBowlCertificationStandards ?? [],\n substanceRules: rulesQuery.data?.getHealthyBowlSubstanceRules ?? [],\n residueTests: residueQuery.data?.getHealthyBowlResidueTests ?? [],\n certificatesOfOrigin: cooQuery.data?.getHealthyBowlCertificatesOfOrigin ?? [],\n flags: flagsQuery.data?.getHealthyBowlComplianceFlags ?? [],\n\n loading: {\n overview: overviewQuery.loading,\n ics: icsQuery.loading,\n standards: standardsQuery.loading,\n rules: rulesQuery.loading,\n residue: residueQuery.loading,\n coos: cooQuery.loading,\n flags: flagsQuery.loading,\n },\n errors: {\n overview: overviewQuery.error,\n ics: icsQuery.error,\n standards: standardsQuery.error,\n rules: rulesQuery.error,\n residue: residueQuery.error,\n coos: cooQuery.error,\n flags: flagsQuery.error,\n },\n\n refetchAll: useCallback(\n () => reconcile(refetchOverview, refetchIcs, refetchFlags, refetchRules, refetchResidue, refetchCoos),\n [reconcile, refetchOverview, refetchIcs, refetchFlags, refetchRules, refetchResidue, refetchCoos]\n ),\n\n // ICS\n createIcsGroup: useCallback(\n (input: Record<string, unknown>) =>\n run(createIcsGroupMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, createIcsGroupMutation, withCtx, refetchIcs, refetchOverview]\n ),\n updateIcsGroup: useCallback(\n (input: Record<string, unknown>) => run(updateIcsGroupMutation, { input: withCtx(input) }, [refetchIcs]),\n [run, updateIcsGroupMutation, withCtx, refetchIcs]\n ),\n deleteIcsGroup: useCallback(\n (id: string) => run(deleteIcsGroupMutation, { id, context: ctx }, [refetchIcs, refetchOverview]),\n [run, deleteIcsGroupMutation, ctx, refetchIcs, refetchOverview]\n ),\n createIcsGrower: useCallback(\n (input: Record<string, unknown>) =>\n run(createIcsGrowerMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, createIcsGrowerMutation, withCtx, refetchIcs, refetchOverview]\n ),\n updateIcsGrower: useCallback(\n (input: Record<string, unknown>) => run(updateIcsGrowerMutation, { input: withCtx(input) }, [refetchIcs]),\n [run, updateIcsGrowerMutation, withCtx, refetchIcs]\n ),\n deleteIcsGrower: useCallback(\n (id: string) => run(deleteIcsGrowerMutation, { id, context: ctx }, [refetchIcs, refetchOverview]),\n [run, deleteIcsGrowerMutation, ctx, refetchIcs, refetchOverview]\n ),\n scheduleInspection: useCallback(\n (input: Record<string, unknown>) =>\n run(scheduleInspectionMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, scheduleInspectionMutation, withCtx, refetchIcs, refetchOverview]\n ),\n recordInspection: useCallback(\n (input: Record<string, unknown>) =>\n run(recordInspectionMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview, refetchFlags]),\n [run, recordInspectionMutation, withCtx, refetchIcs, refetchOverview, refetchFlags]\n ),\n\n // Standards\n applyStandard: useCallback(\n (certificationId: string, standardCode?: string) =>\n run(applyStandardMutation, { input: withCtx({ certificationId, ...(standardCode ? { standardCode } : {}) }) }, [\n refetchOverview,\n ]),\n [run, applyStandardMutation, withCtx, refetchOverview]\n ),\n updateChecklistItem: useCallback(\n (id: string, status: ChecklistStatus, documentId?: string | null) =>\n run(\n updateChecklistItemMutation,\n { input: withCtx({ id, status, ...(documentId !== undefined ? { documentId } : {}) }) },\n [refetchOverview, refetchFlags]\n ),\n [run, updateChecklistItemMutation, withCtx, refetchOverview, refetchFlags]\n ),\n\n // Lifecycle\n startRenewal: useCallback(\n (id: string) => run(startRenewalMutation, { id, context: ctx }, [refetchOverview, refetchFlags]),\n [run, startRenewalMutation, ctx, refetchOverview, refetchFlags]\n ),\n runScan: useCallback(async (): Promise<ScanResult | null> => {\n const res = await runScanMutation({ variables: { context: ctx } });\n if (res.error) throw res.error;\n await reconcile(refetchOverview, refetchFlags, refetchIcs);\n return res.data?.runHealthyBowlComplianceScan ?? null;\n }, [runScanMutation, ctx, reconcile, refetchOverview, refetchFlags, refetchIcs]),\n\n // Flags\n acknowledgeFlag: useCallback(\n (id: string) => run(ackFlagMutation, { id, context: ctx }, [refetchFlags, refetchOverview]),\n [run, ackFlagMutation, ctx, refetchFlags, refetchOverview]\n ),\n resolveFlag: useCallback(\n (id: string, resolution: string) =>\n run(resolveFlagMutation, { input: withCtx({ id, resolution }) }, [refetchFlags, refetchOverview]),\n [run, resolveFlagMutation, withCtx, refetchFlags, refetchOverview]\n ),\n dismissFlag: useCallback(\n (id: string, reason: string) =>\n run(dismissFlagMutation, { input: withCtx({ id, reason }) }, [refetchFlags, refetchOverview]),\n [run, dismissFlagMutation, withCtx, refetchFlags, refetchOverview]\n ),\n\n // Substances / residue\n createSubstanceRule: useCallback(\n (input: Record<string, unknown>) => run(createSubstanceRuleMutation, { input: withCtx(input) }, [refetchRules]),\n [run, createSubstanceRuleMutation, withCtx, refetchRules]\n ),\n deleteSubstanceRule: useCallback(\n (id: string) => run(deleteSubstanceRuleMutation, { id, context: ctx }, [refetchRules]),\n [run, deleteSubstanceRuleMutation, ctx, refetchRules]\n ),\n createResidueTest: useCallback(\n (input: Record<string, unknown>) =>\n run(createResidueTestMutation, { input: withCtx(input) }, [refetchResidue, refetchFlags, refetchOverview]),\n [run, createResidueTestMutation, withCtx, refetchResidue, refetchFlags, refetchOverview]\n ),\n deleteResidueTest: useCallback(\n (id: string) => run(deleteResidueTestMutation, { id, context: ctx }, [refetchResidue]),\n [run, deleteResidueTestMutation, ctx, refetchResidue]\n ),\n\n // Certificate of Origin\n generateCertificateOfOrigin: useCallback(\n async (\n input: Record<string, unknown>\n ): Promise<{ id: string; certificateNumber: string; status: string } | null> => {\n const res = await generateCooMutation({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile(refetchCoos);\n return res.data?.generateHealthyBowlCertificateOfOrigin ?? null;\n },\n [generateCooMutation, withCtx, reconcile, refetchCoos]\n ),\n attachCertificateOfOriginFile: useCallback(\n (id: string, fileId: string, fileName?: string) =>\n run(attachCooFileMutation, { input: withCtx({ id, fileId, ...(fileName ? { fileName } : {}) }) }, [\n refetchCoos,\n ]),\n [run, attachCooFileMutation, withCtx, refetchCoos]\n ),\n revokeCertificateOfOrigin: useCallback(\n (id: string) => run(revokeCooMutation, { id, context: ctx }, [refetchCoos]),\n [run, revokeCooMutation, ctx, refetchCoos]\n ),\n\n /** Documents for the pages that need a one-off query (detail views, PDF download). */\n documents: { GET_CERT_DETAIL, GET_ICS_GROUP_DETAIL, GET_ICS_GROWER_DETAIL, GET_COO_PDF },\n context: ctx,\n };\n}\n\nexport { GET_CERT_DETAIL, GET_ICS_GROUP_DETAIL, GET_ICS_GROWER_DETAIL, GET_COO_PDF, GET_FLAGS };\n\nexport interface IcsGroupDetailData {\n getHealthyBowlIcsGroupDetail: {\n group: IcsGroupSummary;\n certification: Pick<\n Certification,\n 'id' | 'name' | 'standard' | 'standardCode' | 'stage' | 'status' | 'expiryDate' | 'daysToExpiry' | 'expiringSoon'\n > | null;\n growers: IcsGrower[];\n inspections: IcsInspection[];\n rollup: IcsRollup;\n };\n}\n\nexport interface IcsGrowerDetailData {\n getHealthyBowlIcsGrowerDetail: {\n grower: IcsGrower;\n group: IcsGroupSummary;\n inspections: IcsInspection[];\n };\n}\n\nexport interface CertificationDetailData {\n getHealthyBowlCertificationDetail: CertificationDetail;\n}\n\nexport interface CooPdfData {\n getHealthyBowlCertificateOfOriginPdf: {\n id: string;\n certificateNumber: string;\n fileName: string;\n contentType: string;\n pdfBase64: string;\n };\n}\n"],"mappings":";;;;;AAoBA,IAAM,KAAwB,wCAkQxB,IAAc,iLAsBd,IAAuB;IACzB,EAAY;;;;GAMV,IAAc,4JAgBd,IAAoB,mKAepB,IAAgB,iTAuBhB,IAAgB,8OAehB,IAAqB;oBACP,EAAY;;;;;;;;GAU1B,KAAe,CAAG;;;;;;;;;;oBAUJ,EAAqB;uBAClB,EAAqB;gBAC5B,EAAY;8BACE,EAAkB;;;;GAM1C,KAAe,CAAG;;;;;;;kBAON,EAAc;sBACV,EAAkB;iBACvB,EAAc;;;GAKzB,IAAuB,CAAG;;;;;kBAKd,EAAc;sBACV,EAAkB;iBACvB,EAAc;;;GAKzB,IAAwB,CAAG;;;iBAGhB,EAAc;;sBAET,EAAkB;;;GAKlC,KAAgB,CAAG;;;;;;;;;;;;;;;;;GAmBnB,IAAkB,CAAG;;sEAE2C,EAAmB;;GAInF,KAAY,CAAG;;uFAEkE,EAAY;;GAI7F,KAAsB,CAAG;;;;;;;;;;;;;;;;GAkBzB,KAAoB,CAAG;;;;;;;;;;;;;;GAgBvB,KAAW,CAAG;;;;;;;;;;;;;;;;;;;;;;;GAyBd,IAAc,CAAG;;;;;;;;;;GAYjB,KAAmB,CAAG;;;;;;;;;GAUtB,KAAmB,CAAG;;;;;;;;;GAUtB,KAAmB,CAAG;;;;GAKtB,IAAoB,CAAG;;;;;;;;GASvB,KAAoB,CAAG;;;;;;;;GASvB,IAAoB,CAAG;;;;GAKvB,KAAsB,CAAG;;;;;;;;GASzB,KAAoB,CAAG;;;;;;;;GASvB,KAAiB,CAAG;;;;;;;;;GAUpB,KAAwB,CAAG;;;;;;;;GAS3B,KAAgB,CAAG;;;;;;;;;GAUnB,KAAW,CAAG;;;;;;;;;;;;;;;;GAiBd,KAAW,CAAG;;;;;;;GAQd,KAAe,CAAG;;;;;;;;GASlB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AC;AAC/E,OAAI,EAAI,MAAO,OAAM,EAAI;AAEzB,UADA,MAAM,EAAU,EAAY,EACrB,EAAI,MAAM,0CAA0C;KAE7D;GAAC;GAAqB;GAAS;GAAW;GAAY,CACvD;EACD,+BAA+B,GAC5B,GAAY,GAAgB,MAC3B,EAAI,GAAuB,EAAE,OAAO,EAAQ;GAAE;GAAI;GAAQ,GAAI,IAAW,EAAE,aAAU,GAAG,EAAE;GAAG,CAAC,EAAE,EAAE,CAChG,EACD,CAAC,EACJ;GAAC;GAAK;GAAuB;GAAS;GAAY,CACnD;EACD,2BAA2B,GACxB,MAAe,EAAI,GAAmB;GAAE;GAAI,SAAS;GAAK,EAAE,CAAC,EAAY,CAAC,EAC3E;GAAC;GAAK;GAAmB;GAAK;GAAY,CAC3C;EAGD,WAAW;GAAE;GAAiB;GAAsB;GAAuB;GAAa;EACxF,SAAS;EACV"}
|
|
@@ -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"}
|
|
@@ -28,12 +28,13 @@ var M = () => {
|
|
|
28
28
|
});
|
|
29
29
|
return;
|
|
30
30
|
}
|
|
31
|
+
let t = M("healthybowl.compliance.overview.scan.summary", "{{open}} open findings in total. {{sent}} notifications sent.", {
|
|
32
|
+
open: e.totalOpenFlags,
|
|
33
|
+
sent: e.notificationsSent
|
|
34
|
+
}), n = e.documentsExpired > 0 ? `${t} ${M("healthybowl.compliance.overview.scan.documentsExpired", "{{count}} linked document(s) moved to Expired.", { count: e.documentsExpired })}` : t;
|
|
31
35
|
F({
|
|
32
36
|
title: e.newFlags > 0 ? M("healthybowl.compliance.overview.scan.found", "{{count}} new compliance findings", { count: e.newFlags }) : M("healthybowl.compliance.overview.scan.clean", "No new findings"),
|
|
33
|
-
description:
|
|
34
|
-
open: e.totalOpenFlags,
|
|
35
|
-
sent: e.notificationsSent
|
|
36
|
-
}),
|
|
37
|
+
description: n,
|
|
37
38
|
variant: e.newFlags > 0 ? "warning" : "success"
|
|
38
39
|
});
|
|
39
40
|
} catch (e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ComplianceOverviewPage.js","names":[],"sources":["../../../../src/healthybowl/pages/compliance/ComplianceOverviewPage.tsx"],"sourcesContent":["/**\n * Compliance & Certification — Internal Control System (ICS) dashboard.\n * Roadmap 10 · BOFF-2882.\n */\nimport { useMemo, useState } from 'react';\nimport { useNavigate } from 'react-router';\nimport {\n AlertTriangle,\n ArrowRight,\n BadgeCheck,\n ClipboardCheck,\n FileText,\n RefreshCw,\n ShieldCheck,\n Users,\n} from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { PageLayout, StatCard, ErrorState, PageLoader, EmptyState } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { useBasePath } from '../../hooks/useBasePath';\nimport { useHealthyBowlCompliance } from '../../hooks/useHealthyBowlCompliance';\nimport type { CertificationStandardProgress } from '../../hooks/useHealthyBowlCompliance';\nimport { formatDate } from '../../utils/helpers';\nimport {\n ExpiryBadge,\n FLAG_TYPE_LABEL,\n ProgressRing,\n RiskDot,\n SeverityBadge,\n STAGE_LABEL,\n InspectionStatusText,\n stageTone,\n} from './components';\n\nexport const ComplianceOverviewPage = () => {\n const { t } = useI18n();\n const navigate = useNavigate();\n const { buildPath } = useBasePath();\n const { toast } = useToast();\n const { overview, ics, loading, errors, startRenewal, runScan, refetchAll } = useHealthyBowlCompliance();\n const [scanning, setScanning] = useState(false);\n const [renewingId, setRenewingId] = useState<string | null>(null);\n\n const growerRows = useMemo(() => (ics?.growers ?? []).slice(0, 6), [ics]);\n\n const handleScan = async () => {\n setScanning(true);\n try {\n const result = await runScan();\n if (!result) {\n toast({\n title: t('healthybowl.compliance.overview.scan.noResult', 'Scan returned no result'),\n variant: 'warning',\n });\n return;\n }\n toast({\n title:\n result.newFlags > 0\n ? t('healthybowl.compliance.overview.scan.found', '{{count}} new compliance findings', {\n count: result.newFlags,\n })\n : t('healthybowl.compliance.overview.scan.clean', 'No new findings'),\n description: t(\n 'healthybowl.compliance.overview.scan.summary',\n '{{open}} open findings in total. {{sent}} notifications sent.',\n { open: result.totalOpenFlags, sent: result.notificationsSent }\n ),\n variant: result.newFlags > 0 ? 'warning' : 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.compliance.overview.scan.failed', 'Compliance scan failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setScanning(false);\n }\n };\n\n const handleRenew = async (cert: CertificationStandardProgress) => {\n setRenewingId(cert.id);\n try {\n await startRenewal(cert.id);\n toast({\n title: t('healthybowl.compliance.overview.renew.started', 'Renewal started'),\n description: t('healthybowl.compliance.overview.renew.startedDesc', '{{name}} is now pending renewal.', {\n name: cert.name,\n }),\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.compliance.overview.renew.failed', 'Could not start the renewal'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setRenewingId(null);\n }\n };\n\n if (loading.overview && !overview) {\n return <PageLoader />;\n }\n if (errors.overview) {\n return (\n <PageLayout title={t('healthybowl.compliance.overview.title', 'Compliance & Certification')}>\n <ErrorState description={errors.overview.message} onRetry={() => void refetchAll()} />\n </PageLayout>\n );\n }\n\n const openFlags = overview?.flags.filter((flag) => flag.status === 'OPEN') ?? [];\n const topFlag = openFlags[0] ?? null;\n\n return (\n <PageLayout\n title={t('healthybowl.compliance.overview.title', 'Compliance & Certification')}\n description={t(\n 'healthybowl.compliance.overview.description',\n 'Internal Control System, per-standard progress, expiry alerts and residue checks.'\n )}\n purpose=\"See at a glance whether your farm or farmer group is certification-ready: which standards are complete, which certificates are about to lapse, which member growers still need an internal inspection, and whether any prohibited input or over-limit residue has been recorded.\"\n hero\n actions={\n <div className=\"flex flex-wrap gap-2\">\n <Button variant=\"outline\" onClick={() => navigate(buildPath('compliance/alerts'))}>\n <AlertTriangle className=\"h-4 w-4\" />\n {t('healthybowl.compliance.overview.actions.alerts', 'Alerts')}\n {openFlags.length > 0 ? (\n <span className=\"ms-1 rounded-full bg-status-error-bg/20 px-1.5 py-0.5 text-xs font-semibold text-status-error-text\">\n {openFlags.length}\n </span>\n ) : null}\n </Button>\n <Button onClick={handleScan} disabled={scanning}>\n <RefreshCw className={scanning ? 'h-4 w-4 animate-spin' : 'h-4 w-4'} />\n {scanning\n ? t('healthybowl.compliance.overview.actions.scanning', 'Scanning…')\n : t('healthybowl.compliance.overview.actions.scan', 'Run compliance scan')}\n </Button>\n </div>\n }\n >\n <div className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4\">\n <StatCard\n hero\n label={t('healthybowl.compliance.overview.stats.active', 'Active certifications')}\n value={overview?.activeCertifications ?? 0}\n icon={<ShieldCheck className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.compliance.overview.stats.expiring', 'Expiring in 90 days')}\n value={overview?.expiringCertifications ?? 0}\n icon={<AlertTriangle className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.compliance.overview.stats.growers', 'ICS member growers')}\n value={overview?.icsMemberGrowers ?? 0}\n icon={<Users className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.compliance.overview.stats.findings', 'Open audit findings')}\n value={overview?.openAuditFindings ?? 0}\n icon={<ClipboardCheck className=\"h-5 w-5\" />}\n />\n </div>\n\n <div className=\"mt-6 grid grid-cols-1 gap-6 xl:grid-cols-3\">\n {/* Certification standards */}\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5 xl:col-span-2\">\n <header className=\"mb-4 flex items-start justify-between gap-3\">\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">\n {t('healthybowl.compliance.overview.standards.title', 'Certification standards')}\n </h2>\n <p className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.compliance.overview.standards.subtitle',\n 'Completion is approved required documents ÷ required documents.'\n )}\n </p>\n </div>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => navigate(buildPath('compliance/certifications'))}>\n {t('healthybowl.compliance.overview.standards.manage', 'Manage')}\n <ArrowRight className=\"h-4 w-4\" />\n </Button>\n </header>\n\n {(overview?.standards.length ?? 0) === 0 ? (\n <EmptyState\n title={t('healthybowl.compliance.overview.standards.emptyTitle', 'No certifications yet')}\n description={t(\n 'healthybowl.compliance.overview.standards.emptyMessage',\n 'Add a certification to start tracking its document checklist and expiry.'\n )}\n action={\n <Button onClick={() => navigate(buildPath('compliance/certifications'))}>\n {t('healthybowl.compliance.overview.standards.add', 'Add certification')}\n </Button>\n }\n />\n ) : (\n <div className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n {overview?.standards.map((cert) => (\n <button\n key={cert.id}\n type=\"button\"\n onClick={() => navigate(buildPath(`compliance/certifications/${cert.id}`))}\n className=\"flex flex-col items-center gap-3 rounded-lg border border-border-subtle bg-bg-sunken p-4 text-center transition-colors hover:border-border-default\"\n >\n <div className=\"text-sm font-semibold text-text-primary\">{cert.name}</div>\n <div className=\"text-xs text-text-secondary\">\n {cert.standardCode ?? cert.standard} — {STAGE_LABEL[cert.stage] ?? cert.stage}\n </div>\n <ProgressRing\n percent={cert.progressPercent}\n tone={stageTone(cert.stage, cert.daysToExpiry)}\n label={`${cert.name} ${cert.progressPercent} percent complete`}\n />\n <ExpiryBadge daysToExpiry={cert.daysToExpiry} />\n {cert.expiringSoon || cert.daysToExpiry < 0 ? (\n <Button\n size=\"sm\"\n className=\"w-full\"\n disabled={renewingId === cert.id || cert.renewalStartedAt !== null}\n onClick={(e) => {\n e.stopPropagation();\n void handleRenew(cert);\n }}\n >\n {cert.renewalStartedAt !== null\n ? t('healthybowl.compliance.overview.standards.renewing', 'Renewal in progress')\n : t('healthybowl.compliance.overview.standards.renew', 'Renew')}\n </Button>\n ) : null}\n </button>\n ))}\n </div>\n )}\n </section>\n\n {/* ICS group certification */}\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <header className=\"mb-4 flex items-start justify-between gap-3\">\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">\n {t('healthybowl.compliance.overview.ics.title', 'ICS — group certification')}\n </h2>\n <p className=\"text-sm text-text-secondary\">\n {t('healthybowl.compliance.overview.ics.subtitle', 'Member growers by risk and inspection status.')}\n </p>\n </div>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.overview.ics.open', 'Open')}\n <ArrowRight className=\"h-4 w-4\" />\n </Button>\n </header>\n\n {loading.ics && !ics ? (\n <PageLoader />\n ) : growerRows.length === 0 ? (\n <EmptyState\n title={t('healthybowl.compliance.overview.ics.emptyTitle', 'No ICS group yet')}\n description={t(\n 'healthybowl.compliance.overview.ics.emptyMessage',\n 'Create an Internal Control System to certify member growers under one group certificate.'\n )}\n action={\n <Button onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.overview.ics.create', 'Create ICS group')}\n </Button>\n }\n />\n ) : (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"border-b border-border-subtle text-start text-xs uppercase tracking-wide text-text-secondary\">\n <th className=\"pb-2 pe-3 font-medium\">\n {t('healthybowl.compliance.overview.ics.grower', 'Grower')}\n </th>\n <th className=\"pb-2 pe-3 font-medium\">\n {t('healthybowl.compliance.overview.ics.village', 'Village')}\n </th>\n <th className=\"pb-2 pe-3 font-medium\">{t('healthybowl.compliance.overview.ics.risk', 'Risk')}</th>\n <th className=\"pb-2 font-medium\">\n {t('healthybowl.compliance.overview.ics.inspection', 'Inspection')}\n </th>\n </tr>\n </thead>\n <tbody>\n {growerRows.map((grower) => (\n <tr\n key={grower.id}\n className=\"cursor-pointer border-b border-border-subtle last:border-0 hover:bg-bg-sunken\"\n onClick={() => navigate(buildPath(`compliance/ics/growers/${grower.id}`))}\n >\n <td className=\"py-2.5 pe-3 font-medium text-text-primary\">{grower.fullName}</td>\n <td className=\"py-2.5 pe-3 text-text-secondary\">{grower.village}</td>\n <td className=\"py-2.5 pe-3\">\n <RiskDot level={grower.riskLevel} />\n </td>\n <td className=\"py-2.5\">\n <InspectionStatusText status={grower.lastInspectionStatus} overdue={grower.inspectionOverdue} />\n {grower.lastInspectionDate ? (\n <div className=\"text-xs text-text-secondary\">{formatDate(grower.lastInspectionDate)}</div>\n ) : null}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n </section>\n </div>\n\n {/* Findings + Certificate of Origin */}\n <section className=\"mt-6 rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <header className=\"mb-4 flex flex-wrap items-start justify-between gap-3\">\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">\n {t('healthybowl.compliance.overview.findings.title', 'Compliance findings')}\n </h2>\n <p className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.compliance.overview.findings.subtitle',\n 'Banned inputs, residue breaches, expiries and overdue inspections.'\n )}\n </p>\n </div>\n <Button variant=\"outline\" onClick={() => navigate(buildPath('compliance/origin'))}>\n <FileText className=\"h-4 w-4\" />\n {t('healthybowl.compliance.overview.findings.coo', 'Certificate of Origin')}\n </Button>\n </header>\n\n {openFlags.length === 0 ? (\n <div className=\"flex items-center gap-3 rounded-lg border border-border-subtle bg-bg-sunken px-4 py-6\">\n <BadgeCheck className=\"h-6 w-6 text-success\" />\n <div>\n <div className=\"font-medium text-text-primary\">\n {t('healthybowl.compliance.overview.findings.cleanTitle', 'No open findings')}\n </div>\n <div className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.compliance.overview.findings.cleanMessage',\n 'Nothing is currently blocking a certification or an export consignment.'\n )}\n </div>\n </div>\n </div>\n ) : (\n <ul className=\"space-y-3\">\n {openFlags.slice(0, 5).map((flag) => (\n <li\n key={flag.id}\n className=\"flex flex-wrap items-start justify-between gap-3 rounded-lg border border-border-subtle bg-bg-sunken px-4 py-3\"\n >\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <SeverityBadge severity={flag.severity} />\n <span className=\"text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {FLAG_TYPE_LABEL[flag.type] ?? flag.type}\n </span>\n </div>\n <div className=\"mt-1 font-medium text-text-primary\">{flag.title}</div>\n <p className=\"text-sm text-text-secondary\">{flag.message}</p>\n </div>\n <Button variant=\"outline\" size=\"sm\" onClick={() => navigate(buildPath('compliance/alerts'))}>\n {t('healthybowl.compliance.overview.findings.review', 'Review')}\n </Button>\n </li>\n ))}\n </ul>\n )}\n\n {topFlag && openFlags.length > 5 ? (\n <div className=\"mt-3 text-end\">\n <Button variant=\"ghost\" size=\"sm\" onClick={() => navigate(buildPath('compliance/alerts'))}>\n {t('healthybowl.compliance.overview.findings.all', 'See all {{count}} findings', {\n count: openFlags.length,\n })}\n <ArrowRight className=\"h-4 w-4\" />\n </Button>\n </div>\n ) : null}\n </section>\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,IAAa,UAA+B;CAC1C,IAAM,EAAE,SAAM,GAAS,EACjB,IAAW,GAAa,EACxB,EAAE,iBAAc,GAAa,EAC7B,EAAE,aAAU,GAAU,EACtB,EAAE,aAAU,QAAK,YAAS,WAAQ,iBAAc,YAAS,kBAAe,GAA0B,EAClG,CAAC,GAAU,KAAe,EAAS,GAAM,EACzC,CAAC,GAAY,KAAiB,EAAwB,KAAK,EAE3D,IAAa,SAAe,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BAAC,GAAD,EAAY,WAAU,WAAY,CAAA,CAC3B;;MACL,CAAA,GACJ;KACI;;GACC"}
|
|
1
|
+
{"version":3,"file":"ComplianceOverviewPage.js","names":[],"sources":["../../../../src/healthybowl/pages/compliance/ComplianceOverviewPage.tsx"],"sourcesContent":["/**\n * Compliance & Certification — Internal Control System (ICS) dashboard.\n * Roadmap 10 · BOFF-2882.\n */\nimport { useMemo, useState } from 'react';\nimport { useNavigate } from 'react-router';\nimport {\n AlertTriangle,\n ArrowRight,\n BadgeCheck,\n ClipboardCheck,\n FileText,\n RefreshCw,\n ShieldCheck,\n Users,\n} from 'lucide-react';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { PageLayout, StatCard, ErrorState, PageLoader, EmptyState } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { useBasePath } from '../../hooks/useBasePath';\nimport { useHealthyBowlCompliance } from '../../hooks/useHealthyBowlCompliance';\nimport type { CertificationStandardProgress } from '../../hooks/useHealthyBowlCompliance';\nimport { formatDate } from '../../utils/helpers';\nimport {\n ExpiryBadge,\n FLAG_TYPE_LABEL,\n ProgressRing,\n RiskDot,\n SeverityBadge,\n STAGE_LABEL,\n InspectionStatusText,\n stageTone,\n} from './components';\n\nexport const ComplianceOverviewPage = () => {\n const { t } = useI18n();\n const navigate = useNavigate();\n const { buildPath } = useBasePath();\n const { toast } = useToast();\n const { overview, ics, loading, errors, startRenewal, runScan, refetchAll } = useHealthyBowlCompliance();\n const [scanning, setScanning] = useState(false);\n const [renewingId, setRenewingId] = useState<string | null>(null);\n\n const growerRows = useMemo(() => (ics?.growers ?? []).slice(0, 6), [ics]);\n\n const handleScan = async () => {\n setScanning(true);\n try {\n const result = await runScan();\n if (!result) {\n toast({\n title: t('healthybowl.compliance.overview.scan.noResult', 'Scan returned no result'),\n variant: 'warning',\n });\n return;\n }\n const summary = t(\n 'healthybowl.compliance.overview.scan.summary',\n '{{open}} open findings in total. {{sent}} notifications sent.',\n { open: result.totalOpenFlags, sent: result.notificationsSent }\n );\n // BOFF-6108: surface the document cascade when an expired certificate took documents with it.\n const description =\n result.documentsExpired > 0\n ? `${summary} ${t(\n 'healthybowl.compliance.overview.scan.documentsExpired',\n '{{count}} linked document(s) moved to Expired.',\n { count: result.documentsExpired }\n )}`\n : summary;\n toast({\n title:\n result.newFlags > 0\n ? t('healthybowl.compliance.overview.scan.found', '{{count}} new compliance findings', {\n count: result.newFlags,\n })\n : t('healthybowl.compliance.overview.scan.clean', 'No new findings'),\n description,\n variant: result.newFlags > 0 ? 'warning' : 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.compliance.overview.scan.failed', 'Compliance scan failed'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setScanning(false);\n }\n };\n\n const handleRenew = async (cert: CertificationStandardProgress) => {\n setRenewingId(cert.id);\n try {\n await startRenewal(cert.id);\n toast({\n title: t('healthybowl.compliance.overview.renew.started', 'Renewal started'),\n description: t('healthybowl.compliance.overview.renew.startedDesc', '{{name}} is now pending renewal.', {\n name: cert.name,\n }),\n variant: 'success',\n });\n } catch (err) {\n toast({\n title: t('healthybowl.compliance.overview.renew.failed', 'Could not start the renewal'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setRenewingId(null);\n }\n };\n\n if (loading.overview && !overview) {\n return <PageLoader />;\n }\n if (errors.overview) {\n return (\n <PageLayout title={t('healthybowl.compliance.overview.title', 'Compliance & Certification')}>\n <ErrorState description={errors.overview.message} onRetry={() => void refetchAll()} />\n </PageLayout>\n );\n }\n\n const openFlags = overview?.flags.filter((flag) => flag.status === 'OPEN') ?? [];\n const topFlag = openFlags[0] ?? null;\n\n return (\n <PageLayout\n title={t('healthybowl.compliance.overview.title', 'Compliance & Certification')}\n description={t(\n 'healthybowl.compliance.overview.description',\n 'Internal Control System, per-standard progress, expiry alerts and residue checks.'\n )}\n purpose=\"See at a glance whether your farm or farmer group is certification-ready: which standards are complete, which certificates are about to lapse, which member growers still need an internal inspection, and whether any prohibited input or over-limit residue has been recorded.\"\n hero\n actions={\n <div className=\"flex flex-wrap gap-2\">\n <Button variant=\"outline\" onClick={() => navigate(buildPath('compliance/alerts'))}>\n <AlertTriangle className=\"h-4 w-4\" />\n {t('healthybowl.compliance.overview.actions.alerts', 'Alerts')}\n {openFlags.length > 0 ? (\n <span className=\"ms-1 rounded-full bg-status-error-bg/20 px-1.5 py-0.5 text-xs font-semibold text-status-error-text\">\n {openFlags.length}\n </span>\n ) : null}\n </Button>\n <Button onClick={handleScan} disabled={scanning}>\n <RefreshCw className={scanning ? 'h-4 w-4 animate-spin' : 'h-4 w-4'} />\n {scanning\n ? t('healthybowl.compliance.overview.actions.scanning', 'Scanning…')\n : t('healthybowl.compliance.overview.actions.scan', 'Run compliance scan')}\n </Button>\n </div>\n }\n >\n <div className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4\">\n <StatCard\n hero\n label={t('healthybowl.compliance.overview.stats.active', 'Active certifications')}\n value={overview?.activeCertifications ?? 0}\n icon={<ShieldCheck className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.compliance.overview.stats.expiring', 'Expiring in 90 days')}\n value={overview?.expiringCertifications ?? 0}\n icon={<AlertTriangle className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.compliance.overview.stats.growers', 'ICS member growers')}\n value={overview?.icsMemberGrowers ?? 0}\n icon={<Users className=\"h-5 w-5\" />}\n />\n <StatCard\n label={t('healthybowl.compliance.overview.stats.findings', 'Open audit findings')}\n value={overview?.openAuditFindings ?? 0}\n icon={<ClipboardCheck className=\"h-5 w-5\" />}\n />\n </div>\n\n <div className=\"mt-6 grid grid-cols-1 gap-6 xl:grid-cols-3\">\n {/* Certification standards */}\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5 xl:col-span-2\">\n <header className=\"mb-4 flex items-start justify-between gap-3\">\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">\n {t('healthybowl.compliance.overview.standards.title', 'Certification standards')}\n </h2>\n <p className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.compliance.overview.standards.subtitle',\n 'Completion is approved required documents ÷ required documents.'\n )}\n </p>\n </div>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => navigate(buildPath('compliance/certifications'))}>\n {t('healthybowl.compliance.overview.standards.manage', 'Manage')}\n <ArrowRight className=\"h-4 w-4\" />\n </Button>\n </header>\n\n {(overview?.standards.length ?? 0) === 0 ? (\n <EmptyState\n title={t('healthybowl.compliance.overview.standards.emptyTitle', 'No certifications yet')}\n description={t(\n 'healthybowl.compliance.overview.standards.emptyMessage',\n 'Add a certification to start tracking its document checklist and expiry.'\n )}\n action={\n <Button onClick={() => navigate(buildPath('compliance/certifications'))}>\n {t('healthybowl.compliance.overview.standards.add', 'Add certification')}\n </Button>\n }\n />\n ) : (\n <div className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3\">\n {overview?.standards.map((cert) => (\n <button\n key={cert.id}\n type=\"button\"\n onClick={() => navigate(buildPath(`compliance/certifications/${cert.id}`))}\n className=\"flex flex-col items-center gap-3 rounded-lg border border-border-subtle bg-bg-sunken p-4 text-center transition-colors hover:border-border-default\"\n >\n <div className=\"text-sm font-semibold text-text-primary\">{cert.name}</div>\n <div className=\"text-xs text-text-secondary\">\n {cert.standardCode ?? cert.standard} — {STAGE_LABEL[cert.stage] ?? cert.stage}\n </div>\n <ProgressRing\n percent={cert.progressPercent}\n tone={stageTone(cert.stage, cert.daysToExpiry)}\n label={`${cert.name} ${cert.progressPercent} percent complete`}\n />\n <ExpiryBadge daysToExpiry={cert.daysToExpiry} />\n {cert.expiringSoon || cert.daysToExpiry < 0 ? (\n <Button\n size=\"sm\"\n className=\"w-full\"\n disabled={renewingId === cert.id || cert.renewalStartedAt !== null}\n onClick={(e) => {\n e.stopPropagation();\n void handleRenew(cert);\n }}\n >\n {cert.renewalStartedAt !== null\n ? t('healthybowl.compliance.overview.standards.renewing', 'Renewal in progress')\n : t('healthybowl.compliance.overview.standards.renew', 'Renew')}\n </Button>\n ) : null}\n </button>\n ))}\n </div>\n )}\n </section>\n\n {/* ICS group certification */}\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <header className=\"mb-4 flex items-start justify-between gap-3\">\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">\n {t('healthybowl.compliance.overview.ics.title', 'ICS — group certification')}\n </h2>\n <p className=\"text-sm text-text-secondary\">\n {t('healthybowl.compliance.overview.ics.subtitle', 'Member growers by risk and inspection status.')}\n </p>\n </div>\n <Button variant=\"ghost\" size=\"sm\" onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.overview.ics.open', 'Open')}\n <ArrowRight className=\"h-4 w-4\" />\n </Button>\n </header>\n\n {loading.ics && !ics ? (\n <PageLoader />\n ) : growerRows.length === 0 ? (\n <EmptyState\n title={t('healthybowl.compliance.overview.ics.emptyTitle', 'No ICS group yet')}\n description={t(\n 'healthybowl.compliance.overview.ics.emptyMessage',\n 'Create an Internal Control System to certify member growers under one group certificate.'\n )}\n action={\n <Button onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.overview.ics.create', 'Create ICS group')}\n </Button>\n }\n />\n ) : (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"border-b border-border-subtle text-start text-xs uppercase tracking-wide text-text-secondary\">\n <th className=\"pb-2 pe-3 font-medium\">\n {t('healthybowl.compliance.overview.ics.grower', 'Grower')}\n </th>\n <th className=\"pb-2 pe-3 font-medium\">\n {t('healthybowl.compliance.overview.ics.village', 'Village')}\n </th>\n <th className=\"pb-2 pe-3 font-medium\">{t('healthybowl.compliance.overview.ics.risk', 'Risk')}</th>\n <th className=\"pb-2 font-medium\">\n {t('healthybowl.compliance.overview.ics.inspection', 'Inspection')}\n </th>\n </tr>\n </thead>\n <tbody>\n {growerRows.map((grower) => (\n <tr\n key={grower.id}\n className=\"cursor-pointer border-b border-border-subtle last:border-0 hover:bg-bg-sunken\"\n onClick={() => navigate(buildPath(`compliance/ics/growers/${grower.id}`))}\n >\n <td className=\"py-2.5 pe-3 font-medium text-text-primary\">{grower.fullName}</td>\n <td className=\"py-2.5 pe-3 text-text-secondary\">{grower.village}</td>\n <td className=\"py-2.5 pe-3\">\n <RiskDot level={grower.riskLevel} />\n </td>\n <td className=\"py-2.5\">\n <InspectionStatusText status={grower.lastInspectionStatus} overdue={grower.inspectionOverdue} />\n {grower.lastInspectionDate ? (\n <div className=\"text-xs text-text-secondary\">{formatDate(grower.lastInspectionDate)}</div>\n ) : null}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n </section>\n </div>\n\n {/* Findings + Certificate of Origin */}\n <section className=\"mt-6 rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <header className=\"mb-4 flex flex-wrap items-start justify-between gap-3\">\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">\n {t('healthybowl.compliance.overview.findings.title', 'Compliance findings')}\n </h2>\n <p className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.compliance.overview.findings.subtitle',\n 'Banned inputs, residue breaches, expiries and overdue inspections.'\n )}\n </p>\n </div>\n <Button variant=\"outline\" onClick={() => navigate(buildPath('compliance/origin'))}>\n <FileText className=\"h-4 w-4\" />\n {t('healthybowl.compliance.overview.findings.coo', 'Certificate of Origin')}\n </Button>\n </header>\n\n {openFlags.length === 0 ? (\n <div className=\"flex items-center gap-3 rounded-lg border border-border-subtle bg-bg-sunken px-4 py-6\">\n <BadgeCheck className=\"h-6 w-6 text-success\" />\n <div>\n <div className=\"font-medium text-text-primary\">\n {t('healthybowl.compliance.overview.findings.cleanTitle', 'No open findings')}\n </div>\n <div className=\"text-sm text-text-secondary\">\n {t(\n 'healthybowl.compliance.overview.findings.cleanMessage',\n 'Nothing is currently blocking a certification or an export consignment.'\n )}\n </div>\n </div>\n </div>\n ) : (\n <ul className=\"space-y-3\">\n {openFlags.slice(0, 5).map((flag) => (\n <li\n key={flag.id}\n className=\"flex flex-wrap items-start justify-between gap-3 rounded-lg border border-border-subtle bg-bg-sunken px-4 py-3\"\n >\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <SeverityBadge severity={flag.severity} />\n <span className=\"text-xs font-medium uppercase tracking-wide text-text-secondary\">\n {FLAG_TYPE_LABEL[flag.type] ?? flag.type}\n </span>\n </div>\n <div className=\"mt-1 font-medium text-text-primary\">{flag.title}</div>\n <p className=\"text-sm text-text-secondary\">{flag.message}</p>\n </div>\n <Button variant=\"outline\" size=\"sm\" onClick={() => navigate(buildPath('compliance/alerts'))}>\n {t('healthybowl.compliance.overview.findings.review', 'Review')}\n </Button>\n </li>\n ))}\n </ul>\n )}\n\n {topFlag && openFlags.length > 5 ? (\n <div className=\"mt-3 text-end\">\n <Button variant=\"ghost\" size=\"sm\" onClick={() => navigate(buildPath('compliance/alerts'))}>\n {t('healthybowl.compliance.overview.findings.all', 'See all {{count}} findings', {\n count: openFlags.length,\n })}\n <ArrowRight className=\"h-4 w-4\" />\n </Button>\n </div>\n ) : null}\n </section>\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,IAAa,UAA+B;CAC1C,IAAM,EAAE,SAAM,GAAS,EACjB,IAAW,GAAa,EACxB,EAAE,iBAAc,GAAa,EAC7B,EAAE,aAAU,GAAU,EACtB,EAAE,aAAU,QAAK,YAAS,WAAQ,iBAAc,YAAS,kBAAe,GAA0B,EAClG,CAAC,GAAU,KAAe,EAAS,GAAM,EACzC,CAAC,GAAY,KAAiB,EAAwB,KAAK,EAE3D,IAAa,SAAe,GAAK,WAAW,EAAE,EAAE,MAAM,GAAG,EAAE,EAAE,CAAC,EAAI,CAAC,EAEnE,IAAa,YAAY;AAC7B,IAAY,GAAK;AACjB,MAAI;GACF,IAAM,IAAS,MAA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AAU,WAAY,CAAA,CAC3B;;MACL,CAAA,GACJ;KACI;;GACC"}
|
|
@@ -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,SA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C,wBAAwB;KACrE,CAAA,EACJ,EAAY,WAAW,IACtB,kBAAC,KAAD;KAAG,WAAU;eACV,EACC,6CACA,qEACD;KACC,CAAA,GAEJ,kBAAC,MAAD;KAAI,WAAU;eACX,EAAY,KAAK,MAAQ;MACxB,IAAM,IAAU,EAAe,EAAI,aAAa,EAC1C,IAAQ,EAAmB,EAAQ;AACzC,aACE,kBAAC,MAAD;OAEE,WAAU;iBAFZ,CAIE,kBAAC,QAAD;QAAM,WAAU;kBAAiC,EAAI;QAAgB,CAAA,EACrE,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;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 )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E,+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;EAA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B,KAAgB,KAAW,SACxB;;AAIT,SAAgB,EAAmB,GAA2C;AAC5E,SAAQ,GAAR;EACE,KAAK,UACH,QAAO;GAAE,KAAK;GAA+C,cAAc;GAAW;EACxF,KAAK,WACH,QAAO;GAAE,KAAK;GAAgD,cAAc;GAAiB;EAC/F,KAAK,OACH,QAAO;GAAE,KAAK;GAA4C,cAAc;GAAsB;EAChG,QACE,QAAO;GAAE,KAAK;GAA6C,cAAc;GAAoB;;;AAYnG,SAAgB,EAAe,GAA2C;CACxE,IAAM,KAAQ,MAAuB,OAAO,SAAS,EAAE,GAAG,IAAI;AAC9D,QAAO,CAAC,GAAG,EAAK,CAAC,MAAM,GAAG,MAAM,EAAK,EAAE,aAAa,GAAG,EAAK,EAAE,aAAa,CAAC"}
|
|
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 /** 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[]): 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":";AA2EA,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;EAC9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