@burdenoff/microfe-healthybowl 2026.713.17 → 2026.714.2

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,87 @@
1
+ import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
2
+ import { useCallback as t, useMemo as n } from "react";
3
+ import { gql as r } from "@apollo/client";
4
+ import { useMutation as i, useQuery as a } from "@apollo/client/react";
5
+ //#region src/healthybowl/hooks/useOrderPayments.ts
6
+ var o = "https://checkout.razorpay.com/v1/checkout.js", s = null;
7
+ function c() {
8
+ return typeof window > "u" || typeof document > "u" ? Promise.reject(/* @__PURE__ */ Error("Razorpay checkout is only available in a browser")) : window.Razorpay ? Promise.resolve(window.Razorpay) : s || (s = new Promise((e, t) => {
9
+ document.querySelectorAll(`script[src="${o}"]`).forEach((e) => e.remove());
10
+ let n = document.createElement("script"), r = (e) => {
11
+ s = null, n.remove(), t(Error(e));
12
+ };
13
+ n.addEventListener("load", () => {
14
+ if (window.Razorpay) {
15
+ e(window.Razorpay);
16
+ return;
17
+ }
18
+ r("Razorpay checkout loaded but window.Razorpay is missing");
19
+ }), n.addEventListener("error", () => r("Could not load the Razorpay checkout script")), n.src = o, n.async = !0, document.body.appendChild(n);
20
+ }), s);
21
+ }
22
+ var l = "\n id\n orderNumber\n status\n paymentStatus\n total\n paymentProvider\n paymentReference\n paidAmount\n paidAt\n", u = r`
23
+ query HealthyBowlOrderPayments($context: ContextInput!) {
24
+ getHealthyBowlMarketplaceData(context: $context) {
25
+ orders {
26
+ ${l}
27
+ }
28
+ }
29
+ }
30
+ `, d = r`
31
+ mutation CheckoutHealthyBowlOrder($orderId: ID!, $context: ContextInput!) {
32
+ checkoutHealthyBowlOrder(orderId: $orderId, context: $context) {
33
+ orderId
34
+ billingOrderId
35
+ provider
36
+ providerOrderId
37
+ razorpayKeyId
38
+ clientSecret
39
+ subtotal
40
+ taxAmount
41
+ total
42
+ currency
43
+ }
44
+ }
45
+ `, f = r`
46
+ mutation SyncHealthyBowlOrderPayment($orderId: ID!, $context: ContextInput!) {
47
+ syncHealthyBowlOrderPayment(orderId: $orderId, context: $context) {
48
+ ${l}
49
+ }
50
+ }
51
+ `;
52
+ function p() {
53
+ let { workspaceId: r } = e(), o = { workspaceId: r }, { data: s, refetch: c } = a(u, {
54
+ variables: { context: o },
55
+ skip: !r,
56
+ fetchPolicy: "cache-and-network",
57
+ errorPolicy: "all",
58
+ notifyOnNetworkStatusChange: !0
59
+ }), [l] = i(d), [p] = i(f);
60
+ return {
61
+ payments: n(() => {
62
+ let e = s?.getHealthyBowlMarketplaceData?.orders ?? [];
63
+ return Object.fromEntries(e.map((e) => [e.id, e]));
64
+ }, [s]),
65
+ refetchPayments: c,
66
+ checkoutOrder: t(async (e) => {
67
+ let t = (await l({ variables: {
68
+ orderId: e,
69
+ context: o
70
+ } })).data?.checkoutHealthyBowlOrder;
71
+ if (!t) throw Error("Checkout did not return a payment session");
72
+ return t;
73
+ }, [l, r]),
74
+ syncOrderPayment: t(async (e) => {
75
+ let t = (await p({ variables: {
76
+ orderId: e,
77
+ context: o
78
+ } })).data?.syncHealthyBowlOrderPayment;
79
+ if (!t) throw Error("Payment sync did not return the order");
80
+ return t;
81
+ }, [p, r])
82
+ };
83
+ }
84
+ //#endregion
85
+ export { c as loadRazorpayCheckout, p as useOrderPayments };
86
+
87
+ //# sourceMappingURL=useOrderPayments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useOrderPayments.js","names":[],"sources":["../../../src/healthybowl/hooks/useOrderPayments.ts"],"sourcesContent":["/**\n * Real marketplace payments (roadmap #6, acceptance D-2).\n *\n * A fixed-price \"Buy Now\" purchase and a won auction both create an Order with `paymentStatus:\n * pending`. Paying it goes through the platform billing rail, never through this client:\n *\n * 1. `checkoutHealthyBowlOrder` → the backend creates the BillingOrder in global-billing and\n * initiates the payment, handing back what the provider's checkout widget needs.\n * 2. the buyer pays in the provider's widget (Razorpay), loaded lazily on first use.\n * 3. `syncHealthyBowlOrderPayment` → the backend RE-READS the authoritative Payment from billing\n * and only then flips the order to PAID with the gateway's real payment reference.\n *\n * The client never marks anything paid — it only asks the backend to settle, and the backend only\n * settles what billing reports as SUCCEEDED. Calling sync on an abandoned checkout is safe: it\n * simply confirms the order is still pending.\n *\n * These operations post-date the checked-in SDL, so — mirroring `useAuctions` / `useSharedMarket` —\n * they are hand-written `gql` documents executed directly against the live gateway.\n * @module healthybowl\n */\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n// ── Razorpay checkout widget ──────────────────────────────────────────────────\n/** The subset of Razorpay's checkout options this flow uses. */\nexport interface RazorpayCheckoutOptions {\n /** Razorpay publishable key id (from the backend — never hard-coded here). */\n key: string;\n /** The provider's own order id (`order_xxx`), created by global-billing. */\n order_id: string;\n /** Amount in the smallest currency unit (paise for INR). */\n amount: number;\n currency: string;\n name: string;\n description?: string;\n /** Called by Razorpay when the payment succeeds. */\n handler?: (response: RazorpayPaymentResponse) => void;\n modal?: { ondismiss?: () => void };\n theme?: { color?: string };\n}\n\n/** What Razorpay hands back on success. HB ignores the values (billing is the authority) — it only\n * uses the callback as a signal to ask the backend to settle. */\nexport interface RazorpayPaymentResponse {\n razorpay_payment_id?: string;\n razorpay_order_id?: string;\n razorpay_signature?: string;\n}\n\nexport interface RazorpayInstance {\n open: () => void;\n close?: () => void;\n}\n\nexport type RazorpayConstructor = new (options: RazorpayCheckoutOptions) => RazorpayInstance;\n\ndeclare global {\n interface Window {\n Razorpay?: RazorpayConstructor;\n }\n}\n\nconst RAZORPAY_CHECKOUT_SRC = 'https://checkout.razorpay.com/v1/checkout.js';\n\n/** Cached so the script is injected at most once per page, however many orders get paid. */\nlet razorpayScriptPromise: Promise<RazorpayConstructor> | null = null;\n\n/**\n * Lazily inject Razorpay's checkout script and resolve with the global constructor. It is loaded on\n * first use rather than from index.html so that the vast majority of sessions — which never pay for\n * anything — don't fetch a third-party script at all.\n */\nexport function loadRazorpayCheckout(): Promise<RazorpayConstructor> {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return Promise.reject(new Error('Razorpay checkout is only available in a browser'));\n }\n if (window.Razorpay) return Promise.resolve(window.Razorpay);\n if (razorpayScriptPromise) return razorpayScriptPromise;\n\n razorpayScriptPromise = new Promise<RazorpayConstructor>((resolve, reject) => {\n // Never adopt a <script> we didn't just inject. An element already in the DOM may have fired\n // its load/error before we could listen, and listeners attached afterwards would never run —\n // leaving this promise (and the cached one every later call returns) pending forever, with the\n // Pay Now button stuck disabled. Dropping any pre-existing tag and injecting a fresh one makes\n // load/error guaranteed to fire. We only get here when window.Razorpay is absent, so nothing\n // usable is being thrown away.\n document.querySelectorAll<HTMLScriptElement>(`script[src=\"${RAZORPAY_CHECKOUT_SRC}\"]`).forEach((el) => el.remove());\n\n const script = document.createElement('script');\n\n /**\n * A failed load must leave NO trace: null the cached promise *and* drop the dead <script>, so\n * the next attempt injects a genuinely fresh one rather than replaying a rejected promise or\n * waiting on a spent element.\n */\n const fail = (message: string) => {\n razorpayScriptPromise = null;\n script.remove();\n reject(new Error(message));\n };\n\n script.addEventListener('load', () => {\n if (window.Razorpay) {\n resolve(window.Razorpay);\n return;\n }\n fail('Razorpay checkout loaded but window.Razorpay is missing');\n });\n script.addEventListener('error', () => fail('Could not load the Razorpay checkout script'));\n\n script.src = RAZORPAY_CHECKOUT_SRC;\n script.async = true;\n document.body.appendChild(script);\n });\n\n return razorpayScriptPromise;\n}\n\n// ── Operations ────────────────────────────────────────────────────────────────\n/** Everything the client needs to open the provider's checkout for an order. */\nexport interface OrderCheckout {\n orderId: string;\n billingOrderId: string;\n /** RAZORPAY / STRIPE — billing decides, the client only reacts. */\n provider: string;\n /** Razorpay `order_xxx`; null when billing routed to another provider. */\n providerOrderId?: string | null;\n razorpayKeyId?: string | null;\n /** Stripe's client secret, when billing routes to Stripe (not handled by this UI). */\n clientSecret?: string | null;\n subtotal: number;\n /** Tax computed by billing, not by HB. */\n taxAmount: number;\n total: number;\n currency: string;\n}\n\n/** The payment provenance of an order, as mirrored from the billing rail. */\nexport interface OrderPayment {\n id: string;\n orderNumber?: string;\n status?: string;\n paymentStatus?: string;\n total?: number;\n /** RAZORPAY / STRIPE for a gateway-verified payment; MANUAL for an offline sale marked paid. */\n paymentProvider?: string | null;\n /** The gateway's own payment reference (e.g. Razorpay `pay_xxx`). Null for a MANUAL sale. */\n paymentReference?: string | null;\n paidAmount?: number | null;\n paidAt?: string | null;\n}\n\nconst ORDER_PAYMENT_FIELDS = `\n id\n orderNumber\n status\n paymentStatus\n total\n paymentProvider\n paymentReference\n paidAmount\n paidAt\n`;\n\n/**\n * The payment provenance of every order. Read through the marketplace payload (the only order read\n * this service exposes) but selecting ONLY the payment columns, which the codegen'd\n * `GetHealthyBowlMarketplaceData` document cannot carry — the checked-in SDL predates them.\n */\nconst ORDER_PAYMENTS_QUERY = gql`\n query HealthyBowlOrderPayments($context: ContextInput!) {\n getHealthyBowlMarketplaceData(context: $context) {\n orders {\n ${ORDER_PAYMENT_FIELDS}\n }\n }\n }\n`;\n\nconst CHECKOUT_ORDER = gql`\n mutation CheckoutHealthyBowlOrder($orderId: ID!, $context: ContextInput!) {\n checkoutHealthyBowlOrder(orderId: $orderId, context: $context) {\n orderId\n billingOrderId\n provider\n providerOrderId\n razorpayKeyId\n clientSecret\n subtotal\n taxAmount\n total\n currency\n }\n }\n`;\n\nconst SYNC_ORDER_PAYMENT = gql`\n mutation SyncHealthyBowlOrderPayment($orderId: ID!, $context: ContextInput!) {\n syncHealthyBowlOrderPayment(orderId: $orderId, context: $context) {\n ${ORDER_PAYMENT_FIELDS}\n }\n }\n`;\n\ninterface OrderPaymentsQueryData {\n getHealthyBowlMarketplaceData: { orders: OrderPayment[] } | null;\n}\ninterface CheckoutOrderData {\n checkoutHealthyBowlOrder: OrderCheckout;\n}\ninterface SyncOrderPaymentData {\n syncHealthyBowlOrderPayment: OrderPayment;\n}\n\n/**\n * Exposes the payment provenance of each order plus the two settlement calls.\n *\n * The provenance read is best-effort (`errorPolicy: 'all'`): the orders list itself comes from\n * `useHealthyBowlData`, so if this read fails the page still renders — it just can't show where the\n * money came from.\n */\nexport function useOrderPayments() {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n\n const { data, refetch } = useQuery<OrderPaymentsQueryData>(ORDER_PAYMENTS_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n errorPolicy: 'all',\n notifyOnNetworkStatusChange: true,\n });\n\n const [checkoutMutation] = useMutation<CheckoutOrderData>(CHECKOUT_ORDER);\n const [syncMutation] = useMutation<SyncOrderPaymentData>(SYNC_ORDER_PAYMENT);\n\n /** Payment provenance keyed by order id. */\n const payments = useMemo<Record<string, OrderPayment>>(() => {\n const orders = data?.getHealthyBowlMarketplaceData?.orders ?? [];\n return Object.fromEntries(orders.map((o) => [o.id, o]));\n }, [data]);\n\n /** Start a real payment. Idempotent server-side — a re-checkout reuses the existing BillingOrder. */\n const checkoutOrder = useCallback(\n async (orderId: string): Promise<OrderCheckout> => {\n const res = await checkoutMutation({ variables: { orderId, context } });\n const checkout = res.data?.checkoutHealthyBowlOrder;\n if (!checkout) throw new Error('Checkout did not return a payment session');\n return checkout;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [checkoutMutation, workspaceId]\n );\n\n /**\n * Ask the backend to settle the order against the billing rail. It re-reads the authoritative\n * Payment and marks the order paid ONLY if billing reports it SUCCEEDED — so this is also the\n * right call to make when the buyer closes the widget without paying (the order stays pending).\n */\n const syncOrderPayment = useCallback(\n async (orderId: string): Promise<OrderPayment> => {\n const res = await syncMutation({ variables: { orderId, context } });\n const order = res.data?.syncHealthyBowlOrderPayment;\n if (!order) throw new Error('Payment sync did not return the order');\n return order;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [syncMutation, workspaceId]\n );\n\n return { payments, refetchPayments: refetch, checkoutOrder, syncOrderPayment };\n}\n"],"mappings":";;;;;AAgEA,IAAM,IAAwB,gDAG1B,IAA6D;AAOjE,SAAgB,IAAqD;AA2CnE,QA1CI,OAAO,SAAW,OAAe,OAAO,WAAa,MAChD,QAAQ,OAAO,gBAAI,MAAM,mDAAmD,CAAC,GAElF,OAAO,WAAiB,QAAQ,QAAQ,OAAO,SAAS,GACxD,MAEJ,IAAwB,IAAI,SAA8B,GAAS,MAAW;AAO5E,WAAS,iBAAoC,eAAe,EAAsB,IAAI,CAAC,SAAS,MAAO,EAAG,QAAQ,CAAC;EAEnH,IAAM,IAAS,SAAS,cAAc,SAAS,EAOzC,KAAQ,MAAoB;AAGhC,GAFA,IAAwB,MACxB,EAAO,QAAQ,EACf,EAAW,MAAM,EAAQ,CAAC;;AAc5B,EAXA,EAAO,iBAAiB,cAAc;AACpC,OAAI,OAAO,UAAU;AACnB,MAAQ,OAAO,SAAS;AACxB;;AAEF,KAAK,0DAA0D;IAC/D,EACF,EAAO,iBAAiB,eAAe,EAAK,8CAA8C,CAAC,EAE3F,EAAO,MAAM,GACb,EAAO,QAAQ,IACf,SAAS,KAAK,YAAY,EAAO;GACjC,EAEK;;AAqCT,IAAM,IAAuB,8HAiBvB,IAAuB,CAAG;;;;UAItB,EAAqB;;;;GAMzB,IAAiB,CAAG;;;;;;;;;;;;;;;GAiBpB,IAAqB,CAAG;;;QAGtB,EAAqB;;;;AAsB7B,SAAgB,IAAmB;CACjC,IAAM,EAAE,mBAAgB,GAAgB,EAClC,IAAU,EAAE,gBAAa,EAEzB,EAAE,SAAM,eAAY,EAAiC,GAAsB;EAC/E,WAAW,EAAE,YAAS;EACtB,MAAM,CAAC;EACP,aAAa;EACb,aAAa;EACb,6BAA6B;EAC9B,CAAC,EAEI,CAAC,KAAoB,EAA+B,EAAe,EACnE,CAAC,KAAgB,EAAkC,EAAmB;AAoC5E,QAAO;EAAE,UAjCQ,QAA4C;GAC3D,IAAM,IAAS,GAAM,+BAA+B,UAAU,EAAE;AAChE,UAAO,OAAO,YAAY,EAAO,KAAK,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;KACtD,CAAC,EAAK,CAAC;EA8BS,iBAAiB;EAAS,eA3BvB,EACpB,OAAO,MAA4C;GAEjD,IAAM,KADM,MAAM,EAAiB,EAAE,WAAW;IAAE;IAAS;IAAS,EAAE,CAAC,EAClD,MAAM;AAC3B,OAAI,CAAC,EAAU,OAAU,MAAM,4CAA4C;AAC3E,UAAO;KAGT,CAAC,GAAkB,EAAY,CAChC;EAkB2D,kBAXnC,EACvB,OAAO,MAA2C;GAEhD,IAAM,KADM,MAAM,EAAa,EAAE,WAAW;IAAE;IAAS;IAAS,EAAE,CAAC,EACjD,MAAM;AACxB,OAAI,CAAC,EAAO,OAAU,MAAM,wCAAwC;AACpE,UAAO;KAGT,CAAC,GAAc,EAAY,CAC5B;EAE6E"}
@@ -0,0 +1,54 @@
1
+ import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
2
+ import { useCallback as t, useMemo as n } from "react";
3
+ import { gql as r } from "@apollo/client";
4
+ import { useMutation as i, useQuery as a } from "@apollo/client/react";
5
+ //#region src/healthybowl/hooks/useSharedMarket.ts
6
+ var o = r`
7
+ query HealthyBowlSharedMarketListings($context: ContextInput!, $category: String, $search: String, $limit: Int) {
8
+ healthyBowlSharedMarketListings(context: $context, category: $category, search: $search, limit: $limit) {
9
+ ${"\n id\n name\n category\n price\n unit\n stock\n organicCertified\n image\n description\n seller\n sellerRating\n location\n rating\n"}
10
+ }
11
+ }
12
+ `, s = r`
13
+ mutation SetHealthyBowlListingShared($id: ID!, $shared: Boolean!, $context: ContextInput!) {
14
+ setHealthyBowlListingShared(id: $id, shared: $shared, context: $context) {
15
+ id
16
+ name
17
+ }
18
+ }
19
+ `;
20
+ function c(t = {}) {
21
+ let { workspaceId: r } = e(), { data: i, loading: s, error: c, refetch: l } = a(o, {
22
+ variables: {
23
+ context: { workspaceId: r },
24
+ category: t.category && t.category !== "All" ? t.category : null,
25
+ search: t.search?.trim() ? t.search.trim() : null,
26
+ limit: t.limit ?? null
27
+ },
28
+ skip: !r,
29
+ fetchPolicy: "cache-and-network",
30
+ notifyOnNetworkStatusChange: !0
31
+ }), u = n(() => i?.healthyBowlSharedMarketListings ?? [], [i]);
32
+ return {
33
+ listings: u,
34
+ sharedListingIds: n(() => new Set(u.map((e) => e.id)), [u]),
35
+ loading: s,
36
+ error: c,
37
+ refetch: l
38
+ };
39
+ }
40
+ function l() {
41
+ let { workspaceId: n } = e(), r = { workspaceId: n }, [a, { loading: o }] = i(s);
42
+ return {
43
+ setListingShared: t(async (e, t) => (await a({ variables: {
44
+ id: e,
45
+ shared: t,
46
+ context: r
47
+ } })).data?.setHealthyBowlListingShared, [a, n]),
48
+ saving: o
49
+ };
50
+ }
51
+ //#endregion
52
+ export { l as useSetListingShared, c as useSharedMarketListings };
53
+
54
+ //# sourceMappingURL=useSharedMarket.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSharedMarket.js","names":[],"sources":["../../../src/healthybowl/hooks/useSharedMarket.ts"],"sourcesContent":["/**\n * Shared cross-farm marketplace (roadmap #6, acceptance D-1).\n *\n * `MarketplaceProduct` is workspace-scoped, so a buyer normally only ever sees their own farm's\n * listings. A farm OPTS IN per listing (`setHealthyBowlListingShared`) and the shared read then\n * returns listings from EVERY farm that has opted in — a narrowed projection\n * (`SharedMarketListing`) that carries the selling farm's identity, which is the entire point of a\n * cross-farm view.\n *\n * The offline codegen doesn't type these operations (they post-date the checked-in SDL), so —\n * mirroring the raw-gql pattern used for Auctions (`useAuctions`) and Irrigation (`useIrrigation`)\n * — they are hand-written `gql` documents executed directly against the live gateway. Every op\n * carries the workspace `context`.\n * @module healthybowl\n */\nimport { useCallback, useMemo } from 'react';\nimport { gql } from '@apollo/client';\nimport { useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n/** A listing some farm has published to the shared cross-farm market. */\nexport interface SharedMarketListing {\n id: string;\n name: string;\n category: string;\n price: number;\n unit: string;\n stock: number;\n organicCertified: boolean;\n image?: string | null;\n description: string;\n /** The selling farm — what makes a cross-farm view legible. */\n seller?: string | null;\n sellerRating?: number | null;\n location?: string | null;\n rating: number;\n}\n\n/** Server-side filters for the shared-market read. */\nexport interface SharedMarketFilters {\n /** Exact category match; pass null/undefined (or 'All') for every category. */\n category?: string | null;\n /** Free-text match on name / description / seller. */\n search?: string | null;\n limit?: number | null;\n}\n\nconst SHARED_LISTING_FIELDS = `\n id\n name\n category\n price\n unit\n stock\n organicCertified\n image\n description\n seller\n sellerRating\n location\n rating\n`;\n\nconst SHARED_LISTINGS_QUERY = gql`\n query HealthyBowlSharedMarketListings($context: ContextInput!, $category: String, $search: String, $limit: Int) {\n healthyBowlSharedMarketListings(context: $context, category: $category, search: $search, limit: $limit) {\n ${SHARED_LISTING_FIELDS}\n }\n }\n`;\n\nconst SET_LISTING_SHARED = gql`\n mutation SetHealthyBowlListingShared($id: ID!, $shared: Boolean!, $context: ContextInput!) {\n setHealthyBowlListingShared(id: $id, shared: $shared, context: $context) {\n id\n name\n }\n }\n`;\n\ninterface SharedListingsQueryData {\n healthyBowlSharedMarketListings: SharedMarketListing[];\n}\n\ninterface SetListingSharedData {\n setHealthyBowlListingShared: { id: string; name: string };\n}\n\n/**\n * Loads the shared cross-farm listings. Filters are passed to the server (not applied client-side)\n * so the buyer searches every farm's catalogue, not just the page they happen to have loaded.\n *\n * `sharedListingIds` is the set of listing ids currently visible in the shared market. The\n * fixed-price tab uses it to show whether one of the farm's OWN listings is published — the\n * `MarketplaceProduct` type deliberately exposes no `sharedMarket` field, so this is the only\n * server-truth available. Caveat: the shared read excludes out-of-stock listings, so a published\n * listing with zero stock reads as unpublished until it is restocked; a toggle performed in-session\n * overrides that (see `MarketplacePage`).\n */\nexport function useSharedMarketListings(filters: SharedMarketFilters = {}) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const category = filters.category && filters.category !== 'All' ? filters.category : null;\n const search = filters.search?.trim() ? filters.search.trim() : null;\n const limit = filters.limit ?? null;\n\n const { data, loading, error, refetch } = useQuery<SharedListingsQueryData>(SHARED_LISTINGS_QUERY, {\n variables: { context, category, search, limit },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n const listings = useMemo(() => data?.healthyBowlSharedMarketListings ?? [], [data]);\n const sharedListingIds = useMemo(() => new Set(listings.map((l) => l.id)), [listings]);\n\n return { listings, sharedListingIds, loading, error, refetch };\n}\n\n/**\n * Publish / unpublish one of the farm's OWN listings to the shared cross-farm market.\n * Workspace-scoped server-side: a farm can only ever change the flag on its own listings.\n */\nexport function useSetListingShared() {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const [mutate, { loading }] = useMutation<SetListingSharedData>(SET_LISTING_SHARED);\n\n const setListingShared = useCallback(\n async (id: string, shared: boolean) => {\n const res = await mutate({ variables: { id, shared, context } });\n return res.data?.setHealthyBowlListingShared;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [mutate, workspaceId]\n );\n\n return { setListingShared, saving: loading };\n}\n"],"mappings":";;;;;AA+DA,IAAM,IAAwB,CAAG;;;QAhBH,qJAmBA;;;GAKxB,IAAqB,CAAG;;;;;;;;AA4B9B,SAAgB,EAAwB,IAA+B,EAAE,EAAE;CACzE,IAAM,EAAE,mBAAgB,GAAgB,EAMlC,EAAE,SAAM,YAAS,UAAO,eAAY,EAAkC,GAAuB;EACjG,WAAW;GAAE,SANC,EAAE,gBAAa;GAMP,UALP,EAAQ,YAAY,EAAQ,aAAa,QAAQ,EAAQ,WAAW;GAKnD,QAJnB,EAAQ,QAAQ,MAAM,GAAG,EAAQ,OAAO,MAAM,GAAG;GAItB,OAH5B,EAAQ,SAAS;GAGkB;EAC/C,MAAM,CAAC;EACP,aAAa;EACb,6BAA6B;EAC9B,CAAC,EAEI,IAAW,QAAc,GAAM,mCAAmC,EAAE,EAAE,CAAC,EAAK,CAAC;AAGnF,QAAO;EAAE;EAAU,kBAFM,QAAc,IAAI,IAAI,EAAS,KAAK,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,EAAS,CAAC;EAEjD;EAAS;EAAO;EAAS;;AAOhE,SAAgB,IAAsB;CACpC,IAAM,EAAE,mBAAgB,GAAgB,EAClC,IAAU,EAAE,gBAAa,EACzB,CAAC,GAAQ,EAAE,gBAAa,EAAkC,EAAmB;AAWnF,QAAO;EAAE,kBATgB,EACvB,OAAO,GAAY,OACL,MAAM,EAAO,EAAE,WAAW;GAAE;GAAI;GAAQ;GAAS,EAAE,CAAC,EACrD,MAAM,6BAGnB,CAAC,GAAQ,EAAY,CACtB;EAE0B,QAAQ;EAAS"}