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