@burdenoff/microfe-healthybowl 2026.902.34 → 2026.902.35

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.
@@ -212,6 +212,7 @@ var ee = "00000000-0000-0000-0000-000000000001", o = "\n id\n name\n body\n
212
212
  id
213
213
  status
214
214
  findingsCount
215
+ photoFileIds
215
216
  }
216
217
  }
217
218
  `, he = r`
@@ -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 /** DOCUMENT | GEO — what kind of evidence clears this item (BOFF-6334). */\n evidenceType: string;\n /** The EUDR plot statement satisfying a GEO item. */\n evidenceRefId: string | null;\n /** Geometry read off that statement, so the row can show it without a second call. */\n geoEvidence: {\n latitude: number | null;\n longitude: number | null;\n plotAreaHa: number | null;\n boundaryDefined: boolean;\n } | 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 {\n id code label description required status documentId orderIndex completedAt\n evidenceType evidenceRefId\n geoEvidence { latitude longitude plotAreaHa boundaryDefined }\n }\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 UPDATE_SUBSTANCE_RULE = gql`\n mutation UpdateHealthyBowlSubstanceRule($input: UpdateComplianceSubstanceRuleInput!) {\n updateHealthyBowlSubstanceRule(input: $input) {\n id\n substanceName\n prohibited\n mrlMgPerKg\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 [updateSubstanceRuleMutation] = useMutation(UPDATE_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, evidenceRefId?: string | null) =>\n run(\n updateChecklistItemMutation,\n {\n input: withCtx({\n id,\n status,\n ...(documentId !== undefined ? { documentId } : {}),\n ...(evidenceRefId !== undefined ? { evidenceRefId } : {}),\n }),\n },\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 updateSubstanceRule: useCallback(\n (input: Record<string, unknown>) => run(updateSubstanceRuleMutation, { input: withCtx(input) }, [refetchRules]),\n [run, updateSubstanceRuleMutation, 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,wCA6QxB,IAAc,iLAsBd,IAAuB;IACzB,EAAY;;;;GAMV,IAAc,4JAgBd,IAAoB,mKAepB,IAAgB,iTAuBhB,IAAgB,8OAehB,IAAqB;oBACP,EAAY;;;;;;;;;;;;GAc1B,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,IAAY,CAAG;;uFAEkE,EAAY;;GAI7F,KAAsB,CAAG;;;;;;;;;;;;;;;;GAkBzB,KAAoB,CAAG;;;;;;;;;;;;;;GAgBvB,KAAW,CAAG;;;;;;;;;;;;;;;;;;;;;;;GAyBd,IAAc,CA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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 /** DOCUMENT | GEO — what kind of evidence clears this item (BOFF-6334). */\n evidenceType: string;\n /** The EUDR plot statement satisfying a GEO item. */\n evidenceRefId: string | null;\n /** Geometry read off that statement, so the row can show it without a second call. */\n geoEvidence: {\n latitude: number | null;\n longitude: number | null;\n plotAreaHa: number | null;\n boundaryDefined: boolean;\n } | 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 {\n id code label description required status documentId orderIndex completedAt\n evidenceType evidenceRefId\n geoEvidence { latitude longitude plotAreaHa boundaryDefined }\n }\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 photoFileIds\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 UPDATE_SUBSTANCE_RULE = gql`\n mutation UpdateHealthyBowlSubstanceRule($input: UpdateComplianceSubstanceRuleInput!) {\n updateHealthyBowlSubstanceRule(input: $input) {\n id\n substanceName\n prohibited\n mrlMgPerKg\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 [updateSubstanceRuleMutation] = useMutation(UPDATE_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, evidenceRefId?: string | null) =>\n run(\n updateChecklistItemMutation,\n {\n input: withCtx({\n id,\n status,\n ...(documentId !== undefined ? { documentId } : {}),\n ...(evidenceRefId !== undefined ? { evidenceRefId } : {}),\n }),\n },\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 updateSubstanceRule: useCallback(\n (input: Record<string, unknown>) => run(updateSubstanceRuleMutation, { input: withCtx(input) }, [refetchRules]),\n [run, updateSubstanceRuleMutation, 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,wCA6QxB,IAAc,iLAsBd,IAAuB;IACzB,EAAY;;;;GAMV,IAAc,4JAgBd,IAAoB,mKAepB,IAAgB,iTAuBhB,IAAgB,8OAehB,IAAqB;oBACP,EAAY;;;;;;;;;;;;GAc1B,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,IAAY,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,KAAoB,CAAG;;;;;;;;GASvB,KAAoB,CAAG;;;;;;;;GASvB,KAAoB,CAAG;;;;GAKvB,KAAsB,CAAG;;;;;;;;GASzB,KAAoB,CAAG;;;;;;;;;GAUvB,KAAiB,CAAG;;;;;;;;;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,mBAAmB,GAChB,MACC,EAAI,GAA2B,EAAE,OAAO,EAAQ,CAAK,EAAE,GAAG;GAAC;GAAgB;GAAc;EAAe,CAAC,GAC3G;GAAC;GAAK;GAA2B;GAAS;GAAgB;GAAc;EAAe,CACzF;EACA,mBAAmB,GAChB,MAAe,EAAI,GAA2B;GAAE;GAAI,SAAS;EAAI,GAAG,CAAC,CAAc,CAAC,GACrF;GAAC;GAAK;GAA2B;GAAK;EAAc,CACtD;EAGA,6BAA6B,EAC3B,OACE,MAC8E;GAC9E,IAAM,IAAM,MAAM,EAAoB,EAAE,WAAW,EAAE,OAAO,EAAQ,CAAK,EAAE,EAAE,CAAC;GAC9E,IAAI,EAAI,OAAO,MAAM,EAAI;GAEzB,OADA,MAAM,EAAU,CAAW,GACpB,EAAI,MAAM,0CAA0C;EAC7D,GACA;GAAC;GAAqB;GAAS;GAAW;EAAW,CACvD;EACA,+BAA+B,GAC5B,GAAY,GAAgB,MAC3B,EAAI,GAAuB,EAAE,OAAO,EAAQ;GAAE;GAAI;GAAQ,GAAI,IAAW,EAAE,YAAS,IAAI,CAAC;EAAG,CAAC,EAAE,GAAG,CAChG,CACF,CAAC,GACH;GAAC;GAAK;GAAuB;GAAS;EAAW,CACnD;EACA,2BAA2B,GACxB,MAAe,EAAI,GAAmB;GAAE;GAAI,SAAS;EAAI,GAAG,CAAC,CAAW,CAAC,GAC1E;GAAC;GAAK;GAAmB;GAAK;EAAW,CAC3C;EAGA,WAAW;GAAE;GAAiB;GAAsB;GAAuB;EAAY;EACvF,SAAS;CACX;AACF"}
@@ -11,15 +11,16 @@ import { useToast as te } from "../../hooks/useToast.js";
11
11
  import "../../components/index.js";
12
12
  import { GET_ICS_GROWER_DETAIL as ne, useHealthyBowlCompliance as re } from "../../hooks/useHealthyBowlCompliance.js";
13
13
  import { InspectionStatusText as u, RiskDot as ie } from "./components.js";
14
- import { useEffect as ae, useMemo as d, useState as f } from "react";
15
- import { useI18n as oe } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
16
- import { CalendarClock as p, Camera as m, ClipboardCheck as h, FileText as se, LocateFixed as ce, MapPin as g, Save as le } from "lucide-react";
17
- import { useNavigate as ue, useParams as de } from "react-router";
18
- import { jsx as _, jsxs as v } from "react/jsx-runtime";
19
- import { Button as y, Input as b, Textarea as fe } from "@burdenoff/fe-libs/ui";
20
- import { useQuery as pe } from "@apollo/client/react";
14
+ import { pickOpenInspection as ae } from "../../utils/icsInspection.js";
15
+ import { useEffect as oe, useMemo as d, useRef as se, useState as f } from "react";
16
+ import { useI18n as ce } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
17
+ import { CalendarClock as p, Camera as le, ClipboardCheck as m, FileText as ue, LocateFixed as de, MapPin as h, Save as fe } from "lucide-react";
18
+ import { useNavigate as pe, useParams as me } from "react-router";
19
+ import { jsx as g, jsxs as _ } from "react/jsx-runtime";
20
+ import { Button as v, Input as y, Textarea as he } from "@burdenoff/fe-libs/ui";
21
+ import { useQuery as ge } from "@apollo/client/react";
21
22
  //#region src/healthybowl/pages/compliance/IcsGrowerDetailPage.tsx
22
- var x = [
23
+ var b = [
23
24
  {
24
25
  key: "no_prohibited_inputs",
25
26
  label: "No prohibited inputs stored on farm"
@@ -40,7 +41,7 @@ var x = [
40
41
  key: "compost_manure",
41
42
  label: "Compost & manure managed correctly"
42
43
  }
43
- ], me = [
44
+ ], _e = 5, ve = [
44
45
  {
45
46
  value: "PASS",
46
47
  labelKey: "healthybowl.compliance.icsGrower.result.pass",
@@ -59,7 +60,7 @@ var x = [
59
60
  fallback: "N/A",
60
61
  active: "bg-bg-sunken text-text-primary border-border-default"
61
62
  }
62
- ], he = {
63
+ ], ye = {
63
64
  CONVENTIONAL: {
64
65
  key: "healthybowl.compliance.icsGrower.conversion.conventional",
65
66
  fallback: "Conventional"
@@ -80,30 +81,30 @@ var x = [
80
81
  key: "healthybowl.compliance.icsGrower.conversion.organic",
81
82
  fallback: "Organic (certified)"
82
83
  }
83
- }, ge = 20, _e = () => void 0, ve = (e) => {
84
+ }, be = 20, xe = () => void 0, x = (e) => {
84
85
  let t = e.trim();
85
86
  if (t === "") return null;
86
87
  let n = Number(t);
87
88
  return Number.isFinite(n) ? n : null;
88
- }, S = () => x.reduce((e, t) => (e[t.key] = "NA", e), {}), C = () => {
89
- let { t: C } = oe(), w = ue(), { buildPath: T } = i(), { toast: E, toasts: ye, dismiss: be } = te(), { growerId: D } = de(), { context: xe, scheduleInspection: Se, recordInspection: Ce } = re({ skipSecondary: !0 }), { data: O, loading: we, error: k, refetch: A } = pe(ne, {
89
+ }, S = () => b.reduce((e, t) => (e[t.key] = "NA", e), {}), C = () => {
90
+ let { t: C } = ce(), w = pe(), { buildPath: T } = i(), { toast: E, toasts: Se, dismiss: Ce } = te(), { growerId: D } = me(), { context: we, scheduleInspection: Te, recordInspection: Ee } = re({ skipSecondary: !0 }), { data: O, loading: De, error: k, refetch: A } = ge(ne, {
90
91
  variables: {
91
92
  id: D ?? "",
92
- context: xe
93
+ context: we
93
94
  },
94
95
  fetchPolicy: "cache-and-network",
95
96
  skip: !D
96
- }), j = O?.getHealthyBowlIcsGrowerDetail ?? null, M = j?.grower ?? null, N = j?.group ?? null, P = d(() => j?.inspections ?? [], [j]), F = d(() => P.find((e) => e.status === "SCHEDULED") ?? null, [P]), I = d(() => [...P].sort((e, t) => new Date(t.inspectionDate).getTime() - new Date(e.inspectionDate).getTime()), [P]), [L, Te] = f(n()), [R, z] = f(""), [B, V] = f(S), [H, U] = f({}), [W, G] = f(""), [K, q] = f(""), [J, Y] = f(""), [X, Z] = f([]), [Q, Ee] = f(null);
97
- ae(() => {
98
- F?.inspectorName && z((e) => e || F.inspectorName);
97
+ }), j = O?.getHealthyBowlIcsGrowerDetail ?? null, M = j?.grower ?? null, N = j?.group ?? null, P = d(() => j?.inspections ?? [], [j]), F = d(() => ae(P), [P]), I = d(() => [...P].sort((e, t) => new Date(t.inspectionDate).getTime() - new Date(e.inspectionDate).getTime()), [P]), [L, Oe] = f(n()), [R, z] = f(""), [B, V] = f(S), [H, U] = f({}), [W, G] = f(""), [K, q] = f(""), [J, Y] = f(""), [X, Z] = f([]), [Q, ke] = f(null), Ae = se(null);
98
+ oe(() => {
99
+ !F || Ae.current === F.id || (Ae.current = F.id, F.inspectorName && z((e) => e || F.inspectorName), Z((e) => e.length > 0 ? e : F.photoFileIds));
99
100
  }, [F]);
100
- let De = d(() => M && M.fullName.split(/\s+/).filter(Boolean).slice(0, 2).map((e) => e.charAt(0).toUpperCase()).join("") || "?", [M]), Oe = (e, t) => V((n) => ({
101
+ let je = d(() => M && M.fullName.split(/\s+/).filter(Boolean).slice(0, 2).map((e) => e.charAt(0).toUpperCase()).join("") || "?", [M]), Me = (e, t) => V((n) => ({
101
102
  ...n,
102
103
  [e]: t
103
- })), ke = (e, t) => U((n) => ({
104
+ })), Ne = (e, t) => U((n) => ({
104
105
  ...n,
105
106
  [e]: t
106
- })), Ae = () => {
107
+ })), Pe = () => {
107
108
  if (typeof navigator > "u" || !("geolocation" in navigator) || !navigator.geolocation) {
108
109
  E({
109
110
  title: C("healthybowl.compliance.icsGrower.geo.unavailable", "Location not available"),
@@ -124,9 +125,9 @@ var x = [
124
125
  variant: "warning"
125
126
  });
126
127
  });
127
- }, je = () => {
128
+ }, Fe = () => {
128
129
  V(S()), U({}), G(""), q(""), Y(""), Z([]);
129
- }, Me = async (e) => {
130
+ }, Ie = async (e) => {
130
131
  if (M) {
131
132
  if (!R.trim()) {
132
133
  E({
@@ -142,15 +143,15 @@ var x = [
142
143
  });
143
144
  return;
144
145
  }
145
- Ee(e);
146
+ ke(e);
146
147
  try {
147
148
  let t = F?.id ?? null;
148
- if (!t && (t = (await Se({
149
+ if (!t && (t = (await Te({
149
150
  growerId: M.id,
150
151
  inspectionDate: L,
151
152
  inspectorName: R.trim()
152
153
  }))?.scheduleHealthyBowlIcsInspection?.id ?? null, !t)) throw Error(C("healthybowl.compliance.icsGrower.error.schedule", "Could not open an inspection to record against."));
153
- let n = x.map((e) => {
154
+ let n = b.map((e) => {
154
155
  let t = H[e.key]?.trim();
155
156
  return {
156
157
  key: e.key,
@@ -164,10 +165,10 @@ var x = [
164
165
  inspectorName: R.trim(),
165
166
  inspectionDate: L
166
167
  };
167
- e === "draft" && (r.status = "DRAFT"), W.trim() && (r.notes = W.trim()), X.length > 0 && (r.photoFileIds = X);
168
- let i = ve(K), a = ve(J);
169
- i !== null && a !== null && i >= -90 && i <= 90 && a >= -180 && a <= 180 && (r.latitude = i, r.longitude = a);
170
- let o = await Ce(r), s = o?.recordHealthyBowlIcsInspection?.status ?? null, c = o?.recordHealthyBowlIcsInspection?.findingsCount ?? 0;
168
+ e === "draft" && (r.status = "DRAFT"), W.trim() && (r.notes = W.trim());
169
+ let i = x(K), a = x(J);
170
+ i !== null && a !== null && i >= -90 && i <= 90 && a >= -180 && a <= 180 && (r.latitude = i, r.longitude = a), r.photoFileIds = X;
171
+ let o = await Ee(r), s = o?.recordHealthyBowlIcsInspection?.status ?? null, c = o?.recordHealthyBowlIcsInspection?.findingsCount ?? 0;
171
172
  E(e === "draft" ? {
172
173
  title: C("healthybowl.compliance.icsGrower.toast.draft", "Inspection saved as draft"),
173
174
  variant: "info"
@@ -184,7 +185,7 @@ var x = [
184
185
  } : {
185
186
  title: C("healthybowl.compliance.icsGrower.toast.recorded", "Inspection recorded"),
186
187
  variant: "success"
187
- }), je(), await A();
188
+ }), e !== "draft" && Fe(), await A();
188
189
  } catch (e) {
189
190
  E({
190
191
  title: C("healthybowl.compliance.icsGrower.toast.error", "Could not record the inspection"),
@@ -192,48 +193,48 @@ var x = [
192
193
  variant: "error"
193
194
  });
194
195
  } finally {
195
- Ee(null);
196
+ ke(null);
196
197
  }
197
198
  }
198
199
  };
199
- if (!D) return /* @__PURE__ */ _(r, {
200
+ if (!D) return /* @__PURE__ */ g(r, {
200
201
  title: C("healthybowl.compliance.icsGrower.notFound.title", "Grower not found"),
201
- children: /* @__PURE__ */ _(a, {
202
- icon: /* @__PURE__ */ _(h, { className: "h-6 w-6" }),
202
+ children: /* @__PURE__ */ g(a, {
203
+ icon: /* @__PURE__ */ g(m, { className: "h-6 w-6" }),
203
204
  title: C("healthybowl.compliance.icsGrower.notFound.title", "Grower not found"),
204
205
  description: C("healthybowl.compliance.icsGrower.notFound.description", "No grower was specified."),
205
- action: /* @__PURE__ */ _(y, {
206
+ action: /* @__PURE__ */ g(v, {
206
207
  onClick: () => w(T("compliance/ics")),
207
208
  children: C("healthybowl.compliance.icsGrower.notFound.action", "Back to ICS")
208
209
  })
209
210
  })
210
211
  });
211
- if (we && !O) return /* @__PURE__ */ _(ee, {});
212
- if (k) return /* @__PURE__ */ _(r, {
212
+ if (De && !O) return /* @__PURE__ */ g(ee, {});
213
+ if (k) return /* @__PURE__ */ g(r, {
213
214
  title: C("healthybowl.compliance.icsGrower.title", "Grower"),
214
- children: /* @__PURE__ */ _(o, {
215
+ children: /* @__PURE__ */ g(o, {
215
216
  description: k.message,
216
217
  onRetry: () => void A()
217
218
  })
218
219
  });
219
- if (!M || !N) return /* @__PURE__ */ _(r, {
220
+ if (!M || !N) return /* @__PURE__ */ g(r, {
220
221
  title: C("healthybowl.compliance.icsGrower.notFound.title", "Grower not found"),
221
- children: /* @__PURE__ */ _(a, {
222
- icon: /* @__PURE__ */ _(h, { className: "h-6 w-6" }),
222
+ children: /* @__PURE__ */ g(a, {
223
+ icon: /* @__PURE__ */ g(m, { className: "h-6 w-6" }),
223
224
  title: C("healthybowl.compliance.icsGrower.notFound.title", "Grower not found"),
224
225
  description: C("healthybowl.compliance.icsGrower.notFound.missing", "This grower may have been removed from the Internal Control System."),
225
- action: /* @__PURE__ */ _(y, {
226
+ action: /* @__PURE__ */ g(v, {
226
227
  onClick: () => w(T("compliance/ics")),
227
228
  children: C("healthybowl.compliance.icsGrower.notFound.action", "Back to ICS")
228
229
  })
229
230
  })
230
231
  });
231
- let $ = he[M.conversionStatus], Ne = $ ? C($.key, $.fallback) : M.conversionStatus;
232
- return /* @__PURE__ */ v(r, {
232
+ let $ = ye[M.conversionStatus], Le = $ ? C($.key, $.fallback) : M.conversionStatus;
233
+ return /* @__PURE__ */ _(r, {
233
234
  title: M.fullName,
234
235
  description: C("healthybowl.compliance.icsGrower.headerSubtitle", "ICS member of {{group}}", { group: N.name }),
235
236
  children: [
236
- /* @__PURE__ */ _(c, { items: [
237
+ /* @__PURE__ */ g(c, { items: [
237
238
  {
238
239
  label: C("healthybowl.compliance.breadcrumb.compliance", "Compliance"),
239
240
  href: T("compliance")
@@ -248,19 +249,19 @@ var x = [
248
249
  },
249
250
  { label: M.fullName }
250
251
  ] }),
251
- /* @__PURE__ */ v("div", {
252
+ /* @__PURE__ */ _("div", {
252
253
  className: "flex flex-wrap items-center justify-between gap-4 rounded-xl border border-border-subtle bg-bg-surface p-5",
253
- children: [/* @__PURE__ */ v("div", {
254
+ children: [/* @__PURE__ */ _("div", {
254
255
  className: "flex items-center gap-4",
255
- children: [/* @__PURE__ */ _("span", {
256
+ children: [/* @__PURE__ */ g("span", {
256
257
  className: "flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-bg-sunken text-lg font-semibold text-text-primary",
257
- children: De
258
- }), /* @__PURE__ */ v("div", { children: [
259
- /* @__PURE__ */ _("h2", {
258
+ children: je
259
+ }), /* @__PURE__ */ _("div", { children: [
260
+ /* @__PURE__ */ g("h2", {
260
261
  className: "text-lg font-semibold text-text-primary",
261
262
  children: M.fullName
262
263
  }),
263
- /* @__PURE__ */ v("p", {
264
+ /* @__PURE__ */ _("p", {
264
265
  className: "text-sm text-text-secondary",
265
266
  children: [
266
267
  C("healthybowl.compliance.icsGrower.header.village", "Village"),
@@ -277,251 +278,251 @@ var x = [
277
278
  M.memberCode
278
279
  ]
279
280
  }),
280
- /* @__PURE__ */ v("p", {
281
+ /* @__PURE__ */ _("p", {
281
282
  className: "mt-1 text-xs text-text-secondary",
282
283
  children: [
283
284
  C("healthybowl.compliance.icsGrower.header.conversion", "Conversion"),
284
285
  ": ",
285
- Ne
286
+ Le
286
287
  ]
287
288
  })
288
289
  ] })]
289
- }), /* @__PURE__ */ v("div", {
290
+ }), /* @__PURE__ */ _("div", {
290
291
  className: "flex flex-col items-end gap-1",
291
- children: [/* @__PURE__ */ _("span", {
292
+ children: [/* @__PURE__ */ g("span", {
292
293
  className: "text-xs uppercase tracking-wide text-text-secondary",
293
294
  children: C("healthybowl.compliance.icsGrower.header.risk", "Risk")
294
- }), /* @__PURE__ */ _("span", {
295
+ }), /* @__PURE__ */ g("span", {
295
296
  className: "inline-flex items-center gap-2 rounded-full border border-border-subtle bg-bg-sunken px-3 py-1",
296
- children: /* @__PURE__ */ _(ie, { level: M.riskLevel })
297
+ children: /* @__PURE__ */ g(ie, { level: M.riskLevel })
297
298
  })]
298
299
  })]
299
300
  }),
300
- /* @__PURE__ */ v("div", {
301
+ /* @__PURE__ */ _("div", {
301
302
  className: "grid grid-cols-1 gap-6 lg:grid-cols-3",
302
- children: [/* @__PURE__ */ v("section", {
303
+ children: [/* @__PURE__ */ _("section", {
303
304
  className: "rounded-xl border border-border-subtle bg-bg-surface p-5 lg:col-span-2",
304
305
  children: [
305
- /* @__PURE__ */ v("header", {
306
+ /* @__PURE__ */ _("header", {
306
307
  className: "mb-4",
307
- children: [/* @__PURE__ */ v("h3", {
308
+ children: [/* @__PURE__ */ _("h3", {
308
309
  className: "flex items-center gap-2 text-lg font-semibold text-text-primary",
309
- children: [/* @__PURE__ */ _(h, { className: "h-5 w-5 text-text-secondary" }), C("healthybowl.compliance.icsGrower.record.title", "Record internal inspection")]
310
- }), /* @__PURE__ */ _("p", {
310
+ children: [/* @__PURE__ */ g(m, { className: "h-5 w-5 text-text-secondary" }), C("healthybowl.compliance.icsGrower.record.title", "Record internal inspection")]
311
+ }), /* @__PURE__ */ g("p", {
311
312
  className: "text-sm text-text-secondary",
312
- children: F ? C("healthybowl.compliance.icsGrower.record.against", "Recording against the inspection scheduled for {{date}}.", { date: t(F.inspectionDate) }) : C("healthybowl.compliance.icsGrower.record.new", "A new inspection will be opened and recorded in one step.")
313
+ children: F ? F.status === "DRAFT" ? C("healthybowl.compliance.icsGrower.record.againstDraft", "Continuing the draft inspection saved for {{date}}.", { date: t(F.inspectionDate) }) : C("healthybowl.compliance.icsGrower.record.against", "Recording against the inspection scheduled for {{date}}.", { date: t(F.inspectionDate) }) : C("healthybowl.compliance.icsGrower.record.new", "A new inspection will be opened and recorded in one step.")
313
314
  })]
314
315
  }),
315
- /* @__PURE__ */ v("div", {
316
+ /* @__PURE__ */ _("div", {
316
317
  className: "grid grid-cols-1 gap-4 sm:grid-cols-2",
317
- children: [/* @__PURE__ */ v("div", { children: [/* @__PURE__ */ _("label", {
318
+ children: [/* @__PURE__ */ _("div", { children: [/* @__PURE__ */ g("label", {
318
319
  htmlFor: "inspection-date",
319
320
  className: "mb-1 block text-sm font-medium text-text-primary",
320
321
  children: C("healthybowl.compliance.icsGrower.record.date", "Inspection date")
321
- }), /* @__PURE__ */ _(b, {
322
+ }), /* @__PURE__ */ g(y, {
322
323
  id: "inspection-date",
323
324
  type: "date",
324
325
  value: L,
325
- onChange: (e) => Te(e.target.value)
326
- })] }), /* @__PURE__ */ v("div", { children: [/* @__PURE__ */ _("label", {
326
+ onChange: (e) => Oe(e.target.value)
327
+ })] }), /* @__PURE__ */ _("div", { children: [/* @__PURE__ */ g("label", {
327
328
  htmlFor: "inspection-inspector",
328
329
  className: "mb-1 block text-sm font-medium text-text-primary",
329
330
  children: C("healthybowl.compliance.icsGrower.record.inspector", "Inspector name")
330
- }), /* @__PURE__ */ _(b, {
331
+ }), /* @__PURE__ */ g(y, {
331
332
  id: "inspection-inspector",
332
333
  value: R,
333
334
  onChange: (e) => z(e.target.value),
334
335
  placeholder: C("healthybowl.compliance.icsGrower.record.inspectorPlaceholder", "e.g., Ravi Kumar")
335
336
  })] })]
336
337
  }),
337
- /* @__PURE__ */ v("div", {
338
+ /* @__PURE__ */ _("div", {
338
339
  className: "mt-5 space-y-3",
339
- children: [/* @__PURE__ */ _("h4", {
340
+ children: [/* @__PURE__ */ g("h4", {
340
341
  className: "text-sm font-semibold text-text-primary",
341
342
  children: C("healthybowl.compliance.icsGrower.record.checklist", "Control points")
342
- }), x.map((t) => /* @__PURE__ */ v("div", {
343
+ }), b.map((t) => /* @__PURE__ */ _("div", {
343
344
  className: "rounded-lg border border-border-subtle bg-bg-sunken p-3",
344
- children: [/* @__PURE__ */ v("div", {
345
+ children: [/* @__PURE__ */ _("div", {
345
346
  className: "flex flex-wrap items-center justify-between gap-3",
346
- children: [/* @__PURE__ */ _("span", {
347
+ children: [/* @__PURE__ */ g("span", {
347
348
  className: "text-sm text-text-primary",
348
349
  children: C(`healthybowl.compliance.icsGrower.controlPoints.${t.key}`, t.label)
349
- }), /* @__PURE__ */ _("div", {
350
+ }), /* @__PURE__ */ g("div", {
350
351
  className: "inline-flex overflow-hidden rounded-md border border-border-subtle",
351
- children: me.map((n) => {
352
+ children: ve.map((n) => {
352
353
  let r = B[t.key] === n.value;
353
- return /* @__PURE__ */ _("button", {
354
+ return /* @__PURE__ */ g("button", {
354
355
  type: "button",
355
- onClick: () => Oe(t.key, n.value),
356
+ onClick: () => Me(t.key, n.value),
356
357
  "aria-pressed": r,
357
358
  className: e("border-s px-3 py-1.5 text-xs font-medium transition-colors first:border-s-0", r ? n.active : "border-border-subtle bg-bg-surface text-text-secondary hover:text-text-primary"),
358
359
  children: C(n.labelKey, n.fallback)
359
360
  }, n.value);
360
361
  })
361
362
  })]
362
- }), B[t.key] === "FAIL" ? /* @__PURE__ */ _(b, {
363
+ }), B[t.key] === "FAIL" ? /* @__PURE__ */ g(y, {
363
364
  value: H[t.key] ?? "",
364
- onChange: (e) => ke(t.key, e.target.value),
365
+ onChange: (e) => Ne(t.key, e.target.value),
365
366
  placeholder: C("healthybowl.compliance.icsGrower.record.itemNote", "What was found? (optional)"),
366
367
  className: "mt-2 h-9"
367
368
  }) : null]
368
369
  }, t.key))]
369
370
  }),
370
- /* @__PURE__ */ v("div", {
371
+ /* @__PURE__ */ _("div", {
371
372
  className: "mt-5",
372
373
  children: [
373
- /* @__PURE__ */ v("h4", {
374
+ /* @__PURE__ */ _("h4", {
374
375
  className: "mb-1 flex items-center gap-2 text-sm font-semibold text-text-primary",
375
- children: [/* @__PURE__ */ _(m, { className: "h-4 w-4 text-text-secondary" }), C("healthybowl.compliance.icsGrower.record.photos", "Photo evidence")]
376
+ children: [/* @__PURE__ */ g(le, { className: "h-4 w-4 text-text-secondary" }), C("healthybowl.compliance.icsGrower.record.photos", "Photo evidence")]
376
377
  }),
377
- /* @__PURE__ */ _("p", {
378
+ /* @__PURE__ */ g("p", {
378
379
  className: "mb-2 text-xs text-text-secondary",
379
380
  children: C("healthybowl.compliance.icsGrower.record.photosHint", "Attach what you saw — a store of inputs, a buffer strip, a spray diary page. Photos are stored in your workspace Files and stay with this inspection for the certifier.")
380
381
  }),
381
- /* @__PURE__ */ _(l, {
382
+ /* @__PURE__ */ g(l, {
382
383
  imageIds: X,
383
384
  onChange: Z,
384
385
  entity: "Inspection",
385
- max: ge
386
+ max: be
386
387
  })
387
388
  ]
388
389
  }),
389
- /* @__PURE__ */ v("div", {
390
+ /* @__PURE__ */ _("div", {
390
391
  className: "mt-5",
391
- children: [/* @__PURE__ */ _("label", {
392
+ children: [/* @__PURE__ */ g("label", {
392
393
  htmlFor: "inspection-notes",
393
394
  className: "mb-1 block text-sm font-medium text-text-primary",
394
395
  children: C("healthybowl.compliance.icsGrower.record.notes", "Inspector notes")
395
- }), /* @__PURE__ */ _(fe, {
396
+ }), /* @__PURE__ */ g(he, {
396
397
  id: "inspection-notes",
397
398
  value: W,
398
399
  onChange: (e) => G(e.target.value),
399
400
  placeholder: C("healthybowl.compliance.icsGrower.record.notesPlaceholder", "Overall observations, follow-up actions, corrective measures…")
400
401
  })]
401
402
  }),
402
- /* @__PURE__ */ v("div", {
403
+ /* @__PURE__ */ _("div", {
403
404
  className: "mt-4 flex flex-wrap items-center justify-between gap-3",
404
- children: [/* @__PURE__ */ v("div", {
405
+ children: [/* @__PURE__ */ _("div", {
405
406
  className: "flex items-center gap-2",
406
- children: [/* @__PURE__ */ v(y, {
407
+ children: [/* @__PURE__ */ _(v, {
407
408
  type: "button",
408
409
  variant: "outline",
409
410
  size: "sm",
410
- onClick: Ae,
411
- children: [/* @__PURE__ */ _(ce, { className: "h-4 w-4" }), C("healthybowl.compliance.icsGrower.record.capture", "Capture GPS")]
412
- }), K.trim() && J.trim() ? /* @__PURE__ */ v("span", {
411
+ onClick: Pe,
412
+ children: [/* @__PURE__ */ g(de, { className: "h-4 w-4" }), C("healthybowl.compliance.icsGrower.record.capture", "Capture GPS")]
413
+ }), K.trim() && J.trim() ? /* @__PURE__ */ _("span", {
413
414
  className: "inline-flex items-center gap-1 text-xs text-text-secondary",
414
415
  children: [
415
- /* @__PURE__ */ _(g, { className: "h-3.5 w-3.5" }),
416
+ /* @__PURE__ */ g(h, { className: "h-3.5 w-3.5" }),
416
417
  K.trim(),
417
418
  ", ",
418
419
  J.trim()
419
420
  ]
420
421
  }) : null]
421
- }), /* @__PURE__ */ v("div", {
422
+ }), /* @__PURE__ */ _("div", {
422
423
  className: "flex items-center gap-2",
423
- children: [/* @__PURE__ */ v(y, {
424
+ children: [/* @__PURE__ */ _(v, {
424
425
  variant: "outline",
425
- onClick: () => void Me("draft"),
426
+ onClick: () => void Ie("draft"),
426
427
  disabled: Q !== null,
427
- children: [/* @__PURE__ */ _(le, { className: "h-4 w-4" }), Q === "draft" ? C("healthybowl.compliance.icsGrower.record.savingDraft", "Saving…") : C("healthybowl.compliance.icsGrower.record.saveDraft", "Save as draft")]
428
- }), /* @__PURE__ */ _(y, {
429
- onClick: () => void Me("submit"),
428
+ children: [/* @__PURE__ */ g(fe, { className: "h-4 w-4" }), Q === "draft" ? C("healthybowl.compliance.icsGrower.record.savingDraft", "Saving…") : C("healthybowl.compliance.icsGrower.record.saveDraft", "Save as draft")]
429
+ }), /* @__PURE__ */ g(v, {
430
+ onClick: () => void Ie("submit"),
430
431
  disabled: Q !== null,
431
432
  children: Q === "submit" ? C("healthybowl.compliance.icsGrower.record.submitting", "Submitting…") : C("healthybowl.compliance.icsGrower.record.submit", "Submit inspection")
432
433
  })]
433
434
  })]
434
435
  })
435
436
  ]
436
- }), /* @__PURE__ */ v("div", {
437
+ }), /* @__PURE__ */ _("div", {
437
438
  className: "space-y-6",
438
- children: [/* @__PURE__ */ v("section", {
439
+ children: [/* @__PURE__ */ _("section", {
439
440
  className: "rounded-xl border border-border-subtle bg-bg-surface p-5",
440
- children: [/* @__PURE__ */ v("h3", {
441
+ children: [/* @__PURE__ */ _("h3", {
441
442
  className: "mb-1 flex items-center gap-2 text-lg font-semibold text-text-primary",
442
- children: [/* @__PURE__ */ _(se, { className: "h-5 w-5 text-text-secondary" }), C("healthybowl.compliance.icsGrower.status.title", "Compliance status")]
443
- }), /* @__PURE__ */ v("dl", {
443
+ children: [/* @__PURE__ */ g(ue, { className: "h-5 w-5 text-text-secondary" }), C("healthybowl.compliance.icsGrower.status.title", "Compliance status")]
444
+ }), /* @__PURE__ */ _("dl", {
444
445
  className: "mt-3 space-y-2 text-sm",
445
446
  children: [
446
- /* @__PURE__ */ v("div", {
447
+ /* @__PURE__ */ _("div", {
447
448
  className: "flex items-center justify-between",
448
- children: [/* @__PURE__ */ _("dt", {
449
+ children: [/* @__PURE__ */ g("dt", {
449
450
  className: "text-text-secondary",
450
451
  children: C("healthybowl.compliance.icsGrower.status.count", "Inspections recorded")
451
- }), /* @__PURE__ */ _("dd", {
452
+ }), /* @__PURE__ */ g("dd", {
452
453
  className: "font-semibold tabular-nums text-text-primary",
453
454
  children: M.inspectionCount
454
455
  })]
455
456
  }),
456
- /* @__PURE__ */ v("div", {
457
+ /* @__PURE__ */ _("div", {
457
458
  className: "flex items-center justify-between",
458
- children: [/* @__PURE__ */ _("dt", {
459
+ children: [/* @__PURE__ */ g("dt", {
459
460
  className: "text-text-secondary",
460
461
  children: C("healthybowl.compliance.icsGrower.status.latest", "Latest status")
461
- }), /* @__PURE__ */ _("dd", { children: /* @__PURE__ */ _(u, {
462
+ }), /* @__PURE__ */ g("dd", { children: /* @__PURE__ */ g(u, {
462
463
  status: M.lastInspectionStatus,
463
464
  overdue: M.inspectionOverdue
464
465
  }) })]
465
466
  }),
466
- M.lastInspectionDate ? /* @__PURE__ */ v("div", {
467
+ M.lastInspectionDate ? /* @__PURE__ */ _("div", {
467
468
  className: "flex items-center justify-between",
468
- children: [/* @__PURE__ */ _("dt", {
469
+ children: [/* @__PURE__ */ g("dt", {
469
470
  className: "text-text-secondary",
470
471
  children: C("healthybowl.compliance.icsGrower.status.lastDate", "Last inspected")
471
- }), /* @__PURE__ */ _("dd", {
472
+ }), /* @__PURE__ */ g("dd", {
472
473
  className: "text-text-primary",
473
474
  children: t(M.lastInspectionDate)
474
475
  })]
475
476
  }) : null
476
477
  ]
477
478
  })]
478
- }), /* @__PURE__ */ v("section", {
479
+ }), /* @__PURE__ */ _("section", {
479
480
  className: "rounded-xl border border-border-subtle bg-bg-surface p-5",
480
- children: [/* @__PURE__ */ v("h3", {
481
+ children: [/* @__PURE__ */ _("h3", {
481
482
  className: "mb-4 flex items-center gap-2 text-lg font-semibold text-text-primary",
482
- children: [/* @__PURE__ */ _(p, { className: "h-5 w-5 text-text-secondary" }), C("healthybowl.compliance.icsGrower.history.title", "Inspection history")]
483
- }), I.length === 0 ? /* @__PURE__ */ _(a, {
484
- icon: /* @__PURE__ */ _(p, { className: "h-6 w-6" }),
483
+ children: [/* @__PURE__ */ g(p, { className: "h-5 w-5 text-text-secondary" }), C("healthybowl.compliance.icsGrower.history.title", "Inspection history")]
484
+ }), I.length === 0 ? /* @__PURE__ */ g(a, {
485
+ icon: /* @__PURE__ */ g(p, { className: "h-6 w-6" }),
485
486
  title: C("healthybowl.compliance.icsGrower.history.emptyTitle", "No inspections yet"),
486
487
  description: C("healthybowl.compliance.icsGrower.history.emptyDescription", "Record the first internal inspection for this grower using the form.")
487
- }) : /* @__PURE__ */ _("ol", {
488
+ }) : /* @__PURE__ */ g("ol", {
488
489
  className: "relative space-y-4 border-s border-border-subtle ps-5",
489
- children: I.map((e) => /* @__PURE__ */ v("li", {
490
+ children: I.map((e, n) => /* @__PURE__ */ _("li", {
490
491
  className: "relative",
491
492
  children: [
492
- /* @__PURE__ */ _("span", { className: "absolute -start-[1.4rem] top-1 h-2.5 w-2.5 rounded-full bg-border-default" }),
493
- /* @__PURE__ */ v("div", {
493
+ /* @__PURE__ */ g("span", { className: "absolute -start-[1.4rem] top-1 h-2.5 w-2.5 rounded-full bg-border-default" }),
494
+ /* @__PURE__ */ _("div", {
494
495
  className: "flex items-center justify-between gap-2",
495
- children: [/* @__PURE__ */ _("span", {
496
+ children: [/* @__PURE__ */ g("span", {
496
497
  className: "text-sm font-medium text-text-primary",
497
498
  children: t(e.inspectionDate)
498
- }), /* @__PURE__ */ _(u, { status: e.status })]
499
+ }), /* @__PURE__ */ g(u, { status: e.status })]
499
500
  }),
500
- /* @__PURE__ */ v("div", {
501
+ /* @__PURE__ */ _("div", {
501
502
  className: "mt-0.5 text-xs text-text-secondary",
502
503
  children: [e.inspectorName, e.findingsCount > 0 ? ` · ${C("healthybowl.compliance.icsGrower.history.findings", "{{count}} finding(s)", { count: e.findingsCount })}` : ""]
503
504
  }),
504
- e.notes ? /* @__PURE__ */ _("p", {
505
+ e.notes ? /* @__PURE__ */ g("p", {
505
506
  className: "mt-1 whitespace-pre-line text-xs text-text-primary",
506
507
  children: e.notes
507
508
  }) : null,
508
- e.latitude != null && e.longitude != null ? /* @__PURE__ */ v("span", {
509
+ e.latitude != null && e.longitude != null ? /* @__PURE__ */ _("span", {
509
510
  className: "mt-1 inline-flex items-center gap-1 text-xs text-text-secondary",
510
511
  children: [
511
- /* @__PURE__ */ _(g, { className: "h-3 w-3" }),
512
+ /* @__PURE__ */ g(h, { className: "h-3 w-3" }),
512
513
  e.latitude.toFixed(5),
513
514
  ", ",
514
515
  e.longitude.toFixed(5)
515
516
  ]
516
517
  }) : null,
517
- e.photoFileIds.length > 0 ? /* @__PURE__ */ v("div", {
518
+ n < _e && e.photoFileIds.length > 0 ? /* @__PURE__ */ _("div", {
518
519
  className: "mt-2",
519
- children: [/* @__PURE__ */ v("p", {
520
+ children: [/* @__PURE__ */ _("p", {
520
521
  className: "mb-1 flex items-center gap-1 text-xs font-medium text-text-secondary",
521
- children: [/* @__PURE__ */ _(m, { className: "h-3 w-3" }), C("healthybowl.compliance.icsGrower.history.photos", "{{count}} photo(s)", { count: e.photoFileIds.length })]
522
- }), /* @__PURE__ */ _(l, {
522
+ children: [/* @__PURE__ */ g(le, { className: "h-3 w-3" }), C("healthybowl.compliance.icsGrower.history.photos", "{{count}} photo(s)", { count: e.photoFileIds.length })]
523
+ }), /* @__PURE__ */ g(l, {
523
524
  imageIds: e.photoFileIds,
524
- onChange: _e,
525
+ onChange: xe,
525
526
  entity: "Inspection",
526
527
  readOnly: !0
527
528
  })]
@@ -532,9 +533,9 @@ var x = [
532
533
  })]
533
534
  })]
534
535
  }),
535
- /* @__PURE__ */ _(s, {
536
- toasts: ye,
537
- onDismiss: be
536
+ /* @__PURE__ */ g(s, {
537
+ toasts: Se,
538
+ onDismiss: Ce
538
539
  })
539
540
  ]
540
541
  });
@@ -1 +1 @@
1
- {"version":3,"file":"IcsGrowerDetailPage.js","names":[],"sources":["../../../../src/healthybowl/pages/compliance/IcsGrowerDetailPage.tsx"],"sourcesContent":["/**\n * ICS — member grower detail + internal-inspection recorder.\n * Roadmap 10 · BOFF-2882.\n *\n * Route: /healthybowl/compliance/ics/growers/:growerId\n * Records inspections against the real backend. If no SCHEDULED inspection exists the\n * submit handler schedules one first, then records against it. The result status is\n * reported honestly (a FAIL forces FAILED server-side).\n */\nimport { useEffect, useMemo, useState } from 'react';\nimport { useNavigate, useParams } from 'react-router';\nimport { useQuery } from '@apollo/client/react';\nimport { Camera, CalendarClock, ClipboardCheck, FileText, LocateFixed, MapPin, Save } from 'lucide-react';\nimport { Button, Input, Textarea } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { PageLayout, ErrorState, PageLoader, EmptyState, Breadcrumbs, HBEntityImages } from '../../components';\nimport { ToastContainer } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { useBasePath } from '../../hooks/useBasePath';\nimport { GET_ICS_GROWER_DETAIL, useHealthyBowlCompliance } from '../../hooks/useHealthyBowlCompliance';\nimport type {\n ChecklistResult,\n IcsGrowerDetailData,\n IcsInspection,\n InspectionStatus,\n} from '../../hooks/useHealthyBowlCompliance';\nimport { cn, formatDate, todayLocalDate } from '../../utils/helpers';\nimport { InspectionStatusText, RiskDot } from './components';\n\ninterface ControlPoint {\n key: string;\n label: string;\n}\n\nconst CONTROL_POINTS: ControlPoint[] = [\n { key: 'no_prohibited_inputs', label: 'No prohibited inputs stored on farm' },\n { key: 'buffer_zone', label: 'Buffer zone maintained from neighbouring plot' },\n { key: 'spray_diary', label: 'Farm records / spray diary up to date' },\n { key: 'organic_seed', label: 'Organic seed / planting material used' },\n { key: 'compost_manure', label: 'Compost & manure managed correctly' },\n];\n\nconst RESULT_SEGMENTS: Array<{ value: ChecklistResult; labelKey: string; fallback: string; active: string }> = [\n {\n value: 'PASS',\n labelKey: 'healthybowl.compliance.icsGrower.result.pass',\n fallback: 'Pass',\n active: 'bg-success/15 text-success border-success/40',\n },\n {\n value: 'FAIL',\n labelKey: 'healthybowl.compliance.icsGrower.result.fail',\n fallback: 'Fail',\n active: 'bg-status-error-bg/15 text-status-error-text border-status-error-border',\n },\n {\n value: 'NA',\n labelKey: 'healthybowl.compliance.icsGrower.result.na',\n fallback: 'N/A',\n active: 'bg-bg-sunken text-text-primary border-border-default',\n },\n];\n\nconst CONVERSION_LABELS: Record<string, { key: string; fallback: string }> = {\n CONVENTIONAL: { key: 'healthybowl.compliance.icsGrower.conversion.conventional', fallback: 'Conventional' },\n IN_CONVERSION_Y1: { key: 'healthybowl.compliance.icsGrower.conversion.y1', fallback: 'In-conversion — Year 1' },\n IN_CONVERSION_Y2: { key: 'healthybowl.compliance.icsGrower.conversion.y2', fallback: 'In-conversion — Year 2' },\n IN_CONVERSION_Y3: { key: 'healthybowl.compliance.icsGrower.conversion.y3', fallback: 'In-conversion — Year 3' },\n ORGANIC: { key: 'healthybowl.compliance.icsGrower.conversion.organic', fallback: 'Organic (certified)' },\n};\n\n/** `RecordIcsInspectionInput.photoFileIds` is documented as accepting at most 20 ids. */\nconst MAX_INSPECTION_PHOTOS = 20;\n\n/**\n * A recorded inspection's photo set is immutable from this page — the gallery is rendered\n * `readOnly`, which never calls back, so this satisfies the controlled-component contract\n * without pretending the history is editable.\n */\nconst noopImageChange = (): void => undefined;\n\nconst num = (value: string): number | null => {\n const trimmed = value.trim();\n if (trimmed === '') return null;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : null;\n};\n\nconst initialResults = (): Record<string, ChecklistResult> =>\n CONTROL_POINTS.reduce<Record<string, ChecklistResult>>((acc, cp) => {\n acc[cp.key] = 'NA';\n return acc;\n }, {});\n\ninterface ScheduleResponse {\n scheduleHealthyBowlIcsInspection?: { id?: string } | null;\n}\ninterface RecordResponse {\n recordHealthyBowlIcsInspection?: { id?: string; status?: InspectionStatus; findingsCount?: number } | null;\n}\n\nexport const IcsGrowerDetailPage = () => {\n const { t } = useI18n();\n const navigate = useNavigate();\n const { buildPath } = useBasePath();\n const { toast, toasts, dismiss } = useToast();\n const { growerId } = useParams<{ growerId: string }>();\n\n const { context, scheduleInspection, recordInspection } = useHealthyBowlCompliance({ skipSecondary: true });\n\n const { data, loading, error, refetch } = useQuery<IcsGrowerDetailData>(GET_ICS_GROWER_DETAIL, {\n variables: { id: growerId ?? '', context },\n fetchPolicy: 'cache-and-network',\n skip: !growerId,\n });\n\n const detail = data?.getHealthyBowlIcsGrowerDetail ?? null;\n const grower = detail?.grower ?? null;\n const group = detail?.group ?? null;\n const inspections = useMemo(() => detail?.inspections ?? [], [detail]);\n\n const scheduledInspection = useMemo<IcsInspection | null>(\n () => inspections.find((i) => i.status === 'SCHEDULED') ?? null,\n [inspections]\n );\n\n const historyInspections = useMemo(\n () => [...inspections].sort((a, b) => new Date(b.inspectionDate).getTime() - new Date(a.inspectionDate).getTime()),\n [inspections]\n );\n\n // Form state\n const [inspectionDate, setInspectionDate] = useState(todayLocalDate());\n const [inspectorName, setInspectorName] = useState('');\n const [results, setResults] = useState<Record<string, ChecklistResult>>(initialResults);\n const [itemNotes, setItemNotes] = useState<Record<string, string>>({});\n const [notes, setNotes] = useState('');\n const [latitude, setLatitude] = useState('');\n const [longitude, setLongitude] = useState('');\n // Opaque wspace-files-svc ids; `RecordIcsInspectionInput.photoFileIds` accepts at most 20.\n const [photoFileIds, setPhotoFileIds] = useState<string[]>([]);\n const [busy, setBusy] = useState<null | 'submit' | 'draft'>(null);\n\n // Prefill inspector from the scheduled inspection, without clobbering operator edits.\n useEffect(() => {\n if (scheduledInspection?.inspectorName) {\n setInspectorName((prev) => prev || scheduledInspection.inspectorName);\n }\n }, [scheduledInspection]);\n\n const initials = useMemo(() => {\n if (!grower) return '?';\n const parts = grower.fullName.split(/\\s+/).filter(Boolean).slice(0, 2);\n const value = parts.map((p) => p.charAt(0).toUpperCase()).join('');\n return value || '?';\n }, [grower]);\n\n const setResult = (key: string, value: ChecklistResult) => setResults((prev) => ({ ...prev, [key]: value }));\n const setItemNote = (key: string, value: string) => setItemNotes((prev) => ({ ...prev, [key]: value }));\n\n const captureLocation = () => {\n if (typeof navigator === 'undefined' || !('geolocation' in navigator) || !navigator.geolocation) {\n toast({\n title: t('healthybowl.compliance.icsGrower.geo.unavailable', 'Location not available'),\n description: t(\n 'healthybowl.compliance.icsGrower.geo.unavailableDesc',\n 'Your device or browser cannot share a location. Enter the coordinates by hand.'\n ),\n variant: 'warning',\n });\n return;\n }\n navigator.geolocation.getCurrentPosition(\n (pos) => {\n setLatitude(pos.coords.latitude.toFixed(6));\n setLongitude(pos.coords.longitude.toFixed(6));\n toast({ title: t('healthybowl.compliance.icsGrower.geo.captured', 'Location captured'), variant: 'success' });\n },\n (err) => {\n toast({\n title: t('healthybowl.compliance.icsGrower.geo.failed', 'Could not read your location'),\n description: err.message,\n variant: 'warning',\n });\n }\n );\n };\n\n const resetForm = () => {\n setResults(initialResults());\n setItemNotes({});\n setNotes('');\n setLatitude('');\n setLongitude('');\n setPhotoFileIds([]);\n };\n\n const record = async (mode: 'submit' | 'draft') => {\n if (!grower) return;\n if (!inspectorName.trim()) {\n toast({\n title: t('healthybowl.compliance.icsGrower.validation.inspector', 'Inspector name is required'),\n variant: 'warning',\n });\n return;\n }\n if (!inspectionDate) {\n toast({\n title: t('healthybowl.compliance.icsGrower.validation.date', 'Inspection date is required'),\n variant: 'warning',\n });\n return;\n }\n\n setBusy(mode);\n try {\n let inspectionId = scheduledInspection?.id ?? null;\n if (!inspectionId) {\n const scheduled = (await scheduleInspection({\n growerId: grower.id,\n inspectionDate,\n inspectorName: inspectorName.trim(),\n })) as ScheduleResponse | null;\n inspectionId = scheduled?.scheduleHealthyBowlIcsInspection?.id ?? null;\n if (!inspectionId) {\n throw new Error(\n t('healthybowl.compliance.icsGrower.error.schedule', 'Could not open an inspection to record against.')\n );\n }\n }\n\n const checklist = CONTROL_POINTS.map((cp) => {\n const note = itemNotes[cp.key]?.trim();\n return { key: cp.key, label: cp.label, result: results[cp.key], note: note ? note : null };\n });\n\n const recordInput: Record<string, unknown> = {\n id: inspectionId,\n checklist,\n inspectorName: inspectorName.trim(),\n inspectionDate,\n };\n if (mode === 'draft') recordInput.status = 'DRAFT';\n if (notes.trim()) recordInput.notes = notes.trim();\n if (photoFileIds.length > 0) recordInput.photoFileIds = photoFileIds;\n const lat = num(latitude);\n const lng = num(longitude);\n if (lat !== null && lng !== null && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {\n recordInput.latitude = lat;\n recordInput.longitude = lng;\n }\n\n const recorded = (await recordInspection(recordInput)) as RecordResponse | null;\n const finalStatus = recorded?.recordHealthyBowlIcsInspection?.status ?? null;\n const findings = recorded?.recordHealthyBowlIcsInspection?.findingsCount ?? 0;\n\n if (mode === 'draft') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.draft', 'Inspection saved as draft'),\n variant: 'info',\n });\n } else if (finalStatus === 'FAILED') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.failed', 'Recorded as Failed'),\n description:\n findings > 0\n ? t('healthybowl.compliance.icsGrower.toast.failedDesc', '{{count}} control point(s) failed.', {\n count: findings,\n })\n : t('healthybowl.compliance.icsGrower.toast.failedGeneric', 'A control point failed.'),\n variant: 'error',\n });\n } else if (finalStatus === 'CONDITIONAL') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.conditional', 'Recorded as Conditional'),\n variant: 'warning',\n });\n } else if (finalStatus === 'PASSED') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.passed', 'Inspection passed'),\n variant: 'success',\n });\n } else {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.recorded', 'Inspection recorded'),\n variant: 'success',\n });\n }\n\n resetForm();\n await refetch();\n } catch (err) {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.error', 'Could not record the inspection'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setBusy(null);\n }\n };\n\n if (!growerId) {\n return (\n <PageLayout title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}>\n <EmptyState\n icon={<ClipboardCheck className=\"h-6 w-6\" />}\n title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}\n description={t('healthybowl.compliance.icsGrower.notFound.description', 'No grower was specified.')}\n action={\n <Button onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.icsGrower.notFound.action', 'Back to ICS')}\n </Button>\n }\n />\n </PageLayout>\n );\n }\n\n if (loading && !data) {\n return <PageLoader />;\n }\n\n if (error) {\n return (\n <PageLayout title={t('healthybowl.compliance.icsGrower.title', 'Grower')}>\n <ErrorState description={error.message} onRetry={() => void refetch()} />\n </PageLayout>\n );\n }\n\n if (!grower || !group) {\n return (\n <PageLayout title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}>\n <EmptyState\n icon={<ClipboardCheck className=\"h-6 w-6\" />}\n title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}\n description={t(\n 'healthybowl.compliance.icsGrower.notFound.missing',\n 'This grower may have been removed from the Internal Control System.'\n )}\n action={\n <Button onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.icsGrower.notFound.action', 'Back to ICS')}\n </Button>\n }\n />\n </PageLayout>\n );\n }\n\n const conversion = CONVERSION_LABELS[grower.conversionStatus];\n const conversionText = conversion ? t(conversion.key, conversion.fallback) : grower.conversionStatus;\n\n return (\n <PageLayout\n title={grower.fullName}\n description={t('healthybowl.compliance.icsGrower.headerSubtitle', 'ICS member of {{group}}', {\n group: group.name,\n })}\n >\n <Breadcrumbs\n items={[\n { label: t('healthybowl.compliance.breadcrumb.compliance', 'Compliance'), href: buildPath('compliance') },\n { label: t('healthybowl.compliance.breadcrumb.ics', 'ICS'), href: buildPath('compliance/ics') },\n { label: group.name, href: buildPath(`compliance/ics/${group.id}`) },\n { label: grower.fullName },\n ]}\n />\n\n {/* Header card */}\n <div className=\"flex flex-wrap items-center justify-between gap-4 rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <div className=\"flex items-center gap-4\">\n <span className=\"flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-bg-sunken text-lg font-semibold text-text-primary\">\n {initials}\n </span>\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">{grower.fullName}</h2>\n <p className=\"text-sm text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.header.village', 'Village')}: {grower.village}\n {' · '}\n {t('healthybowl.compliance.icsGrower.header.area', 'Plot area')}:{' '}\n {grower.plotAreaHectares != null ? `${grower.plotAreaHectares} ha` : '—'}\n {' · '}\n {t('healthybowl.compliance.icsGrower.header.id', 'Grower ID')}: {grower.memberCode}\n </p>\n <p className=\"mt-1 text-xs text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.header.conversion', 'Conversion')}: {conversionText}\n </p>\n </div>\n </div>\n <div className=\"flex flex-col items-end gap-1\">\n <span className=\"text-xs uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.header.risk', 'Risk')}\n </span>\n <span className=\"inline-flex items-center gap-2 rounded-full border border-border-subtle bg-bg-sunken px-3 py-1\">\n <RiskDot level={grower.riskLevel} />\n </span>\n </div>\n </div>\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n {/* Left — record an inspection */}\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5 lg:col-span-2\">\n <header className=\"mb-4\">\n <h3 className=\"flex items-center gap-2 text-lg font-semibold text-text-primary\">\n <ClipboardCheck className=\"h-5 w-5 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.record.title', 'Record internal inspection')}\n </h3>\n <p className=\"text-sm text-text-secondary\">\n {scheduledInspection\n ? t(\n 'healthybowl.compliance.icsGrower.record.against',\n 'Recording against the inspection scheduled for {{date}}.',\n { date: formatDate(scheduledInspection.inspectionDate) }\n )\n : t(\n 'healthybowl.compliance.icsGrower.record.new',\n 'A new inspection will be opened and recorded in one step.'\n )}\n </p>\n </header>\n\n <div className=\"grid grid-cols-1 gap-4 sm:grid-cols-2\">\n <div>\n <label htmlFor=\"inspection-date\" className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.date', 'Inspection date')}\n </label>\n <Input\n id=\"inspection-date\"\n type=\"date\"\n value={inspectionDate}\n onChange={(e) => setInspectionDate(e.target.value)}\n />\n </div>\n <div>\n <label htmlFor=\"inspection-inspector\" className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.inspector', 'Inspector name')}\n </label>\n <Input\n id=\"inspection-inspector\"\n value={inspectorName}\n onChange={(e) => setInspectorName(e.target.value)}\n placeholder={t('healthybowl.compliance.icsGrower.record.inspectorPlaceholder', 'e.g., Ravi Kumar')}\n />\n </div>\n </div>\n\n {/* Checklist */}\n <div className=\"mt-5 space-y-3\">\n <h4 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.checklist', 'Control points')}\n </h4>\n {CONTROL_POINTS.map((cp) => (\n <div key={cp.key} className=\"rounded-lg border border-border-subtle bg-bg-sunken p-3\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <span className=\"text-sm text-text-primary\">\n {t(`healthybowl.compliance.icsGrower.controlPoints.${cp.key}`, cp.label)}\n </span>\n <div className=\"inline-flex overflow-hidden rounded-md border border-border-subtle\">\n {RESULT_SEGMENTS.map((seg) => {\n const selected = results[cp.key] === seg.value;\n return (\n <button\n key={seg.value}\n type=\"button\"\n onClick={() => setResult(cp.key, seg.value)}\n aria-pressed={selected}\n className={cn(\n 'border-s px-3 py-1.5 text-xs font-medium transition-colors first:border-s-0',\n selected\n ? seg.active\n : 'border-border-subtle bg-bg-surface text-text-secondary hover:text-text-primary'\n )}\n >\n {t(seg.labelKey, seg.fallback)}\n </button>\n );\n })}\n </div>\n </div>\n {results[cp.key] === 'FAIL' ? (\n <Input\n value={itemNotes[cp.key] ?? ''}\n onChange={(e) => setItemNote(cp.key, e.target.value)}\n placeholder={t('healthybowl.compliance.icsGrower.record.itemNote', 'What was found? (optional)')}\n className=\"mt-2 h-9\"\n />\n ) : null}\n </div>\n ))}\n </div>\n\n {/* Photo evidence — persisted on the inspection as `photoFileIds` (max 20). */}\n <div className=\"mt-5\">\n <h4 className=\"mb-1 flex items-center gap-2 text-sm font-semibold text-text-primary\">\n <Camera className=\"h-4 w-4 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.record.photos', 'Photo evidence')}\n </h4>\n <p className=\"mb-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.compliance.icsGrower.record.photosHint',\n 'Attach what you saw — a store of inputs, a buffer strip, a spray diary page. Photos are stored in your workspace Files and stay with this inspection for the certifier.'\n )}\n </p>\n <HBEntityImages\n imageIds={photoFileIds}\n onChange={setPhotoFileIds}\n entity=\"Inspection\"\n max={MAX_INSPECTION_PHOTOS}\n />\n </div>\n\n {/* Notes */}\n <div className=\"mt-5\">\n <label htmlFor=\"inspection-notes\" className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.notes', 'Inspector notes')}\n </label>\n <Textarea\n id=\"inspection-notes\"\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n placeholder={t(\n 'healthybowl.compliance.icsGrower.record.notesPlaceholder',\n 'Overall observations, follow-up actions, corrective measures…'\n )}\n />\n </div>\n\n {/* GPS + actions */}\n <div className=\"mt-4 flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex items-center gap-2\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={captureLocation}>\n <LocateFixed className=\"h-4 w-4\" />\n {t('healthybowl.compliance.icsGrower.record.capture', 'Capture GPS')}\n </Button>\n {latitude.trim() && longitude.trim() ? (\n <span className=\"inline-flex items-center gap-1 text-xs text-text-secondary\">\n <MapPin className=\"h-3.5 w-3.5\" />\n {latitude.trim()}, {longitude.trim()}\n </span>\n ) : null}\n </div>\n <div className=\"flex items-center gap-2\">\n <Button variant=\"outline\" onClick={() => void record('draft')} disabled={busy !== null}>\n <Save className=\"h-4 w-4\" />\n {busy === 'draft'\n ? t('healthybowl.compliance.icsGrower.record.savingDraft', 'Saving…')\n : t('healthybowl.compliance.icsGrower.record.saveDraft', 'Save as draft')}\n </Button>\n <Button onClick={() => void record('submit')} disabled={busy !== null}>\n {busy === 'submit'\n ? t('healthybowl.compliance.icsGrower.record.submitting', 'Submitting…')\n : t('healthybowl.compliance.icsGrower.record.submit', 'Submit inspection')}\n </Button>\n </div>\n </div>\n </section>\n\n {/* Right — history + status */}\n <div className=\"space-y-6\">\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <h3 className=\"mb-1 flex items-center gap-2 text-lg font-semibold text-text-primary\">\n <FileText className=\"h-5 w-5 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.status.title', 'Compliance status')}\n </h3>\n <dl className=\"mt-3 space-y-2 text-sm\">\n <div className=\"flex items-center justify-between\">\n <dt className=\"text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.status.count', 'Inspections recorded')}\n </dt>\n <dd className=\"font-semibold tabular-nums text-text-primary\">{grower.inspectionCount}</dd>\n </div>\n <div className=\"flex items-center justify-between\">\n <dt className=\"text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.status.latest', 'Latest status')}\n </dt>\n <dd>\n <InspectionStatusText status={grower.lastInspectionStatus} overdue={grower.inspectionOverdue} />\n </dd>\n </div>\n {grower.lastInspectionDate ? (\n <div className=\"flex items-center justify-between\">\n <dt className=\"text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.status.lastDate', 'Last inspected')}\n </dt>\n <dd className=\"text-text-primary\">{formatDate(grower.lastInspectionDate)}</dd>\n </div>\n ) : null}\n </dl>\n </section>\n\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <h3 className=\"mb-4 flex items-center gap-2 text-lg font-semibold text-text-primary\">\n <CalendarClock className=\"h-5 w-5 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.history.title', 'Inspection history')}\n </h3>\n {historyInspections.length === 0 ? (\n <EmptyState\n icon={<CalendarClock className=\"h-6 w-6\" />}\n title={t('healthybowl.compliance.icsGrower.history.emptyTitle', 'No inspections yet')}\n description={t(\n 'healthybowl.compliance.icsGrower.history.emptyDescription',\n 'Record the first internal inspection for this grower using the form.'\n )}\n />\n ) : (\n <ol className=\"relative space-y-4 border-s border-border-subtle ps-5\">\n {historyInspections.map((inspection) => (\n <li key={inspection.id} className=\"relative\">\n <span className=\"absolute -start-[1.4rem] top-1 h-2.5 w-2.5 rounded-full bg-border-default\" />\n <div className=\"flex items-center justify-between gap-2\">\n <span className=\"text-sm font-medium text-text-primary\">\n {formatDate(inspection.inspectionDate)}\n </span>\n <InspectionStatusText status={inspection.status} />\n </div>\n <div className=\"mt-0.5 text-xs text-text-secondary\">\n {inspection.inspectorName}\n {inspection.findingsCount > 0\n ? ` · ${t('healthybowl.compliance.icsGrower.history.findings', '{{count}} finding(s)', {\n count: inspection.findingsCount,\n })}`\n : ''}\n </div>\n {inspection.notes ? (\n <p className=\"mt-1 whitespace-pre-line text-xs text-text-primary\">{inspection.notes}</p>\n ) : null}\n {inspection.latitude != null && inspection.longitude != null ? (\n <span className=\"mt-1 inline-flex items-center gap-1 text-xs text-text-secondary\">\n <MapPin className=\"h-3 w-3\" />\n {inspection.latitude.toFixed(5)}, {inspection.longitude.toFixed(5)}\n </span>\n ) : null}\n {inspection.photoFileIds.length > 0 ? (\n <div className=\"mt-2\">\n <p className=\"mb-1 flex items-center gap-1 text-xs font-medium text-text-secondary\">\n <Camera className=\"h-3 w-3\" />\n {t('healthybowl.compliance.icsGrower.history.photos', '{{count}} photo(s)', {\n count: inspection.photoFileIds.length,\n })}\n </p>\n <HBEntityImages\n imageIds={inspection.photoFileIds}\n onChange={noopImageChange}\n entity=\"Inspection\"\n readOnly\n />\n </div>\n ) : null}\n </li>\n ))}\n </ol>\n )}\n </section>\n </div>\n </div>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,IAAM,IAAiC;CACrC;EAAE,KAAK;EAAwB,OAAO;CAAsC;CAC5E;EAAE,KAAK;EAAe,OAAO;CAAgD;CAC7E;EAAE,KAAK;EAAe,OAAO;CAAwC;CACrE;EAAE,KAAK;EAAgB,OAAO;CAAwC;CACtE;EAAE,KAAK;EAAkB,OAAO;CAAqC;AACvE,GAEM,KAAyG;CAC7G;EACE,OAAO;EACP,UAAU;EACV,UAAU;EACV,QAAQ;CACV;CACA;EACE,OAAO;EACP,UAAU;EACV,UAAU;EACV,QAAQ;CACV;CACA;EACE,OA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ance/IcsGrowerDetailPage.tsx"],"sourcesContent":["/**\n * ICS — member grower detail + internal-inspection recorder.\n * Roadmap 10 · BOFF-2882.\n *\n * Route: /healthybowl/compliance/ics/growers/:growerId\n * Records inspections against the real backend. If no SCHEDULED inspection exists the\n * submit handler schedules one first, then records against it. The result status is\n * reported honestly (a FAIL forces FAILED server-side).\n */\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { useNavigate, useParams } from 'react-router';\nimport { useQuery } from '@apollo/client/react';\nimport { Camera, CalendarClock, ClipboardCheck, FileText, LocateFixed, MapPin, Save } from 'lucide-react';\nimport { Button, Input, Textarea } from '@burdenoff/fe-libs/ui';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { PageLayout, ErrorState, PageLoader, EmptyState, Breadcrumbs, HBEntityImages } from '../../components';\nimport { ToastContainer } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { useBasePath } from '../../hooks/useBasePath';\nimport { GET_ICS_GROWER_DETAIL, useHealthyBowlCompliance } from '../../hooks/useHealthyBowlCompliance';\nimport type {\n ChecklistResult,\n IcsGrowerDetailData,\n IcsInspection,\n InspectionStatus,\n} from '../../hooks/useHealthyBowlCompliance';\nimport { cn, formatDate, todayLocalDate } from '../../utils/helpers';\nimport { pickOpenInspection } from '../../utils/icsInspection';\nimport { InspectionStatusText, RiskDot } from './components';\n\ninterface ControlPoint {\n key: string;\n label: string;\n}\n\nconst CONTROL_POINTS: ControlPoint[] = [\n { key: 'no_prohibited_inputs', label: 'No prohibited inputs stored on farm' },\n { key: 'buffer_zone', label: 'Buffer zone maintained from neighbouring plot' },\n { key: 'spray_diary', label: 'Farm records / spray diary up to date' },\n { key: 'organic_seed', label: 'Organic seed / planting material used' },\n { key: 'compost_manure', label: 'Compost & manure managed correctly' },\n];\n\n/**\n * How many history entries render their photo thumbnails. Each thumbnail costs one\n * `getFileDownloadUrl` round-trip and the query returns up to 200 inspections, so an unbounded\n * gallery is an unbounded fan-out. The recent visits are the ones an auditor looks at.\n */\nconst HISTORY_PHOTO_ENTRIES = 5;\n\nconst RESULT_SEGMENTS: Array<{ value: ChecklistResult; labelKey: string; fallback: string; active: string }> = [\n {\n value: 'PASS',\n labelKey: 'healthybowl.compliance.icsGrower.result.pass',\n fallback: 'Pass',\n active: 'bg-success/15 text-success border-success/40',\n },\n {\n value: 'FAIL',\n labelKey: 'healthybowl.compliance.icsGrower.result.fail',\n fallback: 'Fail',\n active: 'bg-status-error-bg/15 text-status-error-text border-status-error-border',\n },\n {\n value: 'NA',\n labelKey: 'healthybowl.compliance.icsGrower.result.na',\n fallback: 'N/A',\n active: 'bg-bg-sunken text-text-primary border-border-default',\n },\n];\n\nconst CONVERSION_LABELS: Record<string, { key: string; fallback: string }> = {\n CONVENTIONAL: { key: 'healthybowl.compliance.icsGrower.conversion.conventional', fallback: 'Conventional' },\n IN_CONVERSION_Y1: { key: 'healthybowl.compliance.icsGrower.conversion.y1', fallback: 'In-conversion — Year 1' },\n IN_CONVERSION_Y2: { key: 'healthybowl.compliance.icsGrower.conversion.y2', fallback: 'In-conversion — Year 2' },\n IN_CONVERSION_Y3: { key: 'healthybowl.compliance.icsGrower.conversion.y3', fallback: 'In-conversion — Year 3' },\n ORGANIC: { key: 'healthybowl.compliance.icsGrower.conversion.organic', fallback: 'Organic (certified)' },\n};\n\n/** `RecordIcsInspectionInput.photoFileIds` is documented as accepting at most 20 ids. */\nconst MAX_INSPECTION_PHOTOS = 20;\n\n/**\n * A recorded inspection's photo set is immutable from this page — the gallery is rendered\n * `readOnly`, which never calls back, so this satisfies the controlled-component contract\n * without pretending the history is editable.\n */\nconst noopImageChange = (): void => undefined;\n\nconst num = (value: string): number | null => {\n const trimmed = value.trim();\n if (trimmed === '') return null;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : null;\n};\n\nconst initialResults = (): Record<string, ChecklistResult> =>\n CONTROL_POINTS.reduce<Record<string, ChecklistResult>>((acc, cp) => {\n acc[cp.key] = 'NA';\n return acc;\n }, {});\n\ninterface ScheduleResponse {\n scheduleHealthyBowlIcsInspection?: { id?: string } | null;\n}\ninterface RecordResponse {\n recordHealthyBowlIcsInspection?: {\n id?: string;\n status?: InspectionStatus;\n findingsCount?: number;\n photoFileIds?: string[];\n } | null;\n}\n\nexport const IcsGrowerDetailPage = () => {\n const { t } = useI18n();\n const navigate = useNavigate();\n const { buildPath } = useBasePath();\n const { toast, toasts, dismiss } = useToast();\n const { growerId } = useParams<{ growerId: string }>();\n\n const { context, scheduleInspection, recordInspection } = useHealthyBowlCompliance({ skipSecondary: true });\n\n const { data, loading, error, refetch } = useQuery<IcsGrowerDetailData>(GET_ICS_GROWER_DETAIL, {\n variables: { id: growerId ?? '', context },\n fetchPolicy: 'cache-and-network',\n skip: !growerId,\n });\n\n const detail = data?.getHealthyBowlIcsGrowerDetail ?? null;\n const grower = detail?.grower ?? null;\n const group = detail?.group ?? null;\n const inspections = useMemo(() => detail?.inspections ?? [], [detail]);\n\n // BOFF-6178: a DRAFT is an open visit too. Matching SCHEDULED only meant \"Save as draft\" stranded\n // the draft — and any photo evidence on it — behind a brand-new scheduled inspection.\n const openInspection = useMemo<IcsInspection | null>(() => pickOpenInspection(inspections), [inspections]);\n\n const historyInspections = useMemo(\n () => [...inspections].sort((a, b) => new Date(b.inspectionDate).getTime() - new Date(a.inspectionDate).getTime()),\n [inspections]\n );\n\n // Form state\n const [inspectionDate, setInspectionDate] = useState(todayLocalDate());\n const [inspectorName, setInspectorName] = useState('');\n const [results, setResults] = useState<Record<string, ChecklistResult>>(initialResults);\n const [itemNotes, setItemNotes] = useState<Record<string, string>>({});\n const [notes, setNotes] = useState('');\n const [latitude, setLatitude] = useState('');\n const [longitude, setLongitude] = useState('');\n // Opaque wspace-files-svc ids; `RecordIcsInspectionInput.photoFileIds` accepts at most 20.\n const [photoFileIds, setPhotoFileIds] = useState<string[]>([]);\n const [busy, setBusy] = useState<null | 'submit' | 'draft'>(null);\n\n // Prefill from the open inspection, without clobbering operator edits. Seeding is keyed on the\n // inspection id so a refetch cannot resurrect a photo the inspector just removed (BOFF-6178).\n const seededFromInspectionId = useRef<string | null>(null);\n useEffect(() => {\n if (!openInspection || seededFromInspectionId.current === openInspection.id) return;\n seededFromInspectionId.current = openInspection.id;\n if (openInspection.inspectorName) {\n setInspectorName((prev) => prev || openInspection.inspectorName);\n }\n setPhotoFileIds((prev) => (prev.length > 0 ? prev : openInspection.photoFileIds));\n }, [openInspection]);\n\n const initials = useMemo(() => {\n if (!grower) return '?';\n const parts = grower.fullName.split(/\\s+/).filter(Boolean).slice(0, 2);\n const value = parts.map((p) => p.charAt(0).toUpperCase()).join('');\n return value || '?';\n }, [grower]);\n\n const setResult = (key: string, value: ChecklistResult) => setResults((prev) => ({ ...prev, [key]: value }));\n const setItemNote = (key: string, value: string) => setItemNotes((prev) => ({ ...prev, [key]: value }));\n\n const captureLocation = () => {\n if (typeof navigator === 'undefined' || !('geolocation' in navigator) || !navigator.geolocation) {\n toast({\n title: t('healthybowl.compliance.icsGrower.geo.unavailable', 'Location not available'),\n description: t(\n 'healthybowl.compliance.icsGrower.geo.unavailableDesc',\n 'Your device or browser cannot share a location. Enter the coordinates by hand.'\n ),\n variant: 'warning',\n });\n return;\n }\n navigator.geolocation.getCurrentPosition(\n (pos) => {\n setLatitude(pos.coords.latitude.toFixed(6));\n setLongitude(pos.coords.longitude.toFixed(6));\n toast({ title: t('healthybowl.compliance.icsGrower.geo.captured', 'Location captured'), variant: 'success' });\n },\n (err) => {\n toast({\n title: t('healthybowl.compliance.icsGrower.geo.failed', 'Could not read your location'),\n description: err.message,\n variant: 'warning',\n });\n }\n );\n };\n\n const resetForm = () => {\n setResults(initialResults());\n setItemNotes({});\n setNotes('');\n setLatitude('');\n setLongitude('');\n setPhotoFileIds([]);\n };\n\n const record = async (mode: 'submit' | 'draft') => {\n if (!grower) return;\n if (!inspectorName.trim()) {\n toast({\n title: t('healthybowl.compliance.icsGrower.validation.inspector', 'Inspector name is required'),\n variant: 'warning',\n });\n return;\n }\n if (!inspectionDate) {\n toast({\n title: t('healthybowl.compliance.icsGrower.validation.date', 'Inspection date is required'),\n variant: 'warning',\n });\n return;\n }\n\n setBusy(mode);\n try {\n let inspectionId = openInspection?.id ?? null;\n if (!inspectionId) {\n const scheduled = (await scheduleInspection({\n growerId: grower.id,\n inspectionDate,\n inspectorName: inspectorName.trim(),\n })) as ScheduleResponse | null;\n inspectionId = scheduled?.scheduleHealthyBowlIcsInspection?.id ?? null;\n if (!inspectionId) {\n throw new Error(\n t('healthybowl.compliance.icsGrower.error.schedule', 'Could not open an inspection to record against.')\n );\n }\n }\n\n const checklist = CONTROL_POINTS.map((cp) => {\n const note = itemNotes[cp.key]?.trim();\n return { key: cp.key, label: cp.label, result: results[cp.key], note: note ? note : null };\n });\n\n const recordInput: Record<string, unknown> = {\n id: inspectionId,\n checklist,\n inspectorName: inspectorName.trim(),\n inspectionDate,\n };\n if (mode === 'draft') recordInput.status = 'DRAFT';\n if (notes.trim()) recordInput.notes = notes.trim();\n const lat = num(latitude);\n const lng = num(longitude);\n if (lat !== null && lng !== null && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {\n recordInput.latitude = lat;\n recordInput.longitude = lng;\n }\n // Always sent, even empty: the provider reads `undefined` as \"leave the stored value alone\", so\n // omitting it would make it impossible to remove the last photo from a resumed draft.\n recordInput.photoFileIds = photoFileIds;\n\n const recorded = (await recordInspection(recordInput)) as RecordResponse | null;\n const finalStatus = recorded?.recordHealthyBowlIcsInspection?.status ?? null;\n const findings = recorded?.recordHealthyBowlIcsInspection?.findingsCount ?? 0;\n\n if (mode === 'draft') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.draft', 'Inspection saved as draft'),\n variant: 'info',\n });\n } else if (finalStatus === 'FAILED') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.failed', 'Recorded as Failed'),\n description:\n findings > 0\n ? t('healthybowl.compliance.icsGrower.toast.failedDesc', '{{count}} control point(s) failed.', {\n count: findings,\n })\n : t('healthybowl.compliance.icsGrower.toast.failedGeneric', 'A control point failed.'),\n variant: 'error',\n });\n } else if (finalStatus === 'CONDITIONAL') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.conditional', 'Recorded as Conditional'),\n variant: 'warning',\n });\n } else if (finalStatus === 'PASSED') {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.passed', 'Inspection passed'),\n variant: 'success',\n });\n } else {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.recorded', 'Inspection recorded'),\n variant: 'success',\n });\n }\n\n // A draft is still being filled in — clearing the form under the inspector would throw away the\n // very work they just saved. Only a completed visit resets (BOFF-6178).\n if (mode !== 'draft') resetForm();\n await refetch();\n } catch (err) {\n toast({\n title: t('healthybowl.compliance.icsGrower.toast.error', 'Could not record the inspection'),\n description: err instanceof Error ? err.message : String(err),\n variant: 'error',\n });\n } finally {\n setBusy(null);\n }\n };\n\n if (!growerId) {\n return (\n <PageLayout title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}>\n <EmptyState\n icon={<ClipboardCheck className=\"h-6 w-6\" />}\n title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}\n description={t('healthybowl.compliance.icsGrower.notFound.description', 'No grower was specified.')}\n action={\n <Button onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.icsGrower.notFound.action', 'Back to ICS')}\n </Button>\n }\n />\n </PageLayout>\n );\n }\n\n if (loading && !data) {\n return <PageLoader />;\n }\n\n if (error) {\n return (\n <PageLayout title={t('healthybowl.compliance.icsGrower.title', 'Grower')}>\n <ErrorState description={error.message} onRetry={() => void refetch()} />\n </PageLayout>\n );\n }\n\n if (!grower || !group) {\n return (\n <PageLayout title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}>\n <EmptyState\n icon={<ClipboardCheck className=\"h-6 w-6\" />}\n title={t('healthybowl.compliance.icsGrower.notFound.title', 'Grower not found')}\n description={t(\n 'healthybowl.compliance.icsGrower.notFound.missing',\n 'This grower may have been removed from the Internal Control System.'\n )}\n action={\n <Button onClick={() => navigate(buildPath('compliance/ics'))}>\n {t('healthybowl.compliance.icsGrower.notFound.action', 'Back to ICS')}\n </Button>\n }\n />\n </PageLayout>\n );\n }\n\n const conversion = CONVERSION_LABELS[grower.conversionStatus];\n const conversionText = conversion ? t(conversion.key, conversion.fallback) : grower.conversionStatus;\n\n return (\n <PageLayout\n title={grower.fullName}\n description={t('healthybowl.compliance.icsGrower.headerSubtitle', 'ICS member of {{group}}', {\n group: group.name,\n })}\n >\n <Breadcrumbs\n items={[\n { label: t('healthybowl.compliance.breadcrumb.compliance', 'Compliance'), href: buildPath('compliance') },\n { label: t('healthybowl.compliance.breadcrumb.ics', 'ICS'), href: buildPath('compliance/ics') },\n { label: group.name, href: buildPath(`compliance/ics/${group.id}`) },\n { label: grower.fullName },\n ]}\n />\n\n {/* Header card */}\n <div className=\"flex flex-wrap items-center justify-between gap-4 rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <div className=\"flex items-center gap-4\">\n <span className=\"flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-bg-sunken text-lg font-semibold text-text-primary\">\n {initials}\n </span>\n <div>\n <h2 className=\"text-lg font-semibold text-text-primary\">{grower.fullName}</h2>\n <p className=\"text-sm text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.header.village', 'Village')}: {grower.village}\n {' · '}\n {t('healthybowl.compliance.icsGrower.header.area', 'Plot area')}:{' '}\n {grower.plotAreaHectares != null ? `${grower.plotAreaHectares} ha` : '—'}\n {' · '}\n {t('healthybowl.compliance.icsGrower.header.id', 'Grower ID')}: {grower.memberCode}\n </p>\n <p className=\"mt-1 text-xs text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.header.conversion', 'Conversion')}: {conversionText}\n </p>\n </div>\n </div>\n <div className=\"flex flex-col items-end gap-1\">\n <span className=\"text-xs uppercase tracking-wide text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.header.risk', 'Risk')}\n </span>\n <span className=\"inline-flex items-center gap-2 rounded-full border border-border-subtle bg-bg-sunken px-3 py-1\">\n <RiskDot level={grower.riskLevel} />\n </span>\n </div>\n </div>\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n {/* Left — record an inspection */}\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5 lg:col-span-2\">\n <header className=\"mb-4\">\n <h3 className=\"flex items-center gap-2 text-lg font-semibold text-text-primary\">\n <ClipboardCheck className=\"h-5 w-5 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.record.title', 'Record internal inspection')}\n </h3>\n <p className=\"text-sm text-text-secondary\">\n {openInspection\n ? openInspection.status === 'DRAFT'\n ? t(\n 'healthybowl.compliance.icsGrower.record.againstDraft',\n 'Continuing the draft inspection saved for {{date}}.',\n { date: formatDate(openInspection.inspectionDate) }\n )\n : t(\n 'healthybowl.compliance.icsGrower.record.against',\n 'Recording against the inspection scheduled for {{date}}.',\n { date: formatDate(openInspection.inspectionDate) }\n )\n : t(\n 'healthybowl.compliance.icsGrower.record.new',\n 'A new inspection will be opened and recorded in one step.'\n )}\n </p>\n </header>\n\n <div className=\"grid grid-cols-1 gap-4 sm:grid-cols-2\">\n <div>\n <label htmlFor=\"inspection-date\" className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.date', 'Inspection date')}\n </label>\n <Input\n id=\"inspection-date\"\n type=\"date\"\n value={inspectionDate}\n onChange={(e) => setInspectionDate(e.target.value)}\n />\n </div>\n <div>\n <label htmlFor=\"inspection-inspector\" className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.inspector', 'Inspector name')}\n </label>\n <Input\n id=\"inspection-inspector\"\n value={inspectorName}\n onChange={(e) => setInspectorName(e.target.value)}\n placeholder={t('healthybowl.compliance.icsGrower.record.inspectorPlaceholder', 'e.g., Ravi Kumar')}\n />\n </div>\n </div>\n\n {/* Checklist */}\n <div className=\"mt-5 space-y-3\">\n <h4 className=\"text-sm font-semibold text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.checklist', 'Control points')}\n </h4>\n {CONTROL_POINTS.map((cp) => (\n <div key={cp.key} className=\"rounded-lg border border-border-subtle bg-bg-sunken p-3\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <span className=\"text-sm text-text-primary\">\n {t(`healthybowl.compliance.icsGrower.controlPoints.${cp.key}`, cp.label)}\n </span>\n <div className=\"inline-flex overflow-hidden rounded-md border border-border-subtle\">\n {RESULT_SEGMENTS.map((seg) => {\n const selected = results[cp.key] === seg.value;\n return (\n <button\n key={seg.value}\n type=\"button\"\n onClick={() => setResult(cp.key, seg.value)}\n aria-pressed={selected}\n className={cn(\n 'border-s px-3 py-1.5 text-xs font-medium transition-colors first:border-s-0',\n selected\n ? seg.active\n : 'border-border-subtle bg-bg-surface text-text-secondary hover:text-text-primary'\n )}\n >\n {t(seg.labelKey, seg.fallback)}\n </button>\n );\n })}\n </div>\n </div>\n {results[cp.key] === 'FAIL' ? (\n <Input\n value={itemNotes[cp.key] ?? ''}\n onChange={(e) => setItemNote(cp.key, e.target.value)}\n placeholder={t('healthybowl.compliance.icsGrower.record.itemNote', 'What was found? (optional)')}\n className=\"mt-2 h-9\"\n />\n ) : null}\n </div>\n ))}\n </div>\n\n {/* Photo evidence — persisted on the inspection as `photoFileIds` (max 20). */}\n <div className=\"mt-5\">\n <h4 className=\"mb-1 flex items-center gap-2 text-sm font-semibold text-text-primary\">\n <Camera className=\"h-4 w-4 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.record.photos', 'Photo evidence')}\n </h4>\n <p className=\"mb-2 text-xs text-text-secondary\">\n {t(\n 'healthybowl.compliance.icsGrower.record.photosHint',\n 'Attach what you saw — a store of inputs, a buffer strip, a spray diary page. Photos are stored in your workspace Files and stay with this inspection for the certifier.'\n )}\n </p>\n <HBEntityImages\n imageIds={photoFileIds}\n onChange={setPhotoFileIds}\n entity=\"Inspection\"\n max={MAX_INSPECTION_PHOTOS}\n />\n </div>\n\n {/* Notes */}\n <div className=\"mt-5\">\n <label htmlFor=\"inspection-notes\" className=\"mb-1 block text-sm font-medium text-text-primary\">\n {t('healthybowl.compliance.icsGrower.record.notes', 'Inspector notes')}\n </label>\n <Textarea\n id=\"inspection-notes\"\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n placeholder={t(\n 'healthybowl.compliance.icsGrower.record.notesPlaceholder',\n 'Overall observations, follow-up actions, corrective measures…'\n )}\n />\n </div>\n\n {/* GPS + actions */}\n <div className=\"mt-4 flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex items-center gap-2\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={captureLocation}>\n <LocateFixed className=\"h-4 w-4\" />\n {t('healthybowl.compliance.icsGrower.record.capture', 'Capture GPS')}\n </Button>\n {latitude.trim() && longitude.trim() ? (\n <span className=\"inline-flex items-center gap-1 text-xs text-text-secondary\">\n <MapPin className=\"h-3.5 w-3.5\" />\n {latitude.trim()}, {longitude.trim()}\n </span>\n ) : null}\n </div>\n <div className=\"flex items-center gap-2\">\n <Button variant=\"outline\" onClick={() => void record('draft')} disabled={busy !== null}>\n <Save className=\"h-4 w-4\" />\n {busy === 'draft'\n ? t('healthybowl.compliance.icsGrower.record.savingDraft', 'Saving…')\n : t('healthybowl.compliance.icsGrower.record.saveDraft', 'Save as draft')}\n </Button>\n <Button onClick={() => void record('submit')} disabled={busy !== null}>\n {busy === 'submit'\n ? t('healthybowl.compliance.icsGrower.record.submitting', 'Submitting…')\n : t('healthybowl.compliance.icsGrower.record.submit', 'Submit inspection')}\n </Button>\n </div>\n </div>\n </section>\n\n {/* Right — history + status */}\n <div className=\"space-y-6\">\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <h3 className=\"mb-1 flex items-center gap-2 text-lg font-semibold text-text-primary\">\n <FileText className=\"h-5 w-5 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.status.title', 'Compliance status')}\n </h3>\n <dl className=\"mt-3 space-y-2 text-sm\">\n <div className=\"flex items-center justify-between\">\n <dt className=\"text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.status.count', 'Inspections recorded')}\n </dt>\n <dd className=\"font-semibold tabular-nums text-text-primary\">{grower.inspectionCount}</dd>\n </div>\n <div className=\"flex items-center justify-between\">\n <dt className=\"text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.status.latest', 'Latest status')}\n </dt>\n <dd>\n <InspectionStatusText status={grower.lastInspectionStatus} overdue={grower.inspectionOverdue} />\n </dd>\n </div>\n {grower.lastInspectionDate ? (\n <div className=\"flex items-center justify-between\">\n <dt className=\"text-text-secondary\">\n {t('healthybowl.compliance.icsGrower.status.lastDate', 'Last inspected')}\n </dt>\n <dd className=\"text-text-primary\">{formatDate(grower.lastInspectionDate)}</dd>\n </div>\n ) : null}\n </dl>\n </section>\n\n <section className=\"rounded-xl border border-border-subtle bg-bg-surface p-5\">\n <h3 className=\"mb-4 flex items-center gap-2 text-lg font-semibold text-text-primary\">\n <CalendarClock className=\"h-5 w-5 text-text-secondary\" />\n {t('healthybowl.compliance.icsGrower.history.title', 'Inspection history')}\n </h3>\n {historyInspections.length === 0 ? (\n <EmptyState\n icon={<CalendarClock className=\"h-6 w-6\" />}\n title={t('healthybowl.compliance.icsGrower.history.emptyTitle', 'No inspections yet')}\n description={t(\n 'healthybowl.compliance.icsGrower.history.emptyDescription',\n 'Record the first internal inspection for this grower using the form.'\n )}\n />\n ) : (\n <ol className=\"relative space-y-4 border-s border-border-subtle ps-5\">\n {historyInspections.map((inspection, index) => (\n <li key={inspection.id} className=\"relative\">\n <span className=\"absolute -start-[1.4rem] top-1 h-2.5 w-2.5 rounded-full bg-border-default\" />\n <div className=\"flex items-center justify-between gap-2\">\n <span className=\"text-sm font-medium text-text-primary\">\n {formatDate(inspection.inspectionDate)}\n </span>\n <InspectionStatusText status={inspection.status} />\n </div>\n <div className=\"mt-0.5 text-xs text-text-secondary\">\n {inspection.inspectorName}\n {inspection.findingsCount > 0\n ? ` · ${t('healthybowl.compliance.icsGrower.history.findings', '{{count}} finding(s)', {\n count: inspection.findingsCount,\n })}`\n : ''}\n </div>\n {inspection.notes ? (\n <p className=\"mt-1 whitespace-pre-line text-xs text-text-primary\">{inspection.notes}</p>\n ) : null}\n {inspection.latitude != null && inspection.longitude != null ? (\n <span className=\"mt-1 inline-flex items-center gap-1 text-xs text-text-secondary\">\n <MapPin className=\"h-3 w-3\" />\n {inspection.latitude.toFixed(5)}, {inspection.longitude.toFixed(5)}\n </span>\n ) : null}\n {index < HISTORY_PHOTO_ENTRIES && inspection.photoFileIds.length > 0 ? (\n <div className=\"mt-2\">\n <p className=\"mb-1 flex items-center gap-1 text-xs font-medium text-text-secondary\">\n <Camera className=\"h-3 w-3\" />\n {t('healthybowl.compliance.icsGrower.history.photos', '{{count}} photo(s)', {\n count: inspection.photoFileIds.length,\n })}\n </p>\n <HBEntityImages\n imageIds={inspection.photoFileIds}\n onChange={noopImageChange}\n entity=\"Inspection\"\n readOnly\n />\n </div>\n ) : null}\n </li>\n ))}\n </ol>\n )}\n </section>\n </div>\n </div>\n\n <ToastContainer toasts={toasts} onDismiss={dismiss} />\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAM,IAAiC;CACrC;EAAE,KAAK;EAAwB,OAAO;CAAsC;CAC5E;EAAE,KAAK;EAAe,OAAO;CAAgD;CAC7E;EAAE,KAAK;EAAe,OAAO;CAAwC;CACrE;EAAE,KAAK;EAAgB,OAAO;CAAwC;CACtE;EAAE,KAAK;EAAkB,OAAO;CAAqC;AACvE,GAOM,KAAwB,GAExB,KAAyG;CAC7G;EACE,OAAO;EACP,UAAU;EACV,UAAU;EACV,QAAQ;CACV;CACA;EACE,OAAO;EACP,UAAU;EACV,UAAU;EACV,QAAQ;CACV;CACA;EACE,OAAO;EACP,UAAU;EACV,UAAU;EACV,QAAQ;CACV;AACF,GAEM,KAA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AEC;OACN;MACF;;GAEL,kBAAC,GAAD;IAAwB;IAAQ,WAAW;GAAU,CAAA;EAC3C;;AAEhB"}
@@ -0,0 +1,18 @@
1
+ //#region src/healthybowl/utils/icsInspection.ts
2
+ var e = ["SCHEDULED", "DRAFT"];
3
+ function t(t) {
4
+ return e.includes(t);
5
+ }
6
+ function n(e) {
7
+ let n = null, r = -Infinity, i = !1;
8
+ for (let a of e) {
9
+ if (!t(a.status)) continue;
10
+ let e = new Date(a.inspectionDate).getTime(), o = Number.isNaN(e) ? -Infinity : e, s = a.status === "DRAFT";
11
+ (n === null || o > r || o === r && s && !i) && (n = a, r = o, i = s);
12
+ }
13
+ return n;
14
+ }
15
+ //#endregion
16
+ export { n as pickOpenInspection };
17
+
18
+ //# sourceMappingURL=icsInspection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"icsInspection.js","names":[],"sources":["../../../src/healthybowl/utils/icsInspection.ts"],"sourcesContent":["/**\n * Which ICS inspection a new recording is written against (BOFF-6178).\n *\n * ### The bug this module exists to close\n *\n * The grower detail page used to look for `status === 'SCHEDULED'` only. \"Save as draft\" writes\n * `DRAFT` (the server honours it as-is), so the *next* recording found no open inspection,\n * scheduled a brand-new one, and stranded the draft together with any photo evidence already\n * uploaded onto it. An inspector's evidence must never be orphaned by the act of saving.\n *\n * So \"open\" means SCHEDULED **or** DRAFT. When both exist we take the most recent by\n * `inspectionDate`, and on an equal date we prefer the DRAFT: a draft holds work the inspector has\n * already done, a schedule holds nothing but an intention.\n *\n * Pure and unit-tested in a `node` environment — no React, no Apollo.\n *\n * @module healthybowl\n */\n\n/** The statuses that mean \"this visit is still being filled in\". */\nexport const OPEN_INSPECTION_STATUSES = ['SCHEDULED', 'DRAFT'] as const;\n\nexport type OpenInspectionStatus = (typeof OPEN_INSPECTION_STATUSES)[number];\n\n/** The minimum shape `pickOpenInspection` needs. Callers pass their full inspection objects. */\nexport interface OpenInspectionLike {\n id: string;\n status: string;\n inspectionDate: string;\n}\n\n/**\n * True when a visit is still open for editing.\n *\n * Derived from `OPEN_INSPECTION_STATUSES` rather than repeating the two literals, so adding a third\n * open status to that array cannot silently leave this predicate behind. The widening cast is needed\n * only because `readonly ['SCHEDULED','DRAFT'].includes()` will not accept an arbitrary `string`;\n * it discards no information, and the return type keeps the narrowing for callers.\n */\nexport function isOpenInspection(status: string): status is OpenInspectionStatus {\n return (OPEN_INSPECTION_STATUSES as readonly string[]).includes(status);\n}\n\n/**\n * The inspection a new recording should update, or `null` when a fresh one must be scheduled.\n *\n * An unparseable `inspectionDate` sorts oldest rather than throwing — a malformed row must not be\n * able to hide a good one, and it must never crash the recorder.\n */\nexport function pickOpenInspection<T extends OpenInspectionLike>(inspections: readonly T[]): T | null {\n let best: T | null = null;\n let bestTime = Number.NEGATIVE_INFINITY;\n let bestIsDraft = false;\n\n for (const inspection of inspections) {\n if (!isOpenInspection(inspection.status)) continue;\n const parsed = new Date(inspection.inspectionDate).getTime();\n const time = Number.isNaN(parsed) ? Number.NEGATIVE_INFINITY : parsed;\n const isDraft = inspection.status === 'DRAFT';\n if (best === null || time > bestTime || (time === bestTime && isDraft && !bestIsDraft)) {\n best = inspection;\n bestTime = time;\n bestIsDraft = isDraft;\n }\n }\n\n return best;\n}\n"],"mappings":";AAoBA,IAAa,IAA2B,CAAC,aAAa,OAAO;AAmB7D,SAAgB,EAAiB,GAAgD;CAC/E,OAAQ,EAA+C,SAAS,CAAM;AACxE;AAQA,SAAgB,EAAiD,GAAqC;CACpG,IAAI,IAAiB,MACjB,IAAW,WACX,IAAc;CAElB,KAAK,IAAM,KAAc,GAAa;EACpC,IAAI,CAAC,EAAiB,EAAW,MAAM,GAAG;EAC1C,IAAM,IAAS,IAAI,KAAK,EAAW,cAAc,EAAE,QAAQ,GACrD,IAAO,OAAO,MAAM,CAAM,IAAI,YAA2B,GACzD,IAAU,EAAW,WAAW;EACtC,CAAI,MAAS,QAAQ,IAAO,KAAa,MAAS,KAAY,KAAW,CAAC,OACxE,IAAO,GACP,IAAW,GACX,IAAc;CAElB;CAEA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.902.34",
3
+ "version": "2026.902.35",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [