@burdenoff/microfe-healthybowl 2026.713.16 → 2026.714.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"useHealthyBowlCompliance.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlCompliance.ts"],"sourcesContent":["/**\n * Certification & Compliance depth (NPOP / GLOBALG.A.P. / EUDR) + Internal Control System.\n * Roadmap 10 · BOFF-2882.\n *\n * Documents are declared inline with `gql` rather than as `src/operations/wspace/*.graphql`\n * files, because codegen validates operation documents against the committed\n * `graphql/wspace.graphql` snapshot — which is pulled from the gateway and so cannot know\n * about these fields until the subgraph is live in the supergraph. This is the same\n * escape hatch `useHealthyBowlData` already uses (see CREATE_COMPLIANCE_DOCUMENT_DOC).\n * Types below mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/compliance.gql`.\n *\n * Reads use `cache-and-network`; every write refetches the reads it invalidates, matching\n * the reconciliation contract in `useHealthyBowlData`.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\nconst FALLBACK_WORKSPACE_ID = '00000000-0000-0000-0000-000000000001';\n\n// ── types (mirror compliance.gql) ──────────────────────────────────────────\n\nexport type FlagSeverity = 'INFO' | 'WARNING' | 'CRITICAL';\nexport type FlagStatus = 'OPEN' | 'ACKNOWLEDGED' | 'RESOLVED' | 'DISMISSED';\nexport type FlagType =\n 'BANNED_SUBSTANCE' | 'MRL_EXCEEDED' | 'CERT_EXPIRING' | 'CERT_EXPIRED' | 'INSPECTION_OVERDUE' | 'DOCUMENT_MISSING';\n\nexport type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH';\nexport type ChecklistStatus = 'MISSING' | 'UPLOADED' | 'UNDER_REVIEW' | 'APPROVED' | 'REJECTED' | 'NOT_APPLICABLE';\nexport type InspectionStatus = 'SCHEDULED' | 'DRAFT' | 'PASSED' | 'CONDITIONAL' | 'FAILED';\nexport type ChecklistResult = 'PASS' | 'FAIL' | 'NA';\n\nexport interface ComplianceFlag {\n id: string;\n type: FlagType;\n severity: FlagSeverity;\n status: FlagStatus;\n title: string;\n message: string;\n entityType: string;\n entityId: string | null;\n detectedAt: string;\n resolvedAt: string | null;\n resolvedBy: string | null;\n resolution: string | null;\n metadata: Record<string, unknown> | null;\n}\n\n/** The `Certification` type. */\nexport interface Certification {\n id: string;\n name: string;\n body: string;\n standard: string;\n standardCode: string | null;\n stage: string;\n icsGroupId: string | null;\n issueDate: string;\n expiryDate: string;\n status: string;\n scope: string[];\n daysToExpiry: number;\n expiringSoon: boolean;\n renewalStartedAt: string | null;\n}\n\n/** A `Certification` plus its computed checklist progress (dashboard standards row). */\nexport interface CertificationStandardProgress extends Certification {\n progressPercent: number;\n checklistTotal: number;\n checklistApproved: number;\n}\n\nexport interface IcsInspection {\n id: string;\n icsGroupId: string;\n growerId: string;\n inspectionDate: string;\n inspectorName: string;\n status: InspectionStatus;\n checklist: Array<{ key: string; label: string; result: ChecklistResult; note: string | null }> | null;\n notes: string | null;\n latitude: number | null;\n longitude: number | null;\n photoFileIds: string[];\n findingsCount: number;\n}\n\nexport interface IcsGrower {\n id: string;\n icsGroupId: string;\n memberCode: string;\n fullName: string;\n village: string;\n district: string | null;\n mobile: string | null;\n primaryCrop: string | null;\n plotAreaHectares: number | null;\n conversionStatus: string;\n riskLevel: RiskLevel;\n latitude: number | null;\n longitude: number | null;\n plots: unknown;\n active: boolean;\n lastInspectionDate: string | null;\n lastInspectionStatus: InspectionStatus | null;\n nextInspectionDate: string | null;\n inspectionOverdue: boolean;\n inspectionCount: number;\n}\n\nexport interface IcsGroupSummary {\n id: string;\n name: string;\n code: string;\n registrationNumber: string | null;\n contactPerson: string | null;\n contactPhone: string | null;\n description: string | null;\n status: string;\n certificationId: string | null;\n createdAt: string;\n growerCount: number;\n highRiskCount: number;\n inspectionsOverdue: number;\n totalPlotAreaHectares: number;\n}\n\nexport interface IcsRollup {\n totalGroups: number;\n totalGrowers: number;\n lowRisk: number;\n mediumRisk: number;\n highRisk: number;\n inspectionsPassed: number;\n inspectionsFailed: number;\n inspectionsConditional: number;\n inspectionsScheduled: number;\n inspectionsOverdue: number;\n growersNeverInspected: number;\n totalPlotAreaHectares: number;\n}\n\nexport interface ComplianceOverview {\n activeCertifications: number;\n expiringCertifications: number;\n expiredCertifications: number;\n icsMemberGrowers: number;\n openAuditFindings: number;\n openFlags: number;\n criticalFlags: number;\n standards: CertificationStandardProgress[];\n expiringSoon: CertificationStandardProgress[];\n flags: ComplianceFlag[];\n upcomingInspections: IcsInspection[];\n updatedAt: string;\n}\n\nexport interface StandardTemplateItem {\n code: string;\n label: string;\n description: string;\n required: boolean;\n orderIndex: number;\n}\n\nexport interface StandardTemplate {\n code: string;\n name: string;\n fullName: string;\n issuerHint: string;\n description: string;\n items: StandardTemplateItem[];\n}\n\nexport interface ChecklistItem {\n id: string;\n code: string;\n label: string;\n description: string | null;\n required: boolean;\n status: ChecklistStatus;\n documentId: string | null;\n orderIndex: number;\n completedAt: string | null;\n}\n\nexport interface CertificationDetail {\n certification: Certification;\n standard: StandardTemplate | null;\n checklistItems: ChecklistItem[];\n documents: Array<{\n id: string;\n name: string;\n type: string;\n status: string;\n uploadedDate: string;\n fileId: string | null;\n fileName: string | null;\n fileUrl: string | null;\n }>;\n progressPercent: number;\n requiredCount: number;\n approvedCount: number;\n missingCount: number;\n}\n\nexport interface SubstanceRule {\n id: string;\n substanceName: string;\n activeIngredient: string | null;\n casNumber: string | null;\n standardCode: string | null;\n prohibited: boolean;\n mrlMgPerKg: number | null;\n cropScope: string | null;\n source: string;\n notes: string | null;\n builtin: boolean;\n}\n\nexport interface ResidueTest {\n id: string;\n traceBatchId: string | null;\n cropId: string | null;\n substanceName: string;\n measuredMgPerKg: number;\n testedAt: string;\n laboratory: string | null;\n reportFileId: string | null;\n notes: string | null;\n}\n\nexport interface CertificateOfOrigin {\n id: string;\n certificateNumber: string;\n traceBatchId: string;\n issuedDate: string;\n exporterName: string;\n consigneeName: string | null;\n destinationCountry: string | null;\n productDescription: string;\n quantity: number;\n unit: string;\n hsCode: string | null;\n originCountry: string;\n originRegion: string | null;\n certificationIds: string[];\n declaration: string;\n status: string;\n fileId: string | null;\n fileName: string | null;\n}\n\nexport interface ScanResult {\n scannedAt: string;\n newFlags: number;\n totalOpenFlags: number;\n certificationsExpiring: number;\n certificationsExpired: number;\n bannedSubstanceFlags: number;\n mrlFlags: number;\n overdueInspections: number;\n missingDocuments: number;\n notificationsSent: number;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\n// ── documents ──────────────────────────────────────────────────────────────\n\n/** Fields on the `Certification` type itself. */\nconst CERT_FIELDS = `\n id\n name\n body\n standard\n standardCode\n stage\n icsGroupId\n issueDate\n expiryDate\n status\n scope\n daysToExpiry\n expiringSoon\n renewalStartedAt\n`;\n\n/**\n * `CertificationStandardProgress` = Certification + the computed checklist progress.\n * These extra fields exist ONLY on that type, not on `Certification` — selecting them\n * inside `CertificationDetail.certification` is a validation error.\n */\nconst CERT_PROGRESS_FIELDS = `\n ${CERT_FIELDS}\n progressPercent\n checklistTotal\n checklistApproved\n`;\n\nconst FLAG_FIELDS = `\n id\n type\n severity\n status\n title\n message\n entityType\n entityId\n detectedAt\n resolvedAt\n resolvedBy\n resolution\n metadata\n`;\n\nconst INSPECTION_FIELDS = `\n id\n icsGroupId\n growerId\n inspectionDate\n inspectorName\n status\n checklist\n notes\n latitude\n longitude\n photoFileIds\n findingsCount\n`;\n\nconst GROWER_FIELDS = `\n id\n icsGroupId\n memberCode\n fullName\n village\n district\n mobile\n primaryCrop\n plotAreaHectares\n conversionStatus\n riskLevel\n latitude\n longitude\n plots\n active\n lastInspectionDate\n lastInspectionStatus\n nextInspectionDate\n inspectionOverdue\n inspectionCount\n`;\n\nconst ROLLUP_FIELDS = `\n totalGroups\n totalGrowers\n lowRisk\n mediumRisk\n highRisk\n inspectionsPassed\n inspectionsFailed\n inspectionsConditional\n inspectionsScheduled\n inspectionsOverdue\n growersNeverInspected\n totalPlotAreaHectares\n`;\n\nconst CERT_DETAIL_FIELDS = `\n certification { ${CERT_FIELDS} }\n standard { code name fullName issuerHint description items { code label description required orderIndex } }\n checklistItems { id code label description required status documentId orderIndex completedAt }\n documents { id name type status uploadedDate fileId fileName fileUrl }\n progressPercent\n requiredCount\n approvedCount\n missingCount\n`;\n\nconst GET_OVERVIEW = gql`\n query GetHealthyBowlComplianceOverview($context: ContextInput!) {\n getHealthyBowlComplianceOverview(context: $context) {\n activeCertifications\n expiringCertifications\n expiredCertifications\n icsMemberGrowers\n openAuditFindings\n openFlags\n criticalFlags\n standards { ${CERT_PROGRESS_FIELDS} }\n expiringSoon { ${CERT_PROGRESS_FIELDS} }\n flags { ${FLAG_FIELDS} }\n upcomingInspections { ${INSPECTION_FIELDS} }\n updatedAt\n }\n }\n`;\n\nconst GET_ICS_DATA = gql`\n query GetHealthyBowlIcsData($context: ContextInput!) {\n getHealthyBowlIcsData(context: $context) {\n groups {\n id name code registrationNumber contactPerson contactPhone description status certificationId createdAt\n growerCount highRiskCount inspectionsOverdue totalPlotAreaHectares\n }\n growers { ${GROWER_FIELDS} }\n inspections { ${INSPECTION_FIELDS} }\n rollup { ${ROLLUP_FIELDS} }\n }\n }\n`;\n\nconst GET_ICS_GROUP_DETAIL = gql`\n query GetHealthyBowlIcsGroupDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlIcsGroupDetail(id: $id, context: $context) {\n group { id name code registrationNumber contactPerson contactPhone description status certificationId createdAt }\n certification { id name standard standardCode stage status expiryDate daysToExpiry expiringSoon }\n growers { ${GROWER_FIELDS} }\n inspections { ${INSPECTION_FIELDS} }\n rollup { ${ROLLUP_FIELDS} }\n }\n }\n`;\n\nconst GET_ICS_GROWER_DETAIL = gql`\n query GetHealthyBowlIcsGrowerDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlIcsGrowerDetail(id: $id, context: $context) {\n grower { ${GROWER_FIELDS} }\n group { id name code status certificationId createdAt }\n inspections { ${INSPECTION_FIELDS} }\n }\n }\n`;\n\nconst GET_STANDARDS = gql`\n query GetHealthyBowlCertificationStandards($context: ContextInput!) {\n getHealthyBowlCertificationStandards(context: $context) {\n code\n name\n fullName\n issuerHint\n description\n items {\n code\n label\n description\n required\n orderIndex\n }\n }\n }\n`;\n\nconst GET_CERT_DETAIL = gql`\n query GetHealthyBowlCertificationDetail($id: ID!, $context: ContextInput!) {\n getHealthyBowlCertificationDetail(id: $id, context: $context) { ${CERT_DETAIL_FIELDS} }\n }\n`;\n\nconst GET_FLAGS = gql`\n query GetHealthyBowlComplianceFlags($context: ContextInput!, $status: String, $type: String) {\n getHealthyBowlComplianceFlags(context: $context, status: $status, type: $type) { ${FLAG_FIELDS} }\n }\n`;\n\nconst GET_SUBSTANCE_RULES = gql`\n query GetHealthyBowlSubstanceRules($context: ContextInput!) {\n getHealthyBowlSubstanceRules(context: $context) {\n id\n substanceName\n activeIngredient\n casNumber\n standardCode\n prohibited\n mrlMgPerKg\n cropScope\n source\n notes\n builtin\n }\n }\n`;\n\nconst GET_RESIDUE_TESTS = gql`\n query GetHealthyBowlResidueTests($context: ContextInput!) {\n getHealthyBowlResidueTests(context: $context) {\n id\n traceBatchId\n cropId\n substanceName\n measuredMgPerKg\n testedAt\n laboratory\n reportFileId\n notes\n }\n }\n`;\n\nconst GET_COOS = gql`\n query GetHealthyBowlCertificatesOfOrigin($context: ContextInput!) {\n getHealthyBowlCertificatesOfOrigin(context: $context) {\n id\n certificateNumber\n traceBatchId\n issuedDate\n exporterName\n consigneeName\n destinationCountry\n productDescription\n quantity\n unit\n hsCode\n originCountry\n originRegion\n certificationIds\n declaration\n status\n fileId\n fileName\n }\n }\n`;\n\nconst GET_COO_PDF = gql`\n query GetHealthyBowlCertificateOfOriginPdf($id: ID!, $context: ContextInput!) {\n getHealthyBowlCertificateOfOriginPdf(id: $id, context: $context) {\n id\n certificateNumber\n fileName\n contentType\n pdfBase64\n }\n }\n`;\n\nconst CREATE_ICS_GROUP = gql`\n mutation CreateHealthyBowlIcsGroup($input: CreateIcsGroupInput!) {\n createHealthyBowlIcsGroup(input: $input) {\n id\n name\n code\n status\n }\n }\n`;\nconst UPDATE_ICS_GROUP = gql`\n mutation UpdateHealthyBowlIcsGroup($input: UpdateIcsGroupInput!) {\n updateHealthyBowlIcsGroup(input: $input) {\n id\n name\n code\n status\n }\n }\n`;\nconst DELETE_ICS_GROUP = gql`\n mutation DeleteHealthyBowlIcsGroup($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlIcsGroup(id: $id, context: $context)\n }\n`;\nconst CREATE_ICS_GROWER = gql`\n mutation CreateHealthyBowlIcsGrower($input: CreateIcsGrowerInput!) {\n createHealthyBowlIcsGrower(input: $input) {\n id\n fullName\n riskLevel\n }\n }\n`;\nconst UPDATE_ICS_GROWER = gql`\n mutation UpdateHealthyBowlIcsGrower($input: UpdateIcsGrowerInput!) {\n updateHealthyBowlIcsGrower(input: $input) {\n id\n fullName\n riskLevel\n }\n }\n`;\nconst DELETE_ICS_GROWER = gql`\n mutation DeleteHealthyBowlIcsGrower($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlIcsGrower(id: $id, context: $context)\n }\n`;\nconst SCHEDULE_INSPECTION = gql`\n mutation ScheduleHealthyBowlIcsInspection($input: ScheduleIcsInspectionInput!) {\n scheduleHealthyBowlIcsInspection(input: $input) {\n id\n status\n inspectionDate\n }\n }\n`;\nconst RECORD_INSPECTION = gql`\n mutation RecordHealthyBowlIcsInspection($input: RecordIcsInspectionInput!) {\n recordHealthyBowlIcsInspection(input: $input) {\n id\n status\n findingsCount\n }\n }\n`;\nconst APPLY_STANDARD = gql`\n mutation ApplyHealthyBowlCertificationStandard($input: ApplyCertificationStandardInput!) {\n applyHealthyBowlCertificationStandard(input: $input) {\n progressPercent\n requiredCount\n approvedCount\n missingCount\n }\n }\n`;\nconst UPDATE_CHECKLIST_ITEM = gql`\n mutation UpdateHealthyBowlCertificationChecklistItem($input: UpdateChecklistItemInput!) {\n updateHealthyBowlCertificationChecklistItem(input: $input) {\n progressPercent\n approvedCount\n missingCount\n }\n }\n`;\nconst START_RENEWAL = gql`\n mutation StartHealthyBowlCertificationRenewal($id: ID!, $context: ContextInput!) {\n startHealthyBowlCertificationRenewal(id: $id, context: $context) {\n id\n status\n stage\n renewalStartedAt\n }\n }\n`;\nconst RUN_SCAN = gql`\n mutation RunHealthyBowlComplianceScan($context: ContextInput!) {\n runHealthyBowlComplianceScan(context: $context) {\n scannedAt\n newFlags\n totalOpenFlags\n certificationsExpiring\n certificationsExpired\n bannedSubstanceFlags\n mrlFlags\n overdueInspections\n missingDocuments\n notificationsSent\n }\n }\n`;\nconst ACK_FLAG = gql`\n mutation AcknowledgeHealthyBowlComplianceFlag($id: ID!, $context: ContextInput!) {\n acknowledgeHealthyBowlComplianceFlag(id: $id, context: $context) {\n id\n status\n }\n }\n`;\nconst RESOLVE_FLAG = gql`\n mutation ResolveHealthyBowlComplianceFlag($input: ResolveComplianceFlagInput!) {\n resolveHealthyBowlComplianceFlag(input: $input) {\n id\n status\n resolution\n }\n }\n`;\nconst DISMISS_FLAG = gql`\n mutation DismissHealthyBowlComplianceFlag($input: DismissComplianceFlagInput!) {\n dismissHealthyBowlComplianceFlag(input: $input) {\n id\n status\n resolution\n }\n }\n`;\nconst CREATE_SUBSTANCE_RULE = gql`\n mutation CreateHealthyBowlSubstanceRule($input: CreateComplianceSubstanceRuleInput!) {\n createHealthyBowlSubstanceRule(input: $input) {\n id\n substanceName\n }\n }\n`;\nconst DELETE_SUBSTANCE_RULE = gql`\n mutation DeleteHealthyBowlSubstanceRule($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlSubstanceRule(id: $id, context: $context)\n }\n`;\nconst CREATE_RESIDUE_TEST = gql`\n mutation CreateHealthyBowlResidueTest($input: CreateComplianceResidueTestInput!) {\n createHealthyBowlResidueTest(input: $input) {\n id\n substanceName\n measuredMgPerKg\n }\n }\n`;\nconst DELETE_RESIDUE_TEST = gql`\n mutation DeleteHealthyBowlResidueTest($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlResidueTest(id: $id, context: $context)\n }\n`;\nconst GENERATE_COO = gql`\n mutation GenerateHealthyBowlCertificateOfOrigin($input: GenerateCertificateOfOriginInput!) {\n generateHealthyBowlCertificateOfOrigin(input: $input) {\n id\n certificateNumber\n status\n }\n }\n`;\nconst ATTACH_COO_FILE = gql`\n mutation AttachHealthyBowlCertificateOfOriginFile($input: AttachCertificateOfOriginFileInput!) {\n attachHealthyBowlCertificateOfOriginFile(input: $input) {\n id\n fileId\n fileName\n }\n }\n`;\nconst REVOKE_COO = gql`\n mutation RevokeHealthyBowlCertificateOfOrigin($id: ID!, $context: ContextInput!) {\n revokeHealthyBowlCertificateOfOrigin(id: $id, context: $context) {\n id\n status\n }\n }\n`;\n\n// ── hook ───────────────────────────────────────────────────────────────────\n\nexport interface UseComplianceOptions {\n /** Skip the ICS / rules / residue / CoO reads on pages that only need the overview. */\n skipSecondary?: boolean;\n}\n\nexport function useHealthyBowlCompliance(options: UseComplianceOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const ctx = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n const skip = options.skipSecondary === true;\n\n const overviewQuery = useQuery<{ getHealthyBowlComplianceOverview: ComplianceOverview }, { context: HbContext }>(\n GET_OVERVIEW,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network' }\n );\n\n const icsQuery = useQuery<\n {\n getHealthyBowlIcsData: {\n groups: IcsGroupSummary[];\n growers: IcsGrower[];\n inspections: IcsInspection[];\n rollup: IcsRollup;\n };\n },\n { context: HbContext }\n >(GET_ICS_DATA, { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip });\n\n const standardsQuery = useQuery<{ getHealthyBowlCertificationStandards: StandardTemplate[] }, { context: HbContext }>(\n GET_STANDARDS,\n { variables: { context: ctx }, fetchPolicy: 'cache-first', skip }\n );\n\n const rulesQuery = useQuery<{ getHealthyBowlSubstanceRules: SubstanceRule[] }, { context: HbContext }>(\n GET_SUBSTANCE_RULES,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const residueQuery = useQuery<{ getHealthyBowlResidueTests: ResidueTest[] }, { context: HbContext }>(\n GET_RESIDUE_TESTS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const cooQuery = useQuery<{ getHealthyBowlCertificatesOfOrigin: CertificateOfOrigin[] }, { context: HbContext }>(\n GET_COOS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip }\n );\n\n const flagsQuery = useQuery<\n { getHealthyBowlComplianceFlags: ComplianceFlag[] },\n { context: HbContext; status?: string | null; type?: string | null }\n >(GET_FLAGS, { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip });\n\n const refetchOverview = overviewQuery.refetch;\n const refetchIcs = icsQuery.refetch;\n const refetchFlags = flagsQuery.refetch;\n const refetchRules = rulesQuery.refetch;\n const refetchResidue = residueQuery.refetch;\n const refetchCoos = cooQuery.refetch;\n\n /** Reconcile the reads a write invalidates. Non-fatal: the next load reconciles anyway. */\n const reconcile = useCallback(async (...refetchers: Array<() => Promise<unknown>>) => {\n await Promise.all(\n refetchers.map((run) =>\n run().catch(() => {\n /* non-fatal */\n })\n )\n );\n }, []);\n\n const [createIcsGroupMutation] = useMutation(CREATE_ICS_GROUP);\n const [updateIcsGroupMutation] = useMutation(UPDATE_ICS_GROUP);\n const [deleteIcsGroupMutation] = useMutation(DELETE_ICS_GROUP);\n const [createIcsGrowerMutation] = useMutation(CREATE_ICS_GROWER);\n const [updateIcsGrowerMutation] = useMutation(UPDATE_ICS_GROWER);\n const [deleteIcsGrowerMutation] = useMutation(DELETE_ICS_GROWER);\n const [scheduleInspectionMutation] = useMutation(SCHEDULE_INSPECTION);\n const [recordInspectionMutation] = useMutation(RECORD_INSPECTION);\n const [applyStandardMutation] = useMutation(APPLY_STANDARD);\n const [updateChecklistItemMutation] = useMutation(UPDATE_CHECKLIST_ITEM);\n const [startRenewalMutation] = useMutation(START_RENEWAL);\n // Typed: these two are the only mutations whose response payload a caller reads back.\n const [runScanMutation] = useMutation<{ runHealthyBowlComplianceScan: ScanResult }, { context: HbContext }>(RUN_SCAN);\n const [ackFlagMutation] = useMutation(ACK_FLAG);\n const [resolveFlagMutation] = useMutation(RESOLVE_FLAG);\n const [dismissFlagMutation] = useMutation(DISMISS_FLAG);\n const [createSubstanceRuleMutation] = useMutation(CREATE_SUBSTANCE_RULE);\n const [deleteSubstanceRuleMutation] = useMutation(DELETE_SUBSTANCE_RULE);\n const [createResidueTestMutation] = useMutation(CREATE_RESIDUE_TEST);\n const [deleteResidueTestMutation] = useMutation(DELETE_RESIDUE_TEST);\n const [generateCooMutation] = useMutation<\n { generateHealthyBowlCertificateOfOrigin: { id: string; certificateNumber: string; status: string } },\n { input: Record<string, unknown> }\n >(GENERATE_COO);\n const [attachCooFileMutation] = useMutation(ATTACH_COO_FILE);\n const [revokeCooMutation] = useMutation(REVOKE_COO);\n\n /**\n * Fire a mutation, surface its error, then reconcile the reads it invalidates.\n * Returns `unknown` because the callers below ignore the payload; the two mutations\n * whose payload IS read (runScan, generateCertificateOfOrigin) are typed and called directly.\n */\n const run = useCallback(\n async (\n mutate: (opts: { variables: Record<string, unknown> }) => Promise<{ data?: unknown; error?: unknown }>,\n variables: Record<string, unknown>,\n after: Array<() => Promise<unknown>>\n ): Promise<unknown> => {\n const res = await mutate({ variables });\n if (res.error) {\n throw res.error instanceof Error ? res.error : new Error(String(res.error));\n }\n await reconcile(...after);\n return res.data;\n },\n [reconcile]\n );\n\n const withCtx = useCallback((input: Record<string, unknown>) => ({ ...input, context: ctx }), [ctx]);\n\n return {\n overview: overviewQuery.data?.getHealthyBowlComplianceOverview ?? null,\n ics: icsQuery.data?.getHealthyBowlIcsData ?? null,\n standards: standardsQuery.data?.getHealthyBowlCertificationStandards ?? [],\n substanceRules: rulesQuery.data?.getHealthyBowlSubstanceRules ?? [],\n residueTests: residueQuery.data?.getHealthyBowlResidueTests ?? [],\n certificatesOfOrigin: cooQuery.data?.getHealthyBowlCertificatesOfOrigin ?? [],\n flags: flagsQuery.data?.getHealthyBowlComplianceFlags ?? [],\n\n loading: {\n overview: overviewQuery.loading,\n ics: icsQuery.loading,\n standards: standardsQuery.loading,\n rules: rulesQuery.loading,\n residue: residueQuery.loading,\n coos: cooQuery.loading,\n flags: flagsQuery.loading,\n },\n errors: {\n overview: overviewQuery.error,\n ics: icsQuery.error,\n standards: standardsQuery.error,\n rules: rulesQuery.error,\n residue: residueQuery.error,\n coos: cooQuery.error,\n flags: flagsQuery.error,\n },\n\n refetchAll: useCallback(\n () => reconcile(refetchOverview, refetchIcs, refetchFlags, refetchRules, refetchResidue, refetchCoos),\n [reconcile, refetchOverview, refetchIcs, refetchFlags, refetchRules, refetchResidue, refetchCoos]\n ),\n\n // ICS\n createIcsGroup: useCallback(\n (input: Record<string, unknown>) =>\n run(createIcsGroupMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, createIcsGroupMutation, withCtx, refetchIcs, refetchOverview]\n ),\n updateIcsGroup: useCallback(\n (input: Record<string, unknown>) => run(updateIcsGroupMutation, { input: withCtx(input) }, [refetchIcs]),\n [run, updateIcsGroupMutation, withCtx, refetchIcs]\n ),\n deleteIcsGroup: useCallback(\n (id: string) => run(deleteIcsGroupMutation, { id, context: ctx }, [refetchIcs, refetchOverview]),\n [run, deleteIcsGroupMutation, ctx, refetchIcs, refetchOverview]\n ),\n createIcsGrower: useCallback(\n (input: Record<string, unknown>) =>\n run(createIcsGrowerMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, createIcsGrowerMutation, withCtx, refetchIcs, refetchOverview]\n ),\n updateIcsGrower: useCallback(\n (input: Record<string, unknown>) => run(updateIcsGrowerMutation, { input: withCtx(input) }, [refetchIcs]),\n [run, updateIcsGrowerMutation, withCtx, refetchIcs]\n ),\n deleteIcsGrower: useCallback(\n (id: string) => run(deleteIcsGrowerMutation, { id, context: ctx }, [refetchIcs, refetchOverview]),\n [run, deleteIcsGrowerMutation, ctx, refetchIcs, refetchOverview]\n ),\n scheduleInspection: useCallback(\n (input: Record<string, unknown>) =>\n run(scheduleInspectionMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview]),\n [run, scheduleInspectionMutation, withCtx, refetchIcs, refetchOverview]\n ),\n recordInspection: useCallback(\n (input: Record<string, unknown>) =>\n run(recordInspectionMutation, { input: withCtx(input) }, [refetchIcs, refetchOverview, refetchFlags]),\n [run, recordInspectionMutation, withCtx, refetchIcs, refetchOverview, refetchFlags]\n ),\n\n // Standards\n applyStandard: useCallback(\n (certificationId: string, standardCode?: string) =>\n run(applyStandardMutation, { input: withCtx({ certificationId, ...(standardCode ? { standardCode } : {}) }) }, [\n refetchOverview,\n ]),\n [run, applyStandardMutation, withCtx, refetchOverview]\n ),\n updateChecklistItem: useCallback(\n (id: string, status: ChecklistStatus, documentId?: string | null) =>\n run(\n updateChecklistItemMutation,\n { input: withCtx({ id, status, ...(documentId !== undefined ? { documentId } : {}) }) },\n [refetchOverview, refetchFlags]\n ),\n [run, updateChecklistItemMutation, withCtx, refetchOverview, refetchFlags]\n ),\n\n // Lifecycle\n startRenewal: useCallback(\n (id: string) => run(startRenewalMutation, { id, context: ctx }, [refetchOverview, refetchFlags]),\n [run, startRenewalMutation, ctx, refetchOverview, refetchFlags]\n ),\n runScan: useCallback(async (): Promise<ScanResult | null> => {\n const res = await runScanMutation({ variables: { context: ctx } });\n if (res.error) throw res.error;\n await reconcile(refetchOverview, refetchFlags, refetchIcs);\n return res.data?.runHealthyBowlComplianceScan ?? null;\n }, [runScanMutation, ctx, reconcile, refetchOverview, refetchFlags, refetchIcs]),\n\n // Flags\n acknowledgeFlag: useCallback(\n (id: string) => run(ackFlagMutation, { id, context: ctx }, [refetchFlags, refetchOverview]),\n [run, ackFlagMutation, ctx, refetchFlags, refetchOverview]\n ),\n resolveFlag: useCallback(\n (id: string, resolution: string) =>\n run(resolveFlagMutation, { input: withCtx({ id, resolution }) }, [refetchFlags, refetchOverview]),\n [run, resolveFlagMutation, withCtx, refetchFlags, refetchOverview]\n ),\n dismissFlag: useCallback(\n (id: string, reason: string) =>\n run(dismissFlagMutation, { input: withCtx({ id, reason }) }, [refetchFlags, refetchOverview]),\n [run, dismissFlagMutation, withCtx, refetchFlags, refetchOverview]\n ),\n\n // Substances / residue\n createSubstanceRule: useCallback(\n (input: Record<string, unknown>) => run(createSubstanceRuleMutation, { input: withCtx(input) }, [refetchRules]),\n [run, createSubstanceRuleMutation, withCtx, refetchRules]\n ),\n deleteSubstanceRule: useCallback(\n (id: string) => run(deleteSubstanceRuleMutation, { id, context: ctx }, [refetchRules]),\n [run, deleteSubstanceRuleMutation, ctx, refetchRules]\n ),\n createResidueTest: useCallback(\n (input: Record<string, unknown>) =>\n run(createResidueTestMutation, { input: withCtx(input) }, [refetchResidue, refetchFlags, refetchOverview]),\n [run, createResidueTestMutation, withCtx, refetchResidue, refetchFlags, refetchOverview]\n ),\n deleteResidueTest: useCallback(\n (id: string) => run(deleteResidueTestMutation, { id, context: ctx }, [refetchResidue]),\n [run, deleteResidueTestMutation, ctx, refetchResidue]\n ),\n\n // Certificate of Origin\n generateCertificateOfOrigin: useCallback(\n async (\n input: Record<string, unknown>\n ): Promise<{ id: string; certificateNumber: string; status: string } | null> => {\n const res = await generateCooMutation({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile(refetchCoos);\n return res.data?.generateHealthyBowlCertificateOfOrigin ?? null;\n },\n [generateCooMutation, withCtx, reconcile, refetchCoos]\n ),\n attachCertificateOfOriginFile: useCallback(\n (id: string, fileId: string, fileName?: string) =>\n run(attachCooFileMutation, { input: withCtx({ id, fileId, ...(fileName ? { fileName } : {}) }) }, [\n refetchCoos,\n ]),\n [run, attachCooFileMutation, withCtx, refetchCoos]\n ),\n revokeCertificateOfOrigin: useCallback(\n (id: string) => run(revokeCooMutation, { id, context: ctx }, [refetchCoos]),\n [run, revokeCooMutation, ctx, refetchCoos]\n ),\n\n /** Documents for the pages that need a one-off query (detail views, PDF download). */\n documents: { GET_CERT_DETAIL, GET_ICS_GROUP_DETAIL, GET_ICS_GROWER_DETAIL, GET_COO_PDF },\n context: ctx,\n };\n}\n\nexport { GET_CERT_DETAIL, GET_ICS_GROUP_DETAIL, GET_ICS_GROWER_DETAIL, GET_COO_PDF, GET_FLAGS };\n\nexport interface IcsGroupDetailData {\n getHealthyBowlIcsGroupDetail: {\n group: IcsGroupSummary;\n certification: Pick<\n Certification,\n 'id' | 'name' | 'standard' | 'standardCode' | 'stage' | 'status' | 'expiryDate' | 'daysToExpiry' | 'expiringSoon'\n > | null;\n growers: IcsGrower[];\n inspections: IcsInspection[];\n rollup: IcsRollup;\n };\n}\n\nexport interface IcsGrowerDetailData {\n getHealthyBowlIcsGrowerDetail: {\n grower: IcsGrower;\n group: IcsGroupSummary;\n inspections: IcsInspection[];\n };\n}\n\nexport interface CertificationDetailData {\n getHealthyBowlCertificationDetail: CertificationDetail;\n}\n\nexport interface CooPdfData {\n getHealthyBowlCertificateOfOriginPdf: {\n id: string;\n certificateNumber: string;\n fileName: string;\n contentType: string;\n pdfBase64: string;\n };\n}\n"],"mappings":";;;;;AAoBA,IAAM,KAAwB,wCAgQxB,IAAc,iLAsBd,IAAuB;IACzB,EAAY;;;;GAMV,IAAc,4JAgBd,IAAoB,mKAepB,IAAgB,iTAuBhB,IAAgB,8OAehB,IAAqB;oBACP,EAAY;;;;;;;;GAU1B,KAAe,CAAG;;;;;;;;;;oBAUJ,EAAqB;uBAClB,EAAqB;gBAC5B,EAAY;8BACE,EAAkB;;;;GAM1C,KAAe,CAAG;;;;;;;kBAON,EAAc;sBACV,EAAkB;iBACvB,EAAc;;;GAKzB,IAAuB,CAAG;;;;;k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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'\n | 'MRL_EXCEEDED'\n | 'CERT_EXPIRING'\n | 'CERT_EXPIRED'\n | 'INSPECTION_OVERDUE'\n | '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,wCAqQxB,IAAc,iLAsBd,IAAuB;IACzB,EAAY;;;;GAMV,IAAc,4JAgBd,IAAoB,mKAepB,IAAgB,iTAuBhB,IAAgB,8OAehB,IAAqB;oBACP,EAAY;;;;;;;;GAU1B,KAAe,CAAG;;;;;;;;;;oBAUJ,EAAqB;uBAClB,EAAqB;gBAC5B,EAAY;8BACE,EAAkB;;;;GAM1C,KAAe,CAAG;;;;;;;kBAON,EAAc;sBACV,EAAkB;iBACvB,EAAc;;;GAKzB,IAAuB,CAAG;;;;;kBAKd,EAAc;sBACV,EAAkB;iBACvB,EAAc;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AAiB;GAAsB;GAAuB;GAAa;EACxF,SAAS;EACV"}
@@ -1 +1 @@
1
- {"version":3,"file":"useHealthyBowlSustainability.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlSustainability.ts"],"sourcesContent":["/**\n * Sustainability — Carbon & Climate (GHG / soil-carbon / carbon credits / EUDR / MRV).\n * Roadmap 24 · BOFF-2896.\n *\n * Documents are declared inline with `gql` rather than as `src/operations/*.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\n * know about these fields until the subgraph is live in the supergraph. This mirrors\n * the escape hatch `useHealthyBowlCompliance` already uses.\n *\n * Types below mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/sustainability.gql`\n * field-for-field. Reads use `cache-and-network`; every write refetches the reads it\n * invalidates (Apollo cache does not auto-update these), matching the reconciliation\n * contract in `useHealthyBowlCompliance`.\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// ── enum-like unions (documented String values in the schema) ────────────────\n\nexport type GhgScope = 'SCOPE_1' | 'SCOPE_2' | 'SCOPE_3';\nexport type GhgSourceType = 'DERIVED' | 'MANUAL';\nexport type InventoryStatus = 'DRAFT' | 'LOCKED' | 'VERIFIED';\nexport type PracticeType =\n 'COVER_CROP' | 'NO_TILL' | 'AGROFORESTRY' | 'COMPOST' | 'RESIDUE_RETENTION' | 'ROTATIONAL_GRAZING';\nexport type SoilMethodology = 'MODELED' | 'SOIL_SAMPLED';\nexport type SoilConfidence = 'LOW' | 'MEDIUM' | 'HIGH';\nexport type CreditMethod = 'SOIL_CARBON' | 'AGROFORESTRY' | 'COVER_CROP' | 'NO_TILL';\nexport type CreditRegistry = 'VERRA_VCS' | 'GOLD_STANDARD' | 'OTHER';\nexport type CreditStatus = 'DRAFT' | 'PENDING' | 'VERIFIED' | 'ISSUED' | 'RETIRED';\nexport type DeforestationRisk = 'LOW' | 'STANDARD' | 'HIGH';\nexport type EudrStatus = 'DRAFT' | 'SUBMITTED' | 'VERIFIED';\nexport type NetStatus = 'NET_POSITIVE' | 'NET_EMITTER';\nexport type MrvFormat = 'PDF' | 'CSV';\n\n// ── types (mirror sustainability.gql) ────────────────────────────────────────\n\nexport interface GhgInventory {\n id: string;\n farmId: string;\n farmName: string | null;\n year: number;\n periodStart: string;\n periodEnd: string;\n status: InventoryStatus;\n methodology: string;\n totalScope1: number;\n totalScope2: number;\n totalScope3: number;\n totalCo2e: number;\n sequesteredCo2e: number;\n netCo2e: number;\n intensityPerTonne: number | null;\n lockedAt: string | null;\n verifiedAt: string | null;\n notes: string | null;\n activityCount: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GhgActivity {\n id: string;\n inventoryId: string;\n scope: GhgScope;\n category: string;\n sourceType: GhgSourceType;\n sourceRef: string | null;\n label: string;\n quantity: number;\n unit: string;\n factorKey: string;\n factorValue: number;\n factorSet: string;\n co2e: number;\n activityDate: string;\n}\n\nexport interface ScopeBreakdown {\n scope: GhgScope;\n label: string;\n co2e: number;\n percentage: number;\n}\n\nexport interface SoilCarbonPoint {\n label: string;\n periodEnd: string;\n cumulativeTco2e: number;\n}\n\nexport interface RegenerativePractice {\n id: string;\n farmId: string;\n fieldId: string | null;\n practiceType: PracticeType;\n startDate: string;\n endDate: string | null;\n areaHa: number;\n evidence: Record<string, unknown> | null;\n notes: string | null;\n createdAt: string;\n}\n\nexport interface SoilCarbonEstimate {\n id: string;\n farmId: string;\n fieldId: string | null;\n practiceId: string | null;\n periodStart: string;\n periodEnd: string;\n methodology: SoilMethodology;\n tCo2eSequestered: number;\n baselineSoc: number | null;\n currentSoc: number | null;\n areaHa: number | null;\n confidence: SoilConfidence;\n notes: string | null;\n createdAt: string;\n}\n\nexport interface CarbonCredit {\n id: string;\n farmId: string;\n creditCode: string;\n method: CreditMethod;\n vintageYear: number;\n quantityTCo2e: number;\n registry: CreditRegistry | null;\n status: CreditStatus;\n registrySerial: string | null;\n verifierRef: string | null;\n pricePerCredit: number | null;\n currency: string | null;\n baselinePractice: string | null;\n inventoryId: string | null;\n linkedFieldIds: string[];\n issuedDate: string | null;\n notes: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CarbonCreditList {\n items: CarbonCredit[];\n total: number;\n verifiedCount: number;\n pendingCount: number;\n draftCount: number;\n issuedCount: number;\n totalTco2e: number;\n}\n\nexport interface EudrStatement {\n id: string;\n farmId: string;\n fieldId: string | null;\n traceBatchId: string | null;\n statementCode: string;\n commodity: string;\n plotGeojson: Record<string, unknown> | null;\n plotAreaHa: number | null;\n geoLatitude: number | null;\n geoLongitude: number | null;\n productionDateFrom: string | null;\n productionDateTo: string | null;\n cutoffDate: string;\n deforestationRisk: DeforestationRisk;\n cutoffCompliant: boolean;\n riskAssessment: Record<string, unknown> | null;\n dataSource: string | null;\n lastVerifiedAt: string | null;\n status: EudrStatus;\n statementFileId: string | null;\n dueDiligenceRef: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface EudrExport {\n statementCode: string;\n fileName: string;\n pdfBase64: string;\n fileId: string | null;\n}\n\nexport interface CreditSummary {\n total: number;\n verified: number;\n pending: number;\n draft: number;\n issued: number;\n totalTco2e: number;\n}\n\nexport interface EudrSummary {\n totalPlots: number;\n compliantPlots: number;\n latestStatement: EudrStatement | null;\n}\n\nexport interface CarbonOverview {\n farmId: string | null;\n farmName: string | null;\n farmLocation: string | null;\n year: number;\n hasData: boolean;\n inventory: GhgInventory | null;\n totalEmissions: number;\n emissionsChangePct: number | null;\n sequestered: number;\n netBalance: number;\n netStatus: NetStatus;\n intensityPerTonne: number | null;\n scopeBreakdown: ScopeBreakdown[];\n soilCarbonTrend: SoilCarbonPoint[];\n credits: CreditSummary;\n eudr: EudrSummary;\n}\n\nexport interface MrvReport {\n id: string;\n farmId: string;\n year: number;\n reportCode: string;\n format: MrvFormat;\n reportFileId: string | null;\n summary: Record<string, unknown> | null;\n generatedAt: string;\n pdfBase64: string | null;\n csv: string | null;\n}\n\n/** A farm field for the credit/EUDR pickers (from `getHealthyBowlCropsData`). */\nexport interface SustainabilityField {\n id: string;\n name: string;\n area: number | null;\n unit: string | null;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\n// ── document field selections ────────────────────────────────────────────────\n\nconst INVENTORY_FIELDS = `\n id farmId farmName year periodStart periodEnd status methodology\n totalScope1 totalScope2 totalScope3 totalCo2e sequesteredCo2e netCo2e\n intensityPerTonne lockedAt verifiedAt notes activityCount createdAt updatedAt\n`;\n\nconst ACTIVITY_FIELDS = `\n id inventoryId scope category sourceType sourceRef label quantity unit\n factorKey factorValue factorSet co2e activityDate\n`;\n\nconst PRACTICE_FIELDS = `\n id farmId fieldId practiceType startDate endDate areaHa evidence notes createdAt\n`;\n\nconst SOIL_ESTIMATE_FIELDS = `\n id farmId fieldId practiceId periodStart periodEnd methodology tCo2eSequestered\n baselineSoc currentSoc areaHa confidence notes createdAt\n`;\n\nconst CREDIT_FIELDS = `\n id farmId creditCode method vintageYear quantityTCo2e registry status\n registrySerial verifierRef pricePerCredit currency baselinePractice\n inventoryId linkedFieldIds issuedDate notes createdAt updatedAt\n`;\n\nconst EUDR_FIELDS = `\n id farmId fieldId traceBatchId statementCode commodity plotGeojson plotAreaHa\n geoLatitude geoLongitude productionDateFrom productionDateTo cutoffDate\n deforestationRisk cutoffCompliant riskAssessment dataSource lastVerifiedAt\n status statementFileId dueDiligenceRef createdAt updatedAt\n`;\n\n/** MRV list rows omit the heavy pdfBase64/csv payloads (returned only on generate). */\nconst MRV_LIST_FIELDS = `\n id farmId year reportCode format reportFileId summary generatedAt\n`;\n\n// ── read documents ───────────────────────────────────────────────────────────\n\nconst GET_OVERVIEW = gql`\n query GetHealthyBowlCarbonOverview($context: ContextInput!, $farmId: ID, $year: Int) {\n getHealthyBowlCarbonOverview(context: $context, farmId: $farmId, year: $year) {\n farmId farmName farmLocation year hasData\n inventory { ${INVENTORY_FIELDS} }\n totalEmissions emissionsChangePct sequestered netBalance netStatus intensityPerTonne\n scopeBreakdown { scope label co2e percentage }\n soilCarbonTrend { label periodEnd cumulativeTco2e }\n credits { total verified pending draft issued totalTco2e }\n eudr { totalPlots compliantPlots latestStatement { ${EUDR_FIELDS} } }\n }\n }\n`;\n\nconst GET_GHG_INVENTORY = gql`\n query GetHealthyBowlGhgInventory($context: ContextInput!, $farmId: ID!, $year: Int) {\n getHealthyBowlGhgInventory(context: $context, farmId: $farmId, year: $year) { ${INVENTORY_FIELDS} }\n }\n`;\n\nconst LIST_GHG_ACTIVITIES = gql`\n query ListHealthyBowlGhgActivities($context: ContextInput!, $inventoryId: ID!, $limit: Int, $offset: Int) {\n listHealthyBowlGhgActivities(context: $context, inventoryId: $inventoryId, limit: $limit, offset: $offset) {\n ${ACTIVITY_FIELDS}\n }\n }\n`;\n\nconst LIST_REGEN_PRACTICES = gql`\n query ListHealthyBowlRegenerativePractices($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlRegenerativePractices(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${PRACTICE_FIELDS}\n }\n }\n`;\n\nconst LIST_SOIL_ESTIMATES = gql`\n query ListHealthyBowlSoilCarbonEstimates($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlSoilCarbonEstimates(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${SOIL_ESTIMATE_FIELDS}\n }\n }\n`;\n\nconst LIST_CARBON_CREDITS = gql`\n query ListHealthyBowlCarbonCredits(\n $context: ContextInput!\n $farmId: ID\n $status: String\n $method: String\n $vintageYear: Int\n $limit: Int\n $offset: Int\n ) {\n listHealthyBowlCarbonCredits(\n context: $context\n farmId: $farmId\n status: $status\n method: $method\n vintageYear: $vintageYear\n limit: $limit\n offset: $offset\n ) {\n items { ${CREDIT_FIELDS} }\n total verifiedCount pendingCount draftCount issuedCount totalTco2e\n }\n }\n`;\n\nconst GET_CARBON_CREDIT = gql`\n query GetHealthyBowlCarbonCredit($context: ContextInput!, $id: ID!) {\n getHealthyBowlCarbonCredit(context: $context, id: $id) { ${CREDIT_FIELDS} }\n }\n`;\n\nconst LIST_EUDR_STATEMENTS = gql`\n query ListHealthyBowlEudrStatements($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlEudrStatements(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${EUDR_FIELDS}\n }\n }\n`;\n\nconst GET_EUDR_STATEMENT = gql`\n query GetHealthyBowlEudrStatement($context: ContextInput!, $id: ID!) {\n getHealthyBowlEudrStatement(context: $context, id: $id) { ${EUDR_FIELDS} }\n }\n`;\n\nconst LIST_MRV_REPORTS = gql`\n query ListHealthyBowlMrvReports($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlMrvReports(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${MRV_LIST_FIELDS}\n }\n }\n`;\n\n/** Lightweight farm-fields read for the credit/EUDR pickers (reuses the crops query). */\nconst GET_FIELDS = gql`\n query GetHealthyBowlSustainabilityFields($context: ContextInput!) {\n getHealthyBowlCropsData(context: $context) {\n fields {\n id\n name\n area\n unit\n }\n }\n }\n`;\n\n// ── mutation documents ───────────────────────────────────────────────────────\n\nconst RECOMPUTE_INVENTORY = gql`\n mutation RecomputeHealthyBowlGhgInventory($input: RecomputeHealthyBowlGhgInventoryInput!) {\n recomputeHealthyBowlGhgInventory(input: $input) { ${INVENTORY_FIELDS} }\n }\n`;\nconst LOCK_INVENTORY = gql`\n mutation LockHealthyBowlGhgInventory($context: ContextInput!, $id: ID!) {\n lockHealthyBowlGhgInventory(context: $context, id: $id) {\n id\n status\n lockedAt\n }\n }\n`;\nconst VERIFY_INVENTORY = gql`\n mutation VerifyHealthyBowlGhgInventory($context: ContextInput!, $id: ID!) {\n verifyHealthyBowlGhgInventory(context: $context, id: $id) {\n id\n status\n verifiedAt\n }\n }\n`;\nconst UPSERT_ACTIVITY = gql`\n mutation UpsertHealthyBowlGhgActivity($input: UpsertHealthyBowlGhgActivityInput!) {\n upsertHealthyBowlGhgActivity(input: $input) {\n id\n scope\n label\n co2e\n }\n }\n`;\nconst DELETE_ACTIVITY = gql`\n mutation DeleteHealthyBowlGhgActivity($context: ContextInput!, $id: ID!) {\n deleteHealthyBowlGhgActivity(context: $context, id: $id)\n }\n`;\nconst CREATE_PRACTICE = gql`\n mutation CreateHealthyBowlRegenerativePractice($input: CreateHealthyBowlRegenerativePracticeInput!) {\n createHealthyBowlRegenerativePractice(input: $input) {\n id\n practiceType\n }\n }\n`;\nconst UPSERT_SOIL_ESTIMATE = gql`\n mutation UpsertHealthyBowlSoilCarbonEstimate($input: UpsertHealthyBowlSoilCarbonEstimateInput!) {\n upsertHealthyBowlSoilCarbonEstimate(input: $input) {\n id\n tCo2eSequestered\n }\n }\n`;\nconst CREATE_CREDIT = gql`\n mutation CreateHealthyBowlCarbonCredit($input: CreateHealthyBowlCarbonCreditInput!) {\n createHealthyBowlCarbonCredit(input: $input) {\n id\n creditCode\n status\n quantityTCo2e\n }\n }\n`;\nconst TRANSITION_CREDIT = gql`\n mutation TransitionHealthyBowlCarbonCredit($input: TransitionHealthyBowlCarbonCreditInput!) {\n transitionHealthyBowlCarbonCredit(input: $input) {\n id\n status\n }\n }\n`;\nconst DELETE_CREDIT = gql`\n mutation DeleteHealthyBowlCarbonCredit($context: ContextInput!, $id: ID!) {\n deleteHealthyBowlCarbonCredit(context: $context, id: $id)\n }\n`;\nconst UPSERT_EUDR = gql`\n mutation UpsertHealthyBowlEudrStatement($input: UpsertHealthyBowlEudrStatementInput!) {\n upsertHealthyBowlEudrStatement(input: $input) {\n id\n statementCode\n status\n cutoffCompliant\n }\n }\n`;\nconst EXPORT_EUDR = gql`\n mutation ExportHealthyBowlEudrStatement($context: ContextInput!, $id: ID!) {\n exportHealthyBowlEudrStatement(context: $context, id: $id) {\n statementCode\n fileName\n pdfBase64\n fileId\n }\n }\n`;\nconst DELETE_EUDR = gql`\n mutation DeleteHealthyBowlEudrStatement($context: ContextInput!, $id: ID!) {\n deleteHealthyBowlEudrStatement(context: $context, id: $id)\n }\n`;\nconst GENERATE_MRV = gql`\n mutation GenerateHealthyBowlMrvReport($input: GenerateHealthyBowlMrvReportInput!) {\n generateHealthyBowlMrvReport(input: $input) {\n id\n farmId\n year\n reportCode\n format\n reportFileId\n summary\n generatedAt\n pdfBase64\n csv\n }\n }\n`;\n\n// ── browser-download helpers (base64 → Uint8Array → Blob → anchor click) ─────\n\nfunction triggerDownload(blob: Blob, fileName: string): void {\n if (typeof document === 'undefined') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = fileName;\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n URL.revokeObjectURL(url);\n}\n\nfunction downloadBase64(base64: string, fileName: string, mime: string): void {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n triggerDownload(new Blob([bytes], { type: mime }), fileName);\n}\n\nfunction downloadText(text: string, fileName: string, mime: string): void {\n triggerDownload(new Blob([text], { type: mime }), fileName);\n}\n\n// ── hook options ─────────────────────────────────────────────────────────────\n\nexport interface SustainabilityInclude {\n /** Top few credits for the overview ledger preview. */\n creditsPreview?: boolean;\n /** Full carbon-credit ledger list (honours `creditFilters`). */\n credits?: boolean;\n /** GHG inventory + its activity ledger (the emissions detail page). */\n ghg?: boolean;\n /** Soil-carbon estimates + regenerative practices. */\n soil?: boolean;\n /** EUDR due-diligence statements. */\n eudr?: boolean;\n /** Farm fields for the credit/EUDR pickers. */\n fields?: boolean;\n /** Generated MRV report history. */\n mrvReports?: boolean;\n}\n\nexport interface UseSustainabilityOptions {\n /** Override the farm; otherwise the overview's resolved first-farm id is used. */\n farmId?: string;\n /** Reporting year for the overview + inventory (defaults to current year server-side). */\n year?: number;\n /** Server-side filters for the full credit ledger. */\n creditFilters?: { status?: string; method?: string; vintageYear?: number };\n /** Which secondary reads to load beyond the always-on overview. */\n include?: SustainabilityInclude;\n}\n\nexport function useHealthyBowlSustainability(options: UseSustainabilityOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const ctx = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n\n const include = options.include ?? {};\n const { year, creditFilters } = options;\n\n // ── Overview (always loaded; resolves the farm when none is passed) ──\n const overviewQuery = useQuery<\n { getHealthyBowlCarbonOverview: CarbonOverview },\n { context: HbContext; farmId?: string | null; year?: number | null }\n >(GET_OVERVIEW, {\n variables: { context: ctx, farmId: options.farmId ?? null, year: year ?? null },\n fetchPolicy: 'cache-and-network',\n });\n\n const overview = overviewQuery.data?.getHealthyBowlCarbonOverview ?? null;\n const farmId = options.farmId ?? overview?.farmId ?? null;\n\n // ── GHG inventory + activities (emissions detail) ──\n const ghgInventoryQuery = useQuery<\n { getHealthyBowlGhgInventory: GhgInventory | null },\n { context: HbContext; farmId: string; year?: number | null }\n >(GET_GHG_INVENTORY, {\n variables: { context: ctx, farmId: farmId ?? '', year: year ?? null },\n fetchPolicy: 'cache-and-network',\n skip: !include.ghg || !farmId,\n });\n\n const inventory = ghgInventoryQuery.data?.getHealthyBowlGhgInventory ?? overview?.inventory ?? null;\n const inventoryId = inventory?.id ?? null;\n\n const activitiesQuery = useQuery<\n { listHealthyBowlGhgActivities: GhgActivity[] },\n { context: HbContext; inventoryId: string; limit?: number; offset?: number }\n >(LIST_GHG_ACTIVITIES, {\n variables: { context: ctx, inventoryId: inventoryId ?? '', limit: 200, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.ghg || !inventoryId,\n });\n\n // ── Soil carbon (estimates + practices) ──\n const soilEstimatesQuery = useQuery<\n { listHealthyBowlSoilCarbonEstimates: SoilCarbonEstimate[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_SOIL_ESTIMATES, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 100, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.soil || !farmId,\n });\n\n const practicesQuery = useQuery<\n { listHealthyBowlRegenerativePractices: RegenerativePractice[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_REGEN_PRACTICES, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 100, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.soil || !farmId,\n });\n\n // ── Carbon credits (full ledger + overview preview) ──\n const creditsQuery = useQuery<\n { listHealthyBowlCarbonCredits: CarbonCreditList },\n {\n context: HbContext;\n farmId?: string | null;\n status?: string | null;\n method?: string | null;\n vintageYear?: number | null;\n limit?: number;\n offset?: number;\n }\n >(LIST_CARBON_CREDITS, {\n variables: {\n context: ctx,\n farmId: farmId ?? null,\n status: creditFilters?.status ?? null,\n method: creditFilters?.method ?? null,\n vintageYear: creditFilters?.vintageYear ?? null,\n limit: 200,\n offset: 0,\n },\n fetchPolicy: 'cache-and-network',\n skip: !include.credits || !farmId,\n });\n\n const creditsPreviewQuery = useQuery<\n { listHealthyBowlCarbonCredits: CarbonCreditList },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_CARBON_CREDITS, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 5, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.creditsPreview || !farmId,\n });\n\n // ── EUDR statements ──\n const eudrQuery = useQuery<\n { listHealthyBowlEudrStatements: EudrStatement[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_EUDR_STATEMENTS, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 100, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.eudr || !farmId,\n });\n\n // ── MRV report history ──\n const mrvReportsQuery = useQuery<\n { listHealthyBowlMrvReports: MrvReport[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_MRV_REPORTS, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 50, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.mrvReports || !farmId,\n });\n\n // ── Farm fields for pickers ──\n const fieldsQuery = useQuery<{ getHealthyBowlCropsData: { fields: SustainabilityField[] } }, { context: HbContext }>(\n GET_FIELDS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip: !include.fields }\n );\n\n const refetchOverview = overviewQuery.refetch;\n const refetchInventory = ghgInventoryQuery.refetch;\n const refetchActivities = activitiesQuery.refetch;\n const refetchSoilEstimates = soilEstimatesQuery.refetch;\n const refetchPractices = practicesQuery.refetch;\n const refetchCredits = creditsQuery.refetch;\n const refetchCreditsPreview = creditsPreviewQuery.refetch;\n const refetchEudr = eudrQuery.refetch;\n const refetchMrvReports = mrvReportsQuery.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 // Generic + typed mutation handles.\n const [recomputeMutation] = useMutation<\n { recomputeHealthyBowlGhgInventory: GhgInventory },\n { input: Record<string, unknown> }\n >(RECOMPUTE_INVENTORY);\n const [lockMutation] = useMutation(LOCK_INVENTORY);\n const [verifyMutation] = useMutation(VERIFY_INVENTORY);\n const [upsertActivityMutation] = useMutation(UPSERT_ACTIVITY);\n const [deleteActivityMutation] = useMutation(DELETE_ACTIVITY);\n const [createPracticeMutation] = useMutation(CREATE_PRACTICE);\n const [upsertSoilEstimateMutation] = useMutation(UPSERT_SOIL_ESTIMATE);\n const [createCreditMutation] = useMutation<\n { createHealthyBowlCarbonCredit: { id: string; creditCode: string; status: CreditStatus; quantityTCo2e: number } },\n { input: Record<string, unknown> }\n >(CREATE_CREDIT);\n const [transitionCreditMutation] = useMutation(TRANSITION_CREDIT);\n const [deleteCreditMutation] = useMutation(DELETE_CREDIT);\n const [upsertEudrMutation] = useMutation(UPSERT_EUDR);\n const [exportEudrMutation] = useMutation<\n { exportHealthyBowlEudrStatement: EudrExport },\n { context: HbContext; id: string }\n >(EXPORT_EUDR);\n const [deleteEudrMutation] = useMutation(DELETE_EUDR);\n const [generateMrvMutation] = useMutation<\n { generateHealthyBowlMrvReport: MrvReport },\n { input: Record<string, unknown> }\n >(GENERATE_MRV);\n\n /**\n * Fire a mutation, surface its error, then reconcile the reads it invalidates.\n * Returns `unknown` because these callers ignore the payload; the mutations\n * whose payload IS read (recompute, createCredit, exportEudr, generateMrv) are\n * 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 const inventoryReaders = useMemo(\n () => [refetchOverview, refetchInventory, refetchActivities],\n [refetchOverview, refetchInventory, refetchActivities]\n );\n\n return {\n // reads\n overview,\n inventory,\n activities: activitiesQuery.data?.listHealthyBowlGhgActivities ?? [],\n soilEstimates: soilEstimatesQuery.data?.listHealthyBowlSoilCarbonEstimates ?? [],\n practices: practicesQuery.data?.listHealthyBowlRegenerativePractices ?? [],\n credits: creditsQuery.data?.listHealthyBowlCarbonCredits ?? null,\n creditsPreview: creditsPreviewQuery.data?.listHealthyBowlCarbonCredits ?? null,\n eudrStatements: eudrQuery.data?.listHealthyBowlEudrStatements ?? [],\n mrvReports: mrvReportsQuery.data?.listHealthyBowlMrvReports ?? [],\n fields: fieldsQuery.data?.getHealthyBowlCropsData?.fields ?? [],\n farmId,\n\n loading: {\n overview: overviewQuery.loading,\n inventory: ghgInventoryQuery.loading,\n activities: activitiesQuery.loading,\n soilEstimates: soilEstimatesQuery.loading,\n practices: practicesQuery.loading,\n credits: creditsQuery.loading,\n creditsPreview: creditsPreviewQuery.loading,\n eudr: eudrQuery.loading,\n mrvReports: mrvReportsQuery.loading,\n fields: fieldsQuery.loading,\n },\n errors: {\n overview: overviewQuery.error,\n inventory: ghgInventoryQuery.error,\n activities: activitiesQuery.error,\n soilEstimates: soilEstimatesQuery.error,\n practices: practicesQuery.error,\n credits: creditsQuery.error,\n creditsPreview: creditsPreviewQuery.error,\n eudr: eudrQuery.error,\n mrvReports: mrvReportsQuery.error,\n fields: fieldsQuery.error,\n },\n\n refetchAll: useCallback(\n () =>\n reconcile(\n refetchOverview,\n refetchInventory,\n refetchActivities,\n refetchSoilEstimates,\n refetchPractices,\n refetchCredits,\n refetchCreditsPreview,\n refetchEudr,\n refetchMrvReports\n ),\n [\n reconcile,\n refetchOverview,\n refetchInventory,\n refetchActivities,\n refetchSoilEstimates,\n refetchPractices,\n refetchCredits,\n refetchCreditsPreview,\n refetchEudr,\n refetchMrvReports,\n ]\n ),\n\n // ── GHG inventory ──\n recomputeInventory: useCallback(\n async (targetFarmId: string, targetYear?: number): Promise<GhgInventory | null> => {\n const res = await recomputeMutation({\n variables: { input: { context: ctx, farmId: targetFarmId, ...(targetYear ? { year: targetYear } : {}) } },\n });\n if (res.error) throw res.error;\n await reconcile(...inventoryReaders, refetchCredits, refetchCreditsPreview);\n return res.data?.recomputeHealthyBowlGhgInventory ?? null;\n },\n [recomputeMutation, ctx, reconcile, inventoryReaders, refetchCredits, refetchCreditsPreview]\n ),\n lockInventory: useCallback(\n (id: string) => run(lockMutation, { context: ctx, id }, inventoryReaders),\n [run, lockMutation, ctx, inventoryReaders]\n ),\n verifyInventory: useCallback(\n (id: string) => run(verifyMutation, { context: ctx, id }, inventoryReaders),\n [run, verifyMutation, ctx, inventoryReaders]\n ),\n upsertActivity: useCallback(\n (input: Record<string, unknown>) => run(upsertActivityMutation, { input: withCtx(input) }, inventoryReaders),\n [run, upsertActivityMutation, withCtx, inventoryReaders]\n ),\n deleteActivity: useCallback(\n (id: string) => run(deleteActivityMutation, { context: ctx, id }, inventoryReaders),\n [run, deleteActivityMutation, ctx, inventoryReaders]\n ),\n\n // ── Soil carbon ──\n createPractice: useCallback(\n (input: Record<string, unknown>) =>\n run(createPracticeMutation, { input: withCtx(input) }, [refetchPractices, refetchOverview]),\n [run, createPracticeMutation, withCtx, refetchPractices, refetchOverview]\n ),\n upsertSoilEstimate: useCallback(\n (input: Record<string, unknown>) =>\n run(upsertSoilEstimateMutation, { input: withCtx(input) }, [refetchSoilEstimates, refetchOverview]),\n [run, upsertSoilEstimateMutation, withCtx, refetchSoilEstimates, refetchOverview]\n ),\n\n // ── Carbon credits ──\n createCredit: useCallback(\n async (\n input: Record<string, unknown>\n ): Promise<{ id: string; creditCode: string; status: CreditStatus; quantityTCo2e: number } | null> => {\n const res = await createCreditMutation({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile(refetchCredits, refetchCreditsPreview, refetchOverview);\n return res.data?.createHealthyBowlCarbonCredit ?? null;\n },\n [createCreditMutation, withCtx, reconcile, refetchCredits, refetchCreditsPreview, refetchOverview]\n ),\n transitionCredit: useCallback(\n (input: Record<string, unknown>) =>\n run(transitionCreditMutation, { input: withCtx(input) }, [\n refetchCredits,\n refetchCreditsPreview,\n refetchOverview,\n ]),\n [run, transitionCreditMutation, withCtx, refetchCredits, refetchCreditsPreview, refetchOverview]\n ),\n deleteCredit: useCallback(\n (id: string) =>\n run(deleteCreditMutation, { context: ctx, id }, [refetchCredits, refetchCreditsPreview, refetchOverview]),\n [run, deleteCreditMutation, ctx, refetchCredits, refetchCreditsPreview, refetchOverview]\n ),\n\n // ── EUDR ──\n upsertEudrStatement: useCallback(\n (input: Record<string, unknown>) =>\n run(upsertEudrMutation, { input: withCtx(input) }, [refetchEudr, refetchOverview]),\n [run, upsertEudrMutation, withCtx, refetchEudr, refetchOverview]\n ),\n deleteEudrStatement: useCallback(\n (id: string) => run(deleteEudrMutation, { context: ctx, id }, [refetchEudr, refetchOverview]),\n [run, deleteEudrMutation, ctx, refetchEudr, refetchOverview]\n ),\n /** Render + archive the EUDR PDF, then trigger a browser download of the bytes. */\n exportEudrStatement: useCallback(\n async (id: string): Promise<EudrExport | null> => {\n const res = await exportEudrMutation({ variables: { context: ctx, id } });\n if (res.error) throw res.error;\n const payload = res.data?.exportHealthyBowlEudrStatement ?? null;\n if (payload?.pdfBase64) {\n downloadBase64(payload.pdfBase64, payload.fileName || `${payload.statementCode}.pdf`, 'application/pdf');\n }\n await reconcile(refetchEudr, refetchOverview);\n return payload;\n },\n [exportEudrMutation, ctx, reconcile, refetchEudr, refetchOverview]\n ),\n\n // ── MRV report ──\n /** Assemble + archive the MRV report, then trigger a browser download (PDF or CSV). */\n generateMrvReport: useCallback(\n async (targetFarmId: string, format: MrvFormat = 'PDF', targetYear?: number): Promise<MrvReport | null> => {\n const res = await generateMrvMutation({\n variables: {\n input: { context: ctx, farmId: targetFarmId, format, ...(targetYear ? { year: targetYear } : {}) },\n },\n });\n if (res.error) throw res.error;\n const report = res.data?.generateHealthyBowlMrvReport ?? null;\n if (report) {\n if (report.format === 'CSV' && report.csv) {\n downloadText(report.csv, `${report.reportCode}.csv`, 'text/csv');\n } else if (report.pdfBase64) {\n downloadBase64(report.pdfBase64, `${report.reportCode}.pdf`, 'application/pdf');\n }\n }\n await reconcile(refetchMrvReports);\n return report;\n },\n [generateMrvMutation, ctx, reconcile, refetchMrvReports]\n ),\n\n /** One-off documents for detail reads (credit / EUDR statement). */\n documents: { GET_CARBON_CREDIT, GET_EUDR_STATEMENT },\n context: ctx,\n };\n}\n\nexport { GET_CARBON_CREDIT, GET_EUDR_STATEMENT };\n\nexport interface CarbonCreditData {\n getHealthyBowlCarbonCredit: CarbonCredit;\n}\nexport interface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AAW,OAAO,kBAAkB,GAGnF,MAAM,EAAU,EAAkB,EAC3B;KAET;GAAC;GAAqB;GAAK;GAAW;GAAkB,CACzD;EAGD,WAAW;GAAE;GAAmB;GAAoB;EACpD,SAAS;EACV"}
1
+ {"version":3,"file":"useHealthyBowlSustainability.js","names":[],"sources":["../../../src/healthybowl/hooks/useHealthyBowlSustainability.ts"],"sourcesContent":["/**\n * Sustainability — Carbon & Climate (GHG / soil-carbon / carbon credits / EUDR / MRV).\n * Roadmap 24 · BOFF-2896.\n *\n * Documents are declared inline with `gql` rather than as `src/operations/*.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\n * know about these fields until the subgraph is live in the supergraph. This mirrors\n * the escape hatch `useHealthyBowlCompliance` already uses.\n *\n * Types below mirror `wspace-healthybowl-svc/src/modules/healthybowl/schema/sustainability.gql`\n * field-for-field. Reads use `cache-and-network`; every write refetches the reads it\n * invalidates (Apollo cache does not auto-update these), matching the reconciliation\n * contract in `useHealthyBowlCompliance`.\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// ── enum-like unions (documented String values in the schema) ────────────────\n\nexport type GhgScope = 'SCOPE_1' | 'SCOPE_2' | 'SCOPE_3';\nexport type GhgSourceType = 'DERIVED' | 'MANUAL';\nexport type InventoryStatus = 'DRAFT' | 'LOCKED' | 'VERIFIED';\nexport type PracticeType =\n | 'COVER_CROP'\n | 'NO_TILL'\n | 'AGROFORESTRY'\n | 'COMPOST'\n | 'RESIDUE_RETENTION'\n | 'ROTATIONAL_GRAZING';\nexport type SoilMethodology = 'MODELED' | 'SOIL_SAMPLED';\nexport type SoilConfidence = 'LOW' | 'MEDIUM' | 'HIGH';\nexport type CreditMethod = 'SOIL_CARBON' | 'AGROFORESTRY' | 'COVER_CROP' | 'NO_TILL';\nexport type CreditRegistry = 'VERRA_VCS' | 'GOLD_STANDARD' | 'OTHER';\nexport type CreditStatus = 'DRAFT' | 'PENDING' | 'VERIFIED' | 'ISSUED' | 'RETIRED';\nexport type DeforestationRisk = 'LOW' | 'STANDARD' | 'HIGH';\nexport type EudrStatus = 'DRAFT' | 'SUBMITTED' | 'VERIFIED';\nexport type NetStatus = 'NET_POSITIVE' | 'NET_EMITTER';\nexport type MrvFormat = 'PDF' | 'CSV';\n\n// ── types (mirror sustainability.gql) ────────────────────────────────────────\n\nexport interface GhgInventory {\n id: string;\n farmId: string;\n farmName: string | null;\n year: number;\n periodStart: string;\n periodEnd: string;\n status: InventoryStatus;\n methodology: string;\n totalScope1: number;\n totalScope2: number;\n totalScope3: number;\n totalCo2e: number;\n sequesteredCo2e: number;\n netCo2e: number;\n intensityPerTonne: number | null;\n lockedAt: string | null;\n verifiedAt: string | null;\n notes: string | null;\n activityCount: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GhgActivity {\n id: string;\n inventoryId: string;\n scope: GhgScope;\n category: string;\n sourceType: GhgSourceType;\n sourceRef: string | null;\n label: string;\n quantity: number;\n unit: string;\n factorKey: string;\n factorValue: number;\n factorSet: string;\n co2e: number;\n activityDate: string;\n}\n\nexport interface ScopeBreakdown {\n scope: GhgScope;\n label: string;\n co2e: number;\n percentage: number;\n}\n\nexport interface SoilCarbonPoint {\n label: string;\n periodEnd: string;\n cumulativeTco2e: number;\n}\n\nexport interface RegenerativePractice {\n id: string;\n farmId: string;\n fieldId: string | null;\n practiceType: PracticeType;\n startDate: string;\n endDate: string | null;\n areaHa: number;\n evidence: Record<string, unknown> | null;\n notes: string | null;\n createdAt: string;\n}\n\nexport interface SoilCarbonEstimate {\n id: string;\n farmId: string;\n fieldId: string | null;\n practiceId: string | null;\n periodStart: string;\n periodEnd: string;\n methodology: SoilMethodology;\n tCo2eSequestered: number;\n baselineSoc: number | null;\n currentSoc: number | null;\n areaHa: number | null;\n confidence: SoilConfidence;\n notes: string | null;\n createdAt: string;\n}\n\nexport interface CarbonCredit {\n id: string;\n farmId: string;\n creditCode: string;\n method: CreditMethod;\n vintageYear: number;\n quantityTCo2e: number;\n registry: CreditRegistry | null;\n status: CreditStatus;\n registrySerial: string | null;\n verifierRef: string | null;\n pricePerCredit: number | null;\n currency: string | null;\n baselinePractice: string | null;\n inventoryId: string | null;\n linkedFieldIds: string[];\n issuedDate: string | null;\n notes: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CarbonCreditList {\n items: CarbonCredit[];\n total: number;\n verifiedCount: number;\n pendingCount: number;\n draftCount: number;\n issuedCount: number;\n totalTco2e: number;\n}\n\nexport interface EudrStatement {\n id: string;\n farmId: string;\n fieldId: string | null;\n traceBatchId: string | null;\n statementCode: string;\n commodity: string;\n plotGeojson: Record<string, unknown> | null;\n plotAreaHa: number | null;\n geoLatitude: number | null;\n geoLongitude: number | null;\n productionDateFrom: string | null;\n productionDateTo: string | null;\n cutoffDate: string;\n deforestationRisk: DeforestationRisk;\n cutoffCompliant: boolean;\n riskAssessment: Record<string, unknown> | null;\n dataSource: string | null;\n lastVerifiedAt: string | null;\n status: EudrStatus;\n statementFileId: string | null;\n dueDiligenceRef: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface EudrExport {\n statementCode: string;\n fileName: string;\n pdfBase64: string;\n fileId: string | null;\n}\n\nexport interface CreditSummary {\n total: number;\n verified: number;\n pending: number;\n draft: number;\n issued: number;\n totalTco2e: number;\n}\n\nexport interface EudrSummary {\n totalPlots: number;\n compliantPlots: number;\n latestStatement: EudrStatement | null;\n}\n\nexport interface CarbonOverview {\n farmId: string | null;\n farmName: string | null;\n farmLocation: string | null;\n year: number;\n hasData: boolean;\n inventory: GhgInventory | null;\n totalEmissions: number;\n emissionsChangePct: number | null;\n sequestered: number;\n netBalance: number;\n netStatus: NetStatus;\n intensityPerTonne: number | null;\n scopeBreakdown: ScopeBreakdown[];\n soilCarbonTrend: SoilCarbonPoint[];\n credits: CreditSummary;\n eudr: EudrSummary;\n}\n\nexport interface MrvReport {\n id: string;\n farmId: string;\n year: number;\n reportCode: string;\n format: MrvFormat;\n reportFileId: string | null;\n summary: Record<string, unknown> | null;\n generatedAt: string;\n pdfBase64: string | null;\n csv: string | null;\n}\n\n/** A farm field for the credit/EUDR pickers (from `getHealthyBowlCropsData`). */\nexport interface SustainabilityField {\n id: string;\n name: string;\n area: number | null;\n unit: string | null;\n}\n\ninterface HbContext {\n workspaceId: string;\n}\n\n// ── document field selections ────────────────────────────────────────────────\n\nconst INVENTORY_FIELDS = `\n id farmId farmName year periodStart periodEnd status methodology\n totalScope1 totalScope2 totalScope3 totalCo2e sequesteredCo2e netCo2e\n intensityPerTonne lockedAt verifiedAt notes activityCount createdAt updatedAt\n`;\n\nconst ACTIVITY_FIELDS = `\n id inventoryId scope category sourceType sourceRef label quantity unit\n factorKey factorValue factorSet co2e activityDate\n`;\n\nconst PRACTICE_FIELDS = `\n id farmId fieldId practiceType startDate endDate areaHa evidence notes createdAt\n`;\n\nconst SOIL_ESTIMATE_FIELDS = `\n id farmId fieldId practiceId periodStart periodEnd methodology tCo2eSequestered\n baselineSoc currentSoc areaHa confidence notes createdAt\n`;\n\nconst CREDIT_FIELDS = `\n id farmId creditCode method vintageYear quantityTCo2e registry status\n registrySerial verifierRef pricePerCredit currency baselinePractice\n inventoryId linkedFieldIds issuedDate notes createdAt updatedAt\n`;\n\nconst EUDR_FIELDS = `\n id farmId fieldId traceBatchId statementCode commodity plotGeojson plotAreaHa\n geoLatitude geoLongitude productionDateFrom productionDateTo cutoffDate\n deforestationRisk cutoffCompliant riskAssessment dataSource lastVerifiedAt\n status statementFileId dueDiligenceRef createdAt updatedAt\n`;\n\n/** MRV list rows omit the heavy pdfBase64/csv payloads (returned only on generate). */\nconst MRV_LIST_FIELDS = `\n id farmId year reportCode format reportFileId summary generatedAt\n`;\n\n// ── read documents ───────────────────────────────────────────────────────────\n\nconst GET_OVERVIEW = gql`\n query GetHealthyBowlCarbonOverview($context: ContextInput!, $farmId: ID, $year: Int) {\n getHealthyBowlCarbonOverview(context: $context, farmId: $farmId, year: $year) {\n farmId farmName farmLocation year hasData\n inventory { ${INVENTORY_FIELDS} }\n totalEmissions emissionsChangePct sequestered netBalance netStatus intensityPerTonne\n scopeBreakdown { scope label co2e percentage }\n soilCarbonTrend { label periodEnd cumulativeTco2e }\n credits { total verified pending draft issued totalTco2e }\n eudr { totalPlots compliantPlots latestStatement { ${EUDR_FIELDS} } }\n }\n }\n`;\n\nconst GET_GHG_INVENTORY = gql`\n query GetHealthyBowlGhgInventory($context: ContextInput!, $farmId: ID!, $year: Int) {\n getHealthyBowlGhgInventory(context: $context, farmId: $farmId, year: $year) { ${INVENTORY_FIELDS} }\n }\n`;\n\nconst LIST_GHG_ACTIVITIES = gql`\n query ListHealthyBowlGhgActivities($context: ContextInput!, $inventoryId: ID!, $limit: Int, $offset: Int) {\n listHealthyBowlGhgActivities(context: $context, inventoryId: $inventoryId, limit: $limit, offset: $offset) {\n ${ACTIVITY_FIELDS}\n }\n }\n`;\n\nconst LIST_REGEN_PRACTICES = gql`\n query ListHealthyBowlRegenerativePractices($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlRegenerativePractices(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${PRACTICE_FIELDS}\n }\n }\n`;\n\nconst LIST_SOIL_ESTIMATES = gql`\n query ListHealthyBowlSoilCarbonEstimates($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlSoilCarbonEstimates(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${SOIL_ESTIMATE_FIELDS}\n }\n }\n`;\n\nconst LIST_CARBON_CREDITS = gql`\n query ListHealthyBowlCarbonCredits(\n $context: ContextInput!\n $farmId: ID\n $status: String\n $method: String\n $vintageYear: Int\n $limit: Int\n $offset: Int\n ) {\n listHealthyBowlCarbonCredits(\n context: $context\n farmId: $farmId\n status: $status\n method: $method\n vintageYear: $vintageYear\n limit: $limit\n offset: $offset\n ) {\n items { ${CREDIT_FIELDS} }\n total verifiedCount pendingCount draftCount issuedCount totalTco2e\n }\n }\n`;\n\nconst GET_CARBON_CREDIT = gql`\n query GetHealthyBowlCarbonCredit($context: ContextInput!, $id: ID!) {\n getHealthyBowlCarbonCredit(context: $context, id: $id) { ${CREDIT_FIELDS} }\n }\n`;\n\nconst LIST_EUDR_STATEMENTS = gql`\n query ListHealthyBowlEudrStatements($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlEudrStatements(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${EUDR_FIELDS}\n }\n }\n`;\n\nconst GET_EUDR_STATEMENT = gql`\n query GetHealthyBowlEudrStatement($context: ContextInput!, $id: ID!) {\n getHealthyBowlEudrStatement(context: $context, id: $id) { ${EUDR_FIELDS} }\n }\n`;\n\nconst LIST_MRV_REPORTS = gql`\n query ListHealthyBowlMrvReports($context: ContextInput!, $farmId: ID, $limit: Int, $offset: Int) {\n listHealthyBowlMrvReports(context: $context, farmId: $farmId, limit: $limit, offset: $offset) {\n ${MRV_LIST_FIELDS}\n }\n }\n`;\n\n/** Lightweight farm-fields read for the credit/EUDR pickers (reuses the crops query). */\nconst GET_FIELDS = gql`\n query GetHealthyBowlSustainabilityFields($context: ContextInput!) {\n getHealthyBowlCropsData(context: $context) {\n fields {\n id\n name\n area\n unit\n }\n }\n }\n`;\n\n// ── mutation documents ───────────────────────────────────────────────────────\n\nconst RECOMPUTE_INVENTORY = gql`\n mutation RecomputeHealthyBowlGhgInventory($input: RecomputeHealthyBowlGhgInventoryInput!) {\n recomputeHealthyBowlGhgInventory(input: $input) { ${INVENTORY_FIELDS} }\n }\n`;\nconst LOCK_INVENTORY = gql`\n mutation LockHealthyBowlGhgInventory($context: ContextInput!, $id: ID!) {\n lockHealthyBowlGhgInventory(context: $context, id: $id) {\n id\n status\n lockedAt\n }\n }\n`;\nconst VERIFY_INVENTORY = gql`\n mutation VerifyHealthyBowlGhgInventory($context: ContextInput!, $id: ID!) {\n verifyHealthyBowlGhgInventory(context: $context, id: $id) {\n id\n status\n verifiedAt\n }\n }\n`;\nconst UPSERT_ACTIVITY = gql`\n mutation UpsertHealthyBowlGhgActivity($input: UpsertHealthyBowlGhgActivityInput!) {\n upsertHealthyBowlGhgActivity(input: $input) {\n id\n scope\n label\n co2e\n }\n }\n`;\nconst DELETE_ACTIVITY = gql`\n mutation DeleteHealthyBowlGhgActivity($context: ContextInput!, $id: ID!) {\n deleteHealthyBowlGhgActivity(context: $context, id: $id)\n }\n`;\nconst CREATE_PRACTICE = gql`\n mutation CreateHealthyBowlRegenerativePractice($input: CreateHealthyBowlRegenerativePracticeInput!) {\n createHealthyBowlRegenerativePractice(input: $input) {\n id\n practiceType\n }\n }\n`;\nconst UPSERT_SOIL_ESTIMATE = gql`\n mutation UpsertHealthyBowlSoilCarbonEstimate($input: UpsertHealthyBowlSoilCarbonEstimateInput!) {\n upsertHealthyBowlSoilCarbonEstimate(input: $input) {\n id\n tCo2eSequestered\n }\n }\n`;\nconst CREATE_CREDIT = gql`\n mutation CreateHealthyBowlCarbonCredit($input: CreateHealthyBowlCarbonCreditInput!) {\n createHealthyBowlCarbonCredit(input: $input) {\n id\n creditCode\n status\n quantityTCo2e\n }\n }\n`;\nconst TRANSITION_CREDIT = gql`\n mutation TransitionHealthyBowlCarbonCredit($input: TransitionHealthyBowlCarbonCreditInput!) {\n transitionHealthyBowlCarbonCredit(input: $input) {\n id\n status\n }\n }\n`;\nconst DELETE_CREDIT = gql`\n mutation DeleteHealthyBowlCarbonCredit($context: ContextInput!, $id: ID!) {\n deleteHealthyBowlCarbonCredit(context: $context, id: $id)\n }\n`;\nconst UPSERT_EUDR = gql`\n mutation UpsertHealthyBowlEudrStatement($input: UpsertHealthyBowlEudrStatementInput!) {\n upsertHealthyBowlEudrStatement(input: $input) {\n id\n statementCode\n status\n cutoffCompliant\n }\n }\n`;\nconst EXPORT_EUDR = gql`\n mutation ExportHealthyBowlEudrStatement($context: ContextInput!, $id: ID!) {\n exportHealthyBowlEudrStatement(context: $context, id: $id) {\n statementCode\n fileName\n pdfBase64\n fileId\n }\n }\n`;\nconst DELETE_EUDR = gql`\n mutation DeleteHealthyBowlEudrStatement($context: ContextInput!, $id: ID!) {\n deleteHealthyBowlEudrStatement(context: $context, id: $id)\n }\n`;\nconst GENERATE_MRV = gql`\n mutation GenerateHealthyBowlMrvReport($input: GenerateHealthyBowlMrvReportInput!) {\n generateHealthyBowlMrvReport(input: $input) {\n id\n farmId\n year\n reportCode\n format\n reportFileId\n summary\n generatedAt\n pdfBase64\n csv\n }\n }\n`;\n\n// ── browser-download helpers (base64 → Uint8Array → Blob → anchor click) ─────\n\nfunction triggerDownload(blob: Blob, fileName: string): void {\n if (typeof document === 'undefined') return;\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = url;\n anchor.download = fileName;\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n URL.revokeObjectURL(url);\n}\n\nfunction downloadBase64(base64: string, fileName: string, mime: string): void {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n triggerDownload(new Blob([bytes], { type: mime }), fileName);\n}\n\nfunction downloadText(text: string, fileName: string, mime: string): void {\n triggerDownload(new Blob([text], { type: mime }), fileName);\n}\n\n// ── hook options ─────────────────────────────────────────────────────────────\n\nexport interface SustainabilityInclude {\n /** Top few credits for the overview ledger preview. */\n creditsPreview?: boolean;\n /** Full carbon-credit ledger list (honours `creditFilters`). */\n credits?: boolean;\n /** GHG inventory + its activity ledger (the emissions detail page). */\n ghg?: boolean;\n /** Soil-carbon estimates + regenerative practices. */\n soil?: boolean;\n /** EUDR due-diligence statements. */\n eudr?: boolean;\n /** Farm fields for the credit/EUDR pickers. */\n fields?: boolean;\n /** Generated MRV report history. */\n mrvReports?: boolean;\n}\n\nexport interface UseSustainabilityOptions {\n /** Override the farm; otherwise the overview's resolved first-farm id is used. */\n farmId?: string;\n /** Reporting year for the overview + inventory (defaults to current year server-side). */\n year?: number;\n /** Server-side filters for the full credit ledger. */\n creditFilters?: { status?: string; method?: string; vintageYear?: number };\n /** Which secondary reads to load beyond the always-on overview. */\n include?: SustainabilityInclude;\n}\n\nexport function useHealthyBowlSustainability(options: UseSustainabilityOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const effectiveWorkspaceId = workspaceId || FALLBACK_WORKSPACE_ID;\n const ctx = useMemo<HbContext>(() => ({ workspaceId: effectiveWorkspaceId }), [effectiveWorkspaceId]);\n\n const include = options.include ?? {};\n const { year, creditFilters } = options;\n\n // ── Overview (always loaded; resolves the farm when none is passed) ──\n const overviewQuery = useQuery<\n { getHealthyBowlCarbonOverview: CarbonOverview },\n { context: HbContext; farmId?: string | null; year?: number | null }\n >(GET_OVERVIEW, {\n variables: { context: ctx, farmId: options.farmId ?? null, year: year ?? null },\n fetchPolicy: 'cache-and-network',\n });\n\n const overview = overviewQuery.data?.getHealthyBowlCarbonOverview ?? null;\n const farmId = options.farmId ?? overview?.farmId ?? null;\n\n // ── GHG inventory + activities (emissions detail) ──\n const ghgInventoryQuery = useQuery<\n { getHealthyBowlGhgInventory: GhgInventory | null },\n { context: HbContext; farmId: string; year?: number | null }\n >(GET_GHG_INVENTORY, {\n variables: { context: ctx, farmId: farmId ?? '', year: year ?? null },\n fetchPolicy: 'cache-and-network',\n skip: !include.ghg || !farmId,\n });\n\n const inventory = ghgInventoryQuery.data?.getHealthyBowlGhgInventory ?? overview?.inventory ?? null;\n const inventoryId = inventory?.id ?? null;\n\n const activitiesQuery = useQuery<\n { listHealthyBowlGhgActivities: GhgActivity[] },\n { context: HbContext; inventoryId: string; limit?: number; offset?: number }\n >(LIST_GHG_ACTIVITIES, {\n variables: { context: ctx, inventoryId: inventoryId ?? '', limit: 200, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.ghg || !inventoryId,\n });\n\n // ── Soil carbon (estimates + practices) ──\n const soilEstimatesQuery = useQuery<\n { listHealthyBowlSoilCarbonEstimates: SoilCarbonEstimate[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_SOIL_ESTIMATES, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 100, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.soil || !farmId,\n });\n\n const practicesQuery = useQuery<\n { listHealthyBowlRegenerativePractices: RegenerativePractice[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_REGEN_PRACTICES, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 100, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.soil || !farmId,\n });\n\n // ── Carbon credits (full ledger + overview preview) ──\n const creditsQuery = useQuery<\n { listHealthyBowlCarbonCredits: CarbonCreditList },\n {\n context: HbContext;\n farmId?: string | null;\n status?: string | null;\n method?: string | null;\n vintageYear?: number | null;\n limit?: number;\n offset?: number;\n }\n >(LIST_CARBON_CREDITS, {\n variables: {\n context: ctx,\n farmId: farmId ?? null,\n status: creditFilters?.status ?? null,\n method: creditFilters?.method ?? null,\n vintageYear: creditFilters?.vintageYear ?? null,\n limit: 200,\n offset: 0,\n },\n fetchPolicy: 'cache-and-network',\n skip: !include.credits || !farmId,\n });\n\n const creditsPreviewQuery = useQuery<\n { listHealthyBowlCarbonCredits: CarbonCreditList },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_CARBON_CREDITS, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 5, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.creditsPreview || !farmId,\n });\n\n // ── EUDR statements ──\n const eudrQuery = useQuery<\n { listHealthyBowlEudrStatements: EudrStatement[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_EUDR_STATEMENTS, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 100, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.eudr || !farmId,\n });\n\n // ── MRV report history ──\n const mrvReportsQuery = useQuery<\n { listHealthyBowlMrvReports: MrvReport[] },\n { context: HbContext; farmId?: string | null; limit?: number; offset?: number }\n >(LIST_MRV_REPORTS, {\n variables: { context: ctx, farmId: farmId ?? null, limit: 50, offset: 0 },\n fetchPolicy: 'cache-and-network',\n skip: !include.mrvReports || !farmId,\n });\n\n // ── Farm fields for pickers ──\n const fieldsQuery = useQuery<{ getHealthyBowlCropsData: { fields: SustainabilityField[] } }, { context: HbContext }>(\n GET_FIELDS,\n { variables: { context: ctx }, fetchPolicy: 'cache-and-network', skip: !include.fields }\n );\n\n const refetchOverview = overviewQuery.refetch;\n const refetchInventory = ghgInventoryQuery.refetch;\n const refetchActivities = activitiesQuery.refetch;\n const refetchSoilEstimates = soilEstimatesQuery.refetch;\n const refetchPractices = practicesQuery.refetch;\n const refetchCredits = creditsQuery.refetch;\n const refetchCreditsPreview = creditsPreviewQuery.refetch;\n const refetchEudr = eudrQuery.refetch;\n const refetchMrvReports = mrvReportsQuery.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 // Generic + typed mutation handles.\n const [recomputeMutation] = useMutation<\n { recomputeHealthyBowlGhgInventory: GhgInventory },\n { input: Record<string, unknown> }\n >(RECOMPUTE_INVENTORY);\n const [lockMutation] = useMutation(LOCK_INVENTORY);\n const [verifyMutation] = useMutation(VERIFY_INVENTORY);\n const [upsertActivityMutation] = useMutation(UPSERT_ACTIVITY);\n const [deleteActivityMutation] = useMutation(DELETE_ACTIVITY);\n const [createPracticeMutation] = useMutation(CREATE_PRACTICE);\n const [upsertSoilEstimateMutation] = useMutation(UPSERT_SOIL_ESTIMATE);\n const [createCreditMutation] = useMutation<\n { createHealthyBowlCarbonCredit: { id: string; creditCode: string; status: CreditStatus; quantityTCo2e: number } },\n { input: Record<string, unknown> }\n >(CREATE_CREDIT);\n const [transitionCreditMutation] = useMutation(TRANSITION_CREDIT);\n const [deleteCreditMutation] = useMutation(DELETE_CREDIT);\n const [upsertEudrMutation] = useMutation(UPSERT_EUDR);\n const [exportEudrMutation] = useMutation<\n { exportHealthyBowlEudrStatement: EudrExport },\n { context: HbContext; id: string }\n >(EXPORT_EUDR);\n const [deleteEudrMutation] = useMutation(DELETE_EUDR);\n const [generateMrvMutation] = useMutation<\n { generateHealthyBowlMrvReport: MrvReport },\n { input: Record<string, unknown> }\n >(GENERATE_MRV);\n\n /**\n * Fire a mutation, surface its error, then reconcile the reads it invalidates.\n * Returns `unknown` because these callers ignore the payload; the mutations\n * whose payload IS read (recompute, createCredit, exportEudr, generateMrv) are\n * 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 const inventoryReaders = useMemo(\n () => [refetchOverview, refetchInventory, refetchActivities],\n [refetchOverview, refetchInventory, refetchActivities]\n );\n\n return {\n // reads\n overview,\n inventory,\n activities: activitiesQuery.data?.listHealthyBowlGhgActivities ?? [],\n soilEstimates: soilEstimatesQuery.data?.listHealthyBowlSoilCarbonEstimates ?? [],\n practices: practicesQuery.data?.listHealthyBowlRegenerativePractices ?? [],\n credits: creditsQuery.data?.listHealthyBowlCarbonCredits ?? null,\n creditsPreview: creditsPreviewQuery.data?.listHealthyBowlCarbonCredits ?? null,\n eudrStatements: eudrQuery.data?.listHealthyBowlEudrStatements ?? [],\n mrvReports: mrvReportsQuery.data?.listHealthyBowlMrvReports ?? [],\n fields: fieldsQuery.data?.getHealthyBowlCropsData?.fields ?? [],\n farmId,\n\n loading: {\n overview: overviewQuery.loading,\n inventory: ghgInventoryQuery.loading,\n activities: activitiesQuery.loading,\n soilEstimates: soilEstimatesQuery.loading,\n practices: practicesQuery.loading,\n credits: creditsQuery.loading,\n creditsPreview: creditsPreviewQuery.loading,\n eudr: eudrQuery.loading,\n mrvReports: mrvReportsQuery.loading,\n fields: fieldsQuery.loading,\n },\n errors: {\n overview: overviewQuery.error,\n inventory: ghgInventoryQuery.error,\n activities: activitiesQuery.error,\n soilEstimates: soilEstimatesQuery.error,\n practices: practicesQuery.error,\n credits: creditsQuery.error,\n creditsPreview: creditsPreviewQuery.error,\n eudr: eudrQuery.error,\n mrvReports: mrvReportsQuery.error,\n fields: fieldsQuery.error,\n },\n\n refetchAll: useCallback(\n () =>\n reconcile(\n refetchOverview,\n refetchInventory,\n refetchActivities,\n refetchSoilEstimates,\n refetchPractices,\n refetchCredits,\n refetchCreditsPreview,\n refetchEudr,\n refetchMrvReports\n ),\n [\n reconcile,\n refetchOverview,\n refetchInventory,\n refetchActivities,\n refetchSoilEstimates,\n refetchPractices,\n refetchCredits,\n refetchCreditsPreview,\n refetchEudr,\n refetchMrvReports,\n ]\n ),\n\n // ── GHG inventory ──\n recomputeInventory: useCallback(\n async (targetFarmId: string, targetYear?: number): Promise<GhgInventory | null> => {\n const res = await recomputeMutation({\n variables: { input: { context: ctx, farmId: targetFarmId, ...(targetYear ? { year: targetYear } : {}) } },\n });\n if (res.error) throw res.error;\n await reconcile(...inventoryReaders, refetchCredits, refetchCreditsPreview);\n return res.data?.recomputeHealthyBowlGhgInventory ?? null;\n },\n [recomputeMutation, ctx, reconcile, inventoryReaders, refetchCredits, refetchCreditsPreview]\n ),\n lockInventory: useCallback(\n (id: string) => run(lockMutation, { context: ctx, id }, inventoryReaders),\n [run, lockMutation, ctx, inventoryReaders]\n ),\n verifyInventory: useCallback(\n (id: string) => run(verifyMutation, { context: ctx, id }, inventoryReaders),\n [run, verifyMutation, ctx, inventoryReaders]\n ),\n upsertActivity: useCallback(\n (input: Record<string, unknown>) => run(upsertActivityMutation, { input: withCtx(input) }, inventoryReaders),\n [run, upsertActivityMutation, withCtx, inventoryReaders]\n ),\n deleteActivity: useCallback(\n (id: string) => run(deleteActivityMutation, { context: ctx, id }, inventoryReaders),\n [run, deleteActivityMutation, ctx, inventoryReaders]\n ),\n\n // ── Soil carbon ──\n createPractice: useCallback(\n (input: Record<string, unknown>) =>\n run(createPracticeMutation, { input: withCtx(input) }, [refetchPractices, refetchOverview]),\n [run, createPracticeMutation, withCtx, refetchPractices, refetchOverview]\n ),\n upsertSoilEstimate: useCallback(\n (input: Record<string, unknown>) =>\n run(upsertSoilEstimateMutation, { input: withCtx(input) }, [refetchSoilEstimates, refetchOverview]),\n [run, upsertSoilEstimateMutation, withCtx, refetchSoilEstimates, refetchOverview]\n ),\n\n // ── Carbon credits ──\n createCredit: useCallback(\n async (\n input: Record<string, unknown>\n ): Promise<{ id: string; creditCode: string; status: CreditStatus; quantityTCo2e: number } | null> => {\n const res = await createCreditMutation({ variables: { input: withCtx(input) } });\n if (res.error) throw res.error;\n await reconcile(refetchCredits, refetchCreditsPreview, refetchOverview);\n return res.data?.createHealthyBowlCarbonCredit ?? null;\n },\n [createCreditMutation, withCtx, reconcile, refetchCredits, refetchCreditsPreview, refetchOverview]\n ),\n transitionCredit: useCallback(\n (input: Record<string, unknown>) =>\n run(transitionCreditMutation, { input: withCtx(input) }, [\n refetchCredits,\n refetchCreditsPreview,\n refetchOverview,\n ]),\n [run, transitionCreditMutation, withCtx, refetchCredits, refetchCreditsPreview, refetchOverview]\n ),\n deleteCredit: useCallback(\n (id: string) =>\n run(deleteCreditMutation, { context: ctx, id }, [refetchCredits, refetchCreditsPreview, refetchOverview]),\n [run, deleteCreditMutation, ctx, refetchCredits, refetchCreditsPreview, refetchOverview]\n ),\n\n // ── EUDR ──\n upsertEudrStatement: useCallback(\n (input: Record<string, unknown>) =>\n run(upsertEudrMutation, { input: withCtx(input) }, [refetchEudr, refetchOverview]),\n [run, upsertEudrMutation, withCtx, refetchEudr, refetchOverview]\n ),\n deleteEudrStatement: useCallback(\n (id: string) => run(deleteEudrMutation, { context: ctx, id }, [refetchEudr, refetchOverview]),\n [run, deleteEudrMutation, ctx, refetchEudr, refetchOverview]\n ),\n /** Render + archive the EUDR PDF, then trigger a browser download of the bytes. */\n exportEudrStatement: useCallback(\n async (id: string): Promise<EudrExport | null> => {\n const res = await exportEudrMutation({ variables: { context: ctx, id } });\n if (res.error) throw res.error;\n const payload = res.data?.exportHealthyBowlEudrStatement ?? null;\n if (payload?.pdfBase64) {\n downloadBase64(payload.pdfBase64, payload.fileName || `${payload.statementCode}.pdf`, 'application/pdf');\n }\n await reconcile(refetchEudr, refetchOverview);\n return payload;\n },\n [exportEudrMutation, ctx, reconcile, refetchEudr, refetchOverview]\n ),\n\n // ── MRV report ──\n /** Assemble + archive the MRV report, then trigger a browser download (PDF or CSV). */\n generateMrvReport: useCallback(\n async (targetFarmId: string, format: MrvFormat = 'PDF', targetYear?: number): Promise<MrvReport | null> => {\n const res = await generateMrvMutation({\n variables: {\n input: { context: ctx, farmId: targetFarmId, format, ...(targetYear ? { year: targetYear } : {}) },\n },\n });\n if (res.error) throw res.error;\n const report = res.data?.generateHealthyBowlMrvReport ?? null;\n if (report) {\n if (report.format === 'CSV' && report.csv) {\n downloadText(report.csv, `${report.reportCode}.csv`, 'text/csv');\n } else if (report.pdfBase64) {\n downloadBase64(report.pdfBase64, `${report.reportCode}.pdf`, 'application/pdf');\n }\n }\n await reconcile(refetchMrvReports);\n return report;\n },\n [generateMrvMutation, ctx, reconcile, refetchMrvReports]\n ),\n\n /** One-off documents for detail reads (credit / EUDR statement). */\n documents: { GET_CARBON_CREDIT, GET_EUDR_STATEMENT },\n context: ctx,\n };\n}\n\nexport { GET_CARBON_CREDIT, GET_EUDR_STATEMENT };\n\nexport interface CarbonCreditData {\n getHealthyBowlCarbonCredit: CarbonCredit;\n}\nexport interface EudrStatementData {\n getHealthyBowlEudrStatement: EudrStatement;\n}\n"],"mappings":";;;;;AAqBA,IAAM,KAAwB,wCA4OxB,IAAmB,oOAMnB,IAAkB,qIAKlB,IAAkB,0FAIlB,IAAuB,qJAKvB,IAAgB,yNAMhB,IAAc,8SAQd,IAAkB,2EAMlB,KAAe,CAAG;;;;oBAIJ,EAAiB;;;;;2DAKsB,EAAY;;;GAKjE,KAAoB,CAAG;;oFAEuD,EAAiB;;GAI/F,KAAsB,CAAG;;;QAGvB,EAAgB;;;GAKlB,KAAuB,CAAG;;;QAGxB,EAAgB;;;GAKlB,KAAsB,CAAG;;;QAGvB,EAAqB;;;GAKvB,IAAsB,CAAG;;;;;;;;;;;;;;;;;;;gBAmBf,EAAc;;;;GAMxB,KAAoB,CAAG;;+DAEkC,EAAc;;GAIvE,KAAuB,CAAG;;;QAGxB,EAAY;;;GAKd,KAAqB,CAAG;;gEAEkC,EAAY;;GAItE,KAAmB,CAAG;;;QAGpB,EAAgB;;;GAMlB,KAAa,CAAG;;;;;;;;;;;GAehB,KAAsB,CAAG;;wDAEyB,EAAiB;;GAGnE,KAAiB,CAAG;;;;;;;;GASpB,KAAmB,CAAG;;;;;;;;GAStB,KAAkB,CAAG;;;;;;;;;GAUrB,KAAkB,CAAG;;;;GAKrB,KAAkB,CAAG;;;;;;;GAQrB,KAAuB,CAAG;;;;;;;GAQ1B,KAAgB,CAAG;;;;;;;;;GAUnB,KAAoB,CAAG;;;;;;;GAQvB,KAAgB,CAAG;;;;GAKnB,KAAc,CAAG;;;;;;;;;GAUjB,KAAc,CAAG;;;;;;;;;GAUjB,KAAc,CAAG;;;;GAKjB,KAAe,CAAG;;;;;;;;;;;;;;;;AAmBxB,SAAS,EAAgB,GAAY,GAAwB;AAC3D,KAAI,OAAO,WAAa,IAAa;CACrC,IAAM,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ACpC,GAAa,EAAO,KAAK,GAAG,EAAO,WAAW,OAAO,WAAW,GACvD,EAAO,aAChB,EAAe,EAAO,WAAW,GAAG,EAAO,WAAW,OAAO,kBAAkB,GAGnF,MAAM,EAAU,EAAkB,EAC3B;KAET;GAAC;GAAqB;GAAK;GAAW;GAAkB,CACzD;EAGD,WAAW;GAAE;GAAmB;GAAoB;EACpD,SAAS;EACV"}
@@ -0,0 +1,53 @@
1
+ import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
2
+ import { useCallback as t } from "react";
3
+ import { gql as n } from "@apollo/client";
4
+ import { useMutation as r, useQuery as i } from "@apollo/client/react";
5
+ //#region src/healthybowl/hooks/useSupplierMessages.ts
6
+ var a = "\n id\n supplierId\n conversationId\n body\n authorId\n authorType\n createdAt\n", o = n`
7
+ query HealthyBowlSupplierMessages($supplierId: ID!, $context: ContextInput!) {
8
+ healthyBowlSupplierMessages(supplierId: $supplierId, context: $context) {
9
+ ${a}
10
+ }
11
+ }
12
+ `, s = n`
13
+ mutation SendHealthyBowlSupplierMessage($input: SendHealthyBowlSupplierMessageInput!) {
14
+ sendHealthyBowlSupplierMessage(input: $input) {
15
+ ${a}
16
+ }
17
+ }
18
+ `;
19
+ function c(n) {
20
+ let { workspaceId: a } = e(), c = { workspaceId: a }, { data: l, loading: u, error: d, refetch: f } = i(o, {
21
+ variables: {
22
+ supplierId: n ?? "",
23
+ context: c
24
+ },
25
+ skip: !a || !n,
26
+ fetchPolicy: "cache-and-network",
27
+ notifyOnNetworkStatusChange: !0
28
+ }), [p, { loading: m }] = r(s), h = t(async (e) => {
29
+ let t = e.trim();
30
+ !n || !t || (await p({ variables: { input: {
31
+ supplierId: n,
32
+ body: t,
33
+ context: c
34
+ } } }), await f());
35
+ }, [
36
+ p,
37
+ f,
38
+ n,
39
+ a
40
+ ]);
41
+ return {
42
+ messages: l?.healthyBowlSupplierMessages ?? [],
43
+ loading: u,
44
+ sending: m,
45
+ error: d,
46
+ refetch: f,
47
+ sendMessage: h
48
+ };
49
+ }
50
+ //#endregion
51
+ export { c as useSupplierMessages };
52
+
53
+ //# sourceMappingURL=useSupplierMessages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSupplierMessages.js","names":[],"sources":["../../../src/healthybowl/hooks/useSupplierMessages.ts"],"sourcesContent":["/**\n * Supplier conversation-thread hook (roadmap #5, \"Message supplier\").\n *\n * Backs the real, persisted supplier message thread with wspace-conversations-svc\n * (via the HB backend). Mirrors the raw-gql pattern used by `useSuppliers` /\n * `useNursery`: the offline codegen doesn't type these ops, so they are hand-written\n * `gql` documents run directly against the live gateway, each carrying the workspace\n * `context`.\n * @module healthybowl\n */\nimport { useCallback } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n/** A single message in a supplier's conversation thread. */\nexport interface SupplierMessage {\n id: string;\n supplierId: string;\n conversationId: string;\n body: string;\n authorId: string;\n authorType?: string | null;\n /** ISO-8601 timestamp. */\n createdAt: string;\n}\n\nconst MESSAGE_FIELDS = `\n id\n supplierId\n conversationId\n body\n authorId\n authorType\n createdAt\n`;\n\nconst SUPPLIER_MESSAGES_QUERY = gql`\n query HealthyBowlSupplierMessages($supplierId: ID!, $context: ContextInput!) {\n healthyBowlSupplierMessages(supplierId: $supplierId, context: $context) {\n ${MESSAGE_FIELDS}\n }\n }\n`;\n\nconst SEND_SUPPLIER_MESSAGE = gql`\n mutation SendHealthyBowlSupplierMessage($input: SendHealthyBowlSupplierMessageInput!) {\n sendHealthyBowlSupplierMessage(input: $input) {\n ${MESSAGE_FIELDS}\n }\n }\n`;\n\ninterface SupplierMessagesQueryData {\n healthyBowlSupplierMessages: SupplierMessage[];\n}\n\n/**\n * Loads (and lets you send to) the conversation thread for a single supplier. Pass\n * `null` for `supplierId` to keep the hook dormant (e.g. while the thread modal is\n * closed) — the query is skipped and `sendMessage` is a no-op. Sending refetches the\n * thread so the new message appears without hand-managing the cache.\n */\nexport function useSupplierMessages(supplierId: string | null) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n\n const { data, loading, error, refetch } = useQuery<SupplierMessagesQueryData>(SUPPLIER_MESSAGES_QUERY, {\n variables: { supplierId: supplierId ?? '', context },\n skip: !workspaceId || !supplierId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n const [sendMutation, { loading: sending }] = useMutation(SEND_SUPPLIER_MESSAGE);\n\n const sendMessage = useCallback(\n async (body: string) => {\n const trimmed = body.trim();\n if (!supplierId || !trimmed) return;\n await sendMutation({ variables: { input: { supplierId, body: trimmed, context } } });\n await refetch();\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [sendMutation, refetch, supplierId, workspaceId]\n );\n\n return {\n messages: data?.healthyBowlSupplierMessages ?? [],\n loading,\n sending,\n error,\n refetch,\n sendMessage,\n };\n}\n"],"mappings":";;;;;AA2BA,IAAM,IAAiB,2FAUjB,IAA0B,CAAG;;;QAG3B,EAAe;;;GAKjB,IAAwB,CAAG;;;QAGzB,EAAe;;;;AAevB,SAAgB,EAAoB,GAA2B;CAC7D,IAAM,EAAE,mBAAgB,GAAgB,EAClC,IAAU,EAAE,gBAAa,EAEzB,EAAE,SAAM,YAAS,UAAO,eAAY,EAAoC,GAAyB;EACrG,WAAW;GAAE,YAAY,KAAc;GAAI;GAAS;EACpD,MAAM,CAAC,KAAe,CAAC;EACvB,aAAa;EACb,6BAA6B;EAC9B,CAAC,EAEI,CAAC,GAAc,EAAE,SAAS,OAAa,EAAY,EAAsB,EAEzE,IAAc,EAClB,OAAO,MAAiB;EACtB,IAAM,IAAU,EAAK,MAAM;AACvB,GAAC,KAAc,CAAC,MACpB,MAAM,EAAa,EAAE,WAAW,EAAE,OAAO;GAAE;GAAY,MAAM;GAAS;GAAS,EAAE,EAAE,CAAC,EACpF,MAAM,GAAS;IAGjB;EAAC;EAAc;EAAS;EAAY;EAAY,CACjD;AAED,QAAO;EACL,UAAU,GAAM,+BAA+B,EAAE;EACjD;EACA;EACA;EACA;EACA;EACD"}