@burdenoff/microfe-healthybowl 2026.826.1 → 2026.828.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.
- package/dist/healthybowl/HealthyBowlRoot.js +1 -1
- package/dist/healthybowl/HealthyBowlRoot.js.map +1 -1
- package/dist/healthybowl/components/HBEntityImages.js.map +1 -1
- package/dist/healthybowl/hooks/useTraceScanActivity.js +68 -0
- package/dist/healthybowl/hooks/useTraceScanActivity.js.map +1 -0
- package/dist/healthybowl/pages/compliance/IcsGrowerDetailPage.js +174 -129
- package/dist/healthybowl/pages/compliance/IcsGrowerDetailPage.js.map +1 -1
- package/dist/healthybowl/pages/crops/FieldDetailsPage.js +858 -803
- package/dist/healthybowl/pages/crops/FieldDetailsPage.js.map +1 -1
- package/dist/healthybowl/pages/traceability/QRCodesPage.js +320 -220
- package/dist/healthybowl/pages/traceability/QRCodesPage.js.map +1 -1
- package/dist/healthybowl/pages/traceability/TraceLedgerPage.js +261 -98
- package/dist/healthybowl/pages/traceability/TraceLedgerPage.js.map +1 -1
- package/dist/healthybowl/public/PortalLanguagePicker.js +1 -1
- package/dist/healthybowl/public/PortalLanguagePicker.js.map +1 -1
- package/package.json +1 -1
|
@@ -11,7 +11,7 @@ import { Award as re, Banknote as ie, BarChart3 as ae, Bug as oe, Cloud as u, Cl
|
|
|
11
11
|
import { jsx as R, jsxs as z } from "react/jsx-runtime";
|
|
12
12
|
import { FeatureFlagProvider as B, useFeatureFlags as V } from "@burdenoff/fe-libs/shared/feature-flags";
|
|
13
13
|
//#region src/healthybowl/HealthyBowlRoot.tsx
|
|
14
|
-
var H = new Set([
|
|
14
|
+
var H = /* @__PURE__ */ new Set([]), U = [
|
|
15
15
|
".lucide-arrow-right",
|
|
16
16
|
".lucide-arrow-left",
|
|
17
17
|
".lucide-chevron-right",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HealthyBowlRoot.js","names":[],"sources":["../../src/healthybowl/HealthyBowlRoot.tsx"],"sourcesContent":["/**\n * HealthyBowl Root Component\n * @module healthybowl\n */\n\nimport type { FC } from 'react';\nimport { useCallback, useEffect } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport {\n Home,\n Tractor,\n ListChecks,\n Wheat,\n PawPrint,\n Cloud,\n Map as MapIcon,\n ShoppingCart,\n DollarSign,\n BarChart3,\n FlaskConical,\n Bug,\n ScanSearch,\n Factory,\n Package,\n ScanLine,\n ShieldCheck,\n Landmark,\n Banknote,\n Stethoscope,\n UserCheck,\n Users,\n CloudUpload,\n RefreshCw,\n ShieldAlert,\n LineChart,\n Fence,\n Radio,\n Leaf,\n Sprout,\n Award,\n Globe,\n Users2,\n} from 'lucide-react';\nimport { HealthyBowlProvider } from './context/HealthyBowlContext';\nimport { FeatureFlagProvider, useFeatureFlags } from '@burdenoff/fe-libs/shared/feature-flags';\nimport {\n HEALTHYBOWL_CARBON_FEATURE_FLAG,\n HEALTHYBOWL_CARBON_FEATURE_FLAG_KEYS,\n isHealthyBowlCarbonEnabled,\n} from './carbonFeatureFlag';\nimport { HealthyBowlRoutes } from './HealthyBowlRoutes';\nimport { ErrorBoundary } from './components/ErrorBoundary';\nimport { ConfirmProvider } from './components/ConfirmDialog';\nimport { OfflineSyncProvider } from './offline/OfflineSyncProvider';\nimport { normalizeBasePath, setHbFormatLocale } from './utils/helpers';\nimport type { HealthyBowlRootProps, NavItem } from './types';\n\n// Locales that render right-to-left. Arabic is the only RTL language in the shell's supported set\n// today; kept as a set so adding Hebrew/Farsi/Urdu later is a one-line change (BOFF-6119).\nconst RTL_LOCALES = new Set<string>(['ar']);\n\n// Horizontal directional lucide icons whose glyph must point the other way under RTL. lucide-react\n// tags every icon with a `lucide-<name>` class; scaleX(-1) mirrors the horizontal ones (vertical\n// chevrons up/down are unchanged by a horizontal flip). Kept off the LTR path via the [dir=rtl] scope.\nconst RTL_ICON_MIRROR_CSS = [\n '.lucide-arrow-right',\n '.lucide-arrow-left',\n '.lucide-chevron-right',\n '.lucide-chevron-left',\n '.lucide-chevrons-right',\n '.lucide-chevrons-left',\n '.lucide-move-right',\n '.lucide-move-left',\n]\n .map((c) => `[dir=\"rtl\"] ${c}`)\n .join(',')\n .concat('{transform:scaleX(-1)}');\n\nconst SUSTAINABILITY_NAV_ITEM_IDS = new Set([\n 'healthybowl-sustainability',\n 'healthybowl-sustainability-carbon',\n 'healthybowl-sustainability-soil',\n 'healthybowl-sustainability-credits',\n 'healthybowl-sustainability-eudr',\n]);\n\nexport function filterHealthyBowlNavItemsForCarbon(navItems: NavItem[], carbonEnabled: boolean): NavItem[] {\n return carbonEnabled ? navItems : navItems.filter((item) => !SUSTAINABILITY_NAV_ITEM_IDS.has(item.id));\n}\n\nconst HealthyBowlRootContent: FC<HealthyBowlRootProps> = (props) => {\n const { registerNavItems, registerFooterItems, basePath = '/' } = props;\n const { error, getEvaluation, isLoading } = useFeatureFlags();\n const carbonEnabled = isHealthyBowlCarbonEnabled(\n getEvaluation(HEALTHYBOWL_CARBON_FEATURE_FLAG),\n isLoading || error !== null\n );\n const { t: translate, locale } = useI18n();\n\n // HealthyBowl's Intl.* formatters (utils/helpers.ts) are plain functions used\n // across ~490 call sites, so they can't call useI18n() themselves. Sync the\n // shell's active language into their ambient locale here — the product's\n // single I18n consumer that wraps every page — so number / currency / date\n // grouping tracks the chosen language (BOFF-6202). Done during render, not in\n // an effect, so children rendered in this same pass already format with the\n // current locale (no one-frame western-grouping flash on a language switch).\n setHbFormatLocale(locale);\n\n // BOFF-6119 — Arabic (and any future RTL locale) must render right-to-left. HealthyBowl's own\n // components are migrated to logical CSS utilities (physical ml-/pr-/left-/text-left/… → logical\n // ms-/pe-/start-/text-start/…), so setting `dir` makes the whole HB surface mirror correctly.\n const dir: 'rtl' | 'ltr' = RTL_LOCALES.has(locale) ? 'rtl' : 'ltr';\n\n // Set the direction on the document root, not just an in-flow wrapper: HB's overlays\n // (confirm/alert dialogs, dropdowns, tooltips) render through Radix portals attached to\n // document.body, so a subtree wrapper would leave them LTR. The shared fe-libs I18nProvider\n // deliberately leaves document.dir unset (the app shell and other products aren't migrated to\n // logical CSS yet — fleet ticket BOFF-5998), so HB owns it here and restores the previous value\n // on unmount, keeping the effect self-contained to when a HealthyBowl surface is mounted.\n useEffect(() => {\n const el = document.documentElement;\n const previous = el.getAttribute('dir');\n el.setAttribute('dir', dir);\n return () => {\n if (previous === null) el.removeAttribute('dir');\n else el.setAttribute('dir', previous);\n };\n }, [dir]);\n\n const t = useCallback(\n (key: string, fallback: string): string => {\n const value = translate(key);\n return value === key ? fallback : value;\n },\n [translate]\n );\n\n // Helper to join paths correctly\n const joinPath = (base: string, path: string): string => {\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return cleanBase + cleanPath;\n };\n\n // Register navigation items with shell on mount\n useEffect(() => {\n if (!registerNavItems) return;\n\n const allNavItems: NavItem[] = [\n // Dashboard\n {\n id: 'healthybowl-dashboard',\n label: t('healthybowl.nav.dashboard', 'Dashboard'),\n // The product index IS the dashboard. Normalize a trailing slash like\n // every sibling item (joinPath) so active-state highlighting matches if\n // the host ever passes '/healthybowl/'.\n path: normalizeBasePath(basePath),\n icon: <Home size={20} />,\n order: 1,\n group: 'main',\n },\n\n // My Farm\n {\n id: 'healthybowl-farm',\n label: t('healthybowl.nav.farm', 'My Farm'),\n path: joinPath(basePath, 'farm'),\n icon: <Tractor size={20} />,\n order: 2,\n group: 'main',\n },\n\n // Farm Tasks (PlanMagnet embed) — shared work-item board across the farm.\n {\n id: 'healthybowl-tasks',\n label: t('healthybowl.nav.tasks', 'Tasks'),\n path: joinPath(basePath, 'tasks'),\n icon: <ListChecks size={20} />,\n order: 3,\n group: 'main',\n },\n\n // Crops\n {\n id: 'healthybowl-crops',\n label: t('healthybowl.nav.crops', 'Crops'),\n path: joinPath(basePath, 'crops'),\n icon: <Wheat size={20} />,\n order: 10,\n group: 'farming',\n },\n\n // Livestock\n {\n id: 'healthybowl-livestock',\n label: t('healthybowl.nav.livestock', 'Livestock'),\n path: joinPath(basePath, 'livestock'),\n icon: <PawPrint size={20} />,\n order: 11,\n group: 'farming',\n },\n\n // Livestock — Analytics (BOFF-6126). The growth, feed and herd-stats charts (BOFF-5971) also\n // render inline on the livestock dashboard; this gives them a dedicated URL and full-width home.\n {\n id: 'healthybowl-livestock-analytics',\n label: t('healthybowl.nav.livestockAnalytics', 'Livestock Analytics'),\n path: joinPath(basePath, 'livestock/analytics'),\n icon: <LineChart size={20} />,\n order: 11.3,\n group: 'farming',\n },\n\n // Livestock — Grazing management (BOFF-5970). Sits next to Livestock rather than inside it\n // because rotational grazing is a daily decision about FIELDS, not a herd-record lookup.\n {\n id: 'healthybowl-grazing',\n label: t('healthybowl.nav.grazing', 'Grazing'),\n path: joinPath(basePath, 'livestock/grazing'),\n icon: <Fence size={20} />,\n order: 11.4,\n group: 'farming',\n },\n\n // Livestock — Medication Withdrawal Alerts (BOFF-2885)\n {\n id: 'healthybowl-withdrawal-alerts',\n label: t('healthybowl.nav.withdrawalAlerts', 'Withdrawal Alerts'),\n path: joinPath(basePath, 'livestock/withdrawal-alerts'),\n icon: <ShieldAlert size={20} />,\n order: 11.5,\n group: 'farming',\n },\n\n // Weather\n {\n id: 'healthybowl-weather',\n label: t('healthybowl.nav.weather', 'Weather'),\n path: joinPath(basePath, 'weather'),\n icon: <Cloud size={20} />,\n order: 12,\n group: 'farming',\n },\n\n // Field Map — draw & manage field boundaries on satellite imagery\n {\n id: 'healthybowl-field-map',\n label: t('healthybowl.nav.fieldMap', 'Field Map'),\n path: joinPath(basePath, 'field-map'),\n icon: <MapIcon size={20} />,\n order: 12.5,\n group: 'farming',\n },\n\n // Field Capture — offline-first observation capture (BOFF-2883)\n {\n id: 'healthybowl-field-capture',\n label: t('healthybowl.nav.fieldCapture', 'Field Capture'),\n path: joinPath(basePath, 'field-capture'),\n icon: <CloudUpload size={20} />,\n order: 12.6,\n group: 'farming',\n },\n\n // Pending Sync — the offline outbox / sync queue (BOFF-2883)\n {\n id: 'healthybowl-pending-sync',\n label: t('healthybowl.nav.pendingSync', 'Pending Sync'),\n path: joinPath(basePath, 'field-capture/pending'),\n icon: <RefreshCw size={20} />,\n order: 12.7,\n group: 'farming',\n },\n\n // Field Sensors — live probe monitoring (BOFF-2894)\n {\n id: 'healthybowl-field-sensors',\n label: t('healthybowl.nav.fieldSensors', 'Field Sensors'),\n path: joinPath(basePath, 'field-sensors'),\n icon: <Radio size={20} />,\n order: 12.75,\n group: 'farming',\n },\n\n // Soil Health\n {\n id: 'healthybowl-soil',\n label: t('healthybowl.nav.soilHealth', 'Soil Health'),\n path: joinPath(basePath, 'soil'),\n icon: <FlaskConical size={20} />,\n order: 13,\n group: 'farming',\n },\n\n // Pest Management\n {\n id: 'healthybowl-pest',\n label: t('healthybowl.nav.pestManagement', 'Pest Management'),\n path: joinPath(basePath, 'pest-management'),\n icon: <Bug size={20} />,\n order: 14,\n group: 'farming',\n },\n {\n id: 'healthybowl-pest-ai',\n label: t('healthybowl.nav.aiPestDetection', 'AI Pest Detection'),\n path: joinPath(basePath, 'pest-management/ai-detection'),\n icon: <ScanSearch size={20} />,\n order: 14.5,\n group: 'farming',\n },\n\n // Production\n {\n id: 'healthybowl-production',\n label: t('healthybowl.nav.production', 'Production'),\n path: joinPath(basePath, 'production'),\n icon: <Factory size={20} />,\n order: 20,\n group: 'business',\n },\n\n // Products\n {\n id: 'healthybowl-products',\n label: t('healthybowl.nav.products', 'Products'),\n path: joinPath(basePath, 'products'),\n icon: <Package size={20} />,\n order: 21,\n group: 'business',\n },\n\n // Marketplace\n {\n id: 'healthybowl-marketplace',\n label: t('healthybowl.nav.marketplace', 'Marketplace'),\n path: joinPath(basePath, 'marketplace'),\n icon: <ShoppingCart size={20} />,\n order: 22,\n group: 'business',\n },\n\n // Co-operative / FPO aggregation (BOFF-6023)\n {\n id: 'healthybowl-coop',\n label: t('healthybowl.nav.coop', 'Co-operative'),\n path: joinPath(basePath, 'coop'),\n icon: <Users2 size={20} />,\n order: 22.5,\n group: 'business',\n },\n\n // Financial\n {\n id: 'healthybowl-financial',\n label: t('healthybowl.nav.financial', 'Financial'),\n path: joinPath(basePath, 'financial'),\n icon: <DollarSign size={20} />,\n order: 23,\n group: 'business',\n },\n\n // Financier portfolio (B2B2C bridge)\n {\n id: 'healthybowl-financier',\n label: t('healthybowl.nav.financier', 'Financier'),\n path: joinPath(basePath, 'financier'),\n icon: <Banknote size={20} />,\n order: 24,\n group: 'business',\n },\n\n // Compliance\n {\n id: 'healthybowl-compliance',\n label: t('healthybowl.nav.compliance', 'Compliance'),\n path: joinPath(basePath, 'compliance'),\n icon: <ShieldCheck size={20} />,\n order: 30,\n group: 'compliance',\n },\n\n // Traceability\n {\n id: 'healthybowl-traceability',\n label: t('healthybowl.nav.traceability', 'Traceability'),\n path: joinPath(basePath, 'traceability'),\n icon: <ScanLine size={20} />,\n order: 31,\n group: 'compliance',\n },\n\n // Sustainability — Carbon & Climate (BOFF-2896)\n {\n id: 'healthybowl-sustainability',\n label: t('healthybowl.nav.sustainability', 'Sustainability'),\n path: joinPath(basePath, 'sustainability'),\n icon: <Leaf size={20} />,\n order: 32,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-carbon',\n label: t('healthybowl.nav.sustainabilityCarbon', 'Carbon & GHG'),\n path: joinPath(basePath, 'sustainability/carbon'),\n icon: <Factory size={20} />,\n order: 32.1,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-soil',\n label: t('healthybowl.nav.sustainabilitySoil', 'Soil Carbon'),\n path: joinPath(basePath, 'sustainability/soil-carbon'),\n icon: <Sprout size={20} />,\n order: 32.2,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-credits',\n label: t('healthybowl.nav.sustainabilityCredits', 'Carbon Credits'),\n path: joinPath(basePath, 'sustainability/credits'),\n icon: <Award size={20} />,\n order: 32.3,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-eudr',\n label: t('healthybowl.nav.sustainabilityEudr', 'EUDR Due-Diligence'),\n path: joinPath(basePath, 'sustainability/eudr'),\n icon: <Globe size={20} />,\n order: 32.4,\n group: 'compliance',\n },\n\n // Government Schemes\n {\n id: 'healthybowl-schemes',\n label: t('healthybowl.nav.governmentSchemes', 'Gov. Schemes'),\n path: joinPath(basePath, 'government-schemes'),\n icon: <Landmark size={20} />,\n order: 40,\n group: 'support',\n },\n\n // Network\n {\n id: 'healthybowl-network',\n label: t('healthybowl.nav.network', 'Network'),\n path: joinPath(basePath, 'network'),\n icon: <Users size={20} />,\n order: 41,\n group: 'support',\n },\n\n // Analytics\n {\n id: 'healthybowl-analytics',\n label: t('healthybowl.nav.analytics', 'Analytics'),\n path: joinPath(basePath, 'analytics'),\n icon: <BarChart3 size={20} />,\n order: 42,\n group: 'support',\n },\n\n // My Advisors (UC-16 — farmer side)\n {\n id: 'healthybowl-advisors',\n label: t('healthybowl.nav.advisors', 'My Advisors'),\n path: joinPath(basePath, 'advisors'),\n icon: <UserCheck size={20} />,\n order: 43,\n group: 'support',\n },\n\n // Consultant portfolio (UC-16 — consultant side)\n {\n id: 'healthybowl-consultant',\n label: t('healthybowl.nav.consultant', 'Consultant'),\n path: joinPath(basePath, 'consultant'),\n icon: <Stethoscope size={20} />,\n order: 44,\n group: 'support',\n },\n ];\n\n // All sections are reachable. Marketplace (UC-08), Network (UC-12) and\n // Traceability (UC-11) render real read data + their real create flows\n // (createMarketplaceProduct / createCommunityPost / createTraceBatch); the\n // few genuinely-unbacked actions (checkout, booking, QR resolution) show\n // honest \"not available yet\" states in-page rather than hiding the section.\n // The operational carbon kill switch hides only Sustainability items;\n // Compliance and Traceability remain available.\n const navItems = filterHealthyBowlNavItemsForCarbon(allNavItems, carbonEnabled);\n const cleanup = registerNavItems(navItems);\n return cleanup;\n }, [registerNavItems, basePath, carbonEnabled, t]);\n\n // Register footer items\n useEffect(() => {\n if (!registerFooterItems) return;\n\n const footerItems = [\n {\n id: 'healthybowl-status',\n label: t('healthybowl.footer.ready', 'HealthyBowl Ready'),\n type: 'status' as const,\n order: 10,\n section: 'left' as const,\n },\n ];\n\n const cleanup = registerFooterItems(footerItems);\n return cleanup;\n }, [registerFooterItems, t]);\n\n return (\n <HealthyBowlProvider {...props}>\n {/* Logical CSS utilities flip an icon's *position* under RTL, but not its glyph. Navigational\n arrows/chevrons must also point the other way, so mirror the horizontal ones. Vertical\n chevrons (up/down, e.g. accordions) are unaffected by scaleX. Scoped to [dir=rtl] so it is\n inert in LTR. See BOFF-6119. */}\n <style>{RTL_ICON_MIRROR_CSS}</style>\n <ErrorBoundary>\n <ConfirmProvider>\n <OfflineSyncProvider>\n <HealthyBowlRoutes />\n </OfflineSyncProvider>\n </ConfirmProvider>\n </ErrorBoundary>\n </HealthyBowlProvider>\n );\n};\n\nexport const HealthyBowlRoot: FC<HealthyBowlRootProps> = (props) => (\n <FeatureFlagProvider\n key={props.workspaceId ?? 'no-workspace'}\n workspaceId={props.workspaceId ?? null}\n gateway=\"global\"\n flagKeys={HEALTHYBOWL_CARBON_FEATURE_FLAG_KEYS}\n defaultEnabled={true}\n >\n <HealthyBowlRootContent {...props} />\n </FeatureFlagProvider>\n);\n"],"mappings":";;;;;;;;;;;;;AA2DA,IAAM,IAAc,IAAI,IAAY,CAAC,IAAI,CAAC,GAKpC,IAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,EACG,KAAK,MAAM,eAAe,GAAG,EAC7B,KAAK,GAAG,EACR,OAAO,wBAAwB,GAE5B,IAA8B,IAAI,IAAI;CAC1C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,EAAmC,GAAqB,GAAmC;CACzG,OAAO,IAAgB,IAAW,EAAS,QAAQ,MAAS,CAAC,EAA4B,IAAI,EAAK,EAAE,CAAC;AACvG;AAEA,IAAM,KAAoD,MAAU;CAClE,IAAM,EAAE,qBAAkB,wBAAqB,cAAW,QAAQ,GAC5D,EAAE,UAA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C;EAAkB;EAAU;EAAe;CAAC,CAAC,GAGjD,QAAgB;EACT,OAaL,OADgB,EAAoB,CATlC;GACE,IAAI;GACJ,OAAO,EAAE,4BAA4B,mBAAmB;GACxD,MAAM;GACN,OAAO;GACP,SAAS;EACX,CAGkC,CAC7B;CACT,GAAG,CAAC,GAAqB,CAAC,CAAC,GAGzB,kBAAC,GAAD;EAAqB,GAAI;YAAzB,CAKE,kBAAC,SAAD,EAAA,UAAQ,EAA2B,CAAA,GACnC,kBAAC,GAAD,EAAA,UACE,kBAAC,GAAD,EAAA,UACE,kBAAC,GAAD,EAAA,UACE,kBAAC,GAAD,CAAoB,CAAA,EACD,CAAA,EACN,CAAA,EACJ,CAAA,CACI;;AAEzB,GAEa,KAA6C,MACxD,kBAAC,GAAD;CAEE,aAAa,EAAM,eAAe;CAClC,SAAQ;CACR,UAAU;CACV,gBAAgB;WAEhB,kBAAC,GAAD,EAAwB,GAAI,EAAQ,CAAA;AACjB,GAPd,EAAM,eAAe,cAOP"}
|
|
1
|
+
{"version":3,"file":"HealthyBowlRoot.js","names":[],"sources":["../../src/healthybowl/HealthyBowlRoot.tsx"],"sourcesContent":["/**\n * HealthyBowl Root Component\n * @module healthybowl\n */\n\nimport type { FC } from 'react';\nimport { useCallback, useEffect } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport {\n Home,\n Tractor,\n ListChecks,\n Wheat,\n PawPrint,\n Cloud,\n Map as MapIcon,\n ShoppingCart,\n DollarSign,\n BarChart3,\n FlaskConical,\n Bug,\n ScanSearch,\n Factory,\n Package,\n ScanLine,\n ShieldCheck,\n Landmark,\n Banknote,\n Stethoscope,\n UserCheck,\n Users,\n CloudUpload,\n RefreshCw,\n ShieldAlert,\n LineChart,\n Fence,\n Radio,\n Leaf,\n Sprout,\n Award,\n Globe,\n Users2,\n} from 'lucide-react';\nimport { HealthyBowlProvider } from './context/HealthyBowlContext';\nimport { FeatureFlagProvider, useFeatureFlags } from '@burdenoff/fe-libs/shared/feature-flags';\nimport {\n HEALTHYBOWL_CARBON_FEATURE_FLAG,\n HEALTHYBOWL_CARBON_FEATURE_FLAG_KEYS,\n isHealthyBowlCarbonEnabled,\n} from './carbonFeatureFlag';\nimport { HealthyBowlRoutes } from './HealthyBowlRoutes';\nimport { ErrorBoundary } from './components/ErrorBoundary';\nimport { ConfirmProvider } from './components/ConfirmDialog';\nimport { OfflineSyncProvider } from './offline/OfflineSyncProvider';\nimport { normalizeBasePath, setHbFormatLocale } from './utils/helpers';\nimport type { HealthyBowlRootProps, NavItem } from './types';\n\n// Locales that render right-to-left.\n//\n// DELIBERATELY EMPTY — Arabic was removed here, reverting BOFF-6119's rendering decision.\n//\n// BOFF-6119 migrated *this package* to logical CSS utilities (461 logical vs 54 physical) and then\n// set `dir` on `document.documentElement`. But the document root is not this package's to mirror:\n// the surrounding shell is `fe-libs` (177 physical utilities, 0 logical) and `healthybowl-app`\n// (7 physical, 0 logical). Neither is migrated, so `dir=\"rtl\"` mirrored them incorrectly and the\n// sidebar jumped to the right — which is what the layout complaint was about.\n//\n// fe-libs documents this exact failure mode and refuses to set `dir` for ANY locale until the\n// fleet-wide migration lands (see its I18nProvider note + BOFF-5998: \"sidebars on the wrong side,\n// icons mirrored, chevrons reversed\"). HealthyBowl was the only surface on the fleet setting it,\n// so Arabic rendered differently here than in every other product.\n//\n// Keeping the Set (rather than deleting the mechanism) so BOFF-6119 can be restored as a one-line\n// change once BOFF-5998 migrates the shell. Re-adding 'ar' before then reintroduces the bug.\nconst RTL_LOCALES = new Set<string>([]);\n\n// Horizontal directional lucide icons whose glyph must point the other way under RTL. lucide-react\n// tags every icon with a `lucide-<name>` class; scaleX(-1) mirrors the horizontal ones (vertical\n// chevrons up/down are unchanged by a horizontal flip). Kept off the LTR path via the [dir=rtl] scope.\nconst RTL_ICON_MIRROR_CSS = [\n '.lucide-arrow-right',\n '.lucide-arrow-left',\n '.lucide-chevron-right',\n '.lucide-chevron-left',\n '.lucide-chevrons-right',\n '.lucide-chevrons-left',\n '.lucide-move-right',\n '.lucide-move-left',\n]\n .map((c) => `[dir=\"rtl\"] ${c}`)\n .join(',')\n .concat('{transform:scaleX(-1)}');\n\nconst SUSTAINABILITY_NAV_ITEM_IDS = new Set([\n 'healthybowl-sustainability',\n 'healthybowl-sustainability-carbon',\n 'healthybowl-sustainability-soil',\n 'healthybowl-sustainability-credits',\n 'healthybowl-sustainability-eudr',\n]);\n\nexport function filterHealthyBowlNavItemsForCarbon(navItems: NavItem[], carbonEnabled: boolean): NavItem[] {\n return carbonEnabled ? navItems : navItems.filter((item) => !SUSTAINABILITY_NAV_ITEM_IDS.has(item.id));\n}\n\nconst HealthyBowlRootContent: FC<HealthyBowlRootProps> = (props) => {\n const { registerNavItems, registerFooterItems, basePath = '/' } = props;\n const { error, getEvaluation, isLoading } = useFeatureFlags();\n const carbonEnabled = isHealthyBowlCarbonEnabled(\n getEvaluation(HEALTHYBOWL_CARBON_FEATURE_FLAG),\n isLoading || error !== null\n );\n const { t: translate, locale } = useI18n();\n\n // HealthyBowl's Intl.* formatters (utils/helpers.ts) are plain functions used\n // across ~490 call sites, so they can't call useI18n() themselves. Sync the\n // shell's active language into their ambient locale here — the product's\n // single I18n consumer that wraps every page — so number / currency / date\n // grouping tracks the chosen language (BOFF-6202). Done during render, not in\n // an effect, so children rendered in this same pass already format with the\n // current locale (no one-frame western-grouping flash on a language switch).\n setHbFormatLocale(locale);\n\n // BOFF-6119 wired RTL rendering here. `RTL_LOCALES` is now empty, so this resolves to 'ltr' for\n // every locale and the effect below writes dir=\"ltr\" — matching fe-libs and every other product.\n //\n // The original claim on this line was that \"HealthyBowl's own components are migrated to logical\n // CSS utilities, so setting `dir` makes the whole HB surface mirror correctly.\" Only the first\n // half held: this package is ~90% logical, but `dir` is set on the DOCUMENT ROOT (see below), so\n // it also mirrors fe-libs (177 physical / 0 logical) and healthybowl-app (7 / 0). \"The whole HB\n // surface\" is bigger than this package, and the rest of it was never migrated.\n const dir: 'rtl' | 'ltr' = RTL_LOCALES.has(locale) ? 'rtl' : 'ltr';\n\n // Set the direction on the document root, not just an in-flow wrapper: HB's overlays\n // (confirm/alert dialogs, dropdowns, tooltips) render through Radix portals attached to\n // document.body, so a subtree wrapper would leave them LTR. The shared fe-libs I18nProvider\n // deliberately leaves document.dir unset (the app shell and other products aren't migrated to\n // logical CSS yet — fleet ticket BOFF-5998), so HB owns it here and restores the previous value\n // on unmount, keeping the effect self-contained to when a HealthyBowl surface is mounted.\n useEffect(() => {\n const el = document.documentElement;\n const previous = el.getAttribute('dir');\n el.setAttribute('dir', dir);\n return () => {\n if (previous === null) el.removeAttribute('dir');\n else el.setAttribute('dir', previous);\n };\n }, [dir]);\n\n const t = useCallback(\n (key: string, fallback: string): string => {\n const value = translate(key);\n return value === key ? fallback : value;\n },\n [translate]\n );\n\n // Helper to join paths correctly\n const joinPath = (base: string, path: string): string => {\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return cleanBase + cleanPath;\n };\n\n // Register navigation items with shell on mount\n useEffect(() => {\n if (!registerNavItems) return;\n\n const allNavItems: NavItem[] = [\n // Dashboard\n {\n id: 'healthybowl-dashboard',\n label: t('healthybowl.nav.dashboard', 'Dashboard'),\n // The product index IS the dashboard. Normalize a trailing slash like\n // every sibling item (joinPath) so active-state highlighting matches if\n // the host ever passes '/healthybowl/'.\n path: normalizeBasePath(basePath),\n icon: <Home size={20} />,\n order: 1,\n group: 'main',\n },\n\n // My Farm\n {\n id: 'healthybowl-farm',\n label: t('healthybowl.nav.farm', 'My Farm'),\n path: joinPath(basePath, 'farm'),\n icon: <Tractor size={20} />,\n order: 2,\n group: 'main',\n },\n\n // Farm Tasks (PlanMagnet embed) — shared work-item board across the farm.\n {\n id: 'healthybowl-tasks',\n label: t('healthybowl.nav.tasks', 'Tasks'),\n path: joinPath(basePath, 'tasks'),\n icon: <ListChecks size={20} />,\n order: 3,\n group: 'main',\n },\n\n // Crops\n {\n id: 'healthybowl-crops',\n label: t('healthybowl.nav.crops', 'Crops'),\n path: joinPath(basePath, 'crops'),\n icon: <Wheat size={20} />,\n order: 10,\n group: 'farming',\n },\n\n // Livestock\n {\n id: 'healthybowl-livestock',\n label: t('healthybowl.nav.livestock', 'Livestock'),\n path: joinPath(basePath, 'livestock'),\n icon: <PawPrint size={20} />,\n order: 11,\n group: 'farming',\n },\n\n // Livestock — Analytics (BOFF-6126). The growth, feed and herd-stats charts (BOFF-5971) also\n // render inline on the livestock dashboard; this gives them a dedicated URL and full-width home.\n {\n id: 'healthybowl-livestock-analytics',\n label: t('healthybowl.nav.livestockAnalytics', 'Livestock Analytics'),\n path: joinPath(basePath, 'livestock/analytics'),\n icon: <LineChart size={20} />,\n order: 11.3,\n group: 'farming',\n },\n\n // Livestock — Grazing management (BOFF-5970). Sits next to Livestock rather than inside it\n // because rotational grazing is a daily decision about FIELDS, not a herd-record lookup.\n {\n id: 'healthybowl-grazing',\n label: t('healthybowl.nav.grazing', 'Grazing'),\n path: joinPath(basePath, 'livestock/grazing'),\n icon: <Fence size={20} />,\n order: 11.4,\n group: 'farming',\n },\n\n // Livestock — Medication Withdrawal Alerts (BOFF-2885)\n {\n id: 'healthybowl-withdrawal-alerts',\n label: t('healthybowl.nav.withdrawalAlerts', 'Withdrawal Alerts'),\n path: joinPath(basePath, 'livestock/withdrawal-alerts'),\n icon: <ShieldAlert size={20} />,\n order: 11.5,\n group: 'farming',\n },\n\n // Weather\n {\n id: 'healthybowl-weather',\n label: t('healthybowl.nav.weather', 'Weather'),\n path: joinPath(basePath, 'weather'),\n icon: <Cloud size={20} />,\n order: 12,\n group: 'farming',\n },\n\n // Field Map — draw & manage field boundaries on satellite imagery\n {\n id: 'healthybowl-field-map',\n label: t('healthybowl.nav.fieldMap', 'Field Map'),\n path: joinPath(basePath, 'field-map'),\n icon: <MapIcon size={20} />,\n order: 12.5,\n group: 'farming',\n },\n\n // Field Capture — offline-first observation capture (BOFF-2883)\n {\n id: 'healthybowl-field-capture',\n label: t('healthybowl.nav.fieldCapture', 'Field Capture'),\n path: joinPath(basePath, 'field-capture'),\n icon: <CloudUpload size={20} />,\n order: 12.6,\n group: 'farming',\n },\n\n // Pending Sync — the offline outbox / sync queue (BOFF-2883)\n {\n id: 'healthybowl-pending-sync',\n label: t('healthybowl.nav.pendingSync', 'Pending Sync'),\n path: joinPath(basePath, 'field-capture/pending'),\n icon: <RefreshCw size={20} />,\n order: 12.7,\n group: 'farming',\n },\n\n // Field Sensors — live probe monitoring (BOFF-2894)\n {\n id: 'healthybowl-field-sensors',\n label: t('healthybowl.nav.fieldSensors', 'Field Sensors'),\n path: joinPath(basePath, 'field-sensors'),\n icon: <Radio size={20} />,\n order: 12.75,\n group: 'farming',\n },\n\n // Soil Health\n {\n id: 'healthybowl-soil',\n label: t('healthybowl.nav.soilHealth', 'Soil Health'),\n path: joinPath(basePath, 'soil'),\n icon: <FlaskConical size={20} />,\n order: 13,\n group: 'farming',\n },\n\n // Pest Management\n {\n id: 'healthybowl-pest',\n label: t('healthybowl.nav.pestManagement', 'Pest Management'),\n path: joinPath(basePath, 'pest-management'),\n icon: <Bug size={20} />,\n order: 14,\n group: 'farming',\n },\n {\n id: 'healthybowl-pest-ai',\n label: t('healthybowl.nav.aiPestDetection', 'AI Pest Detection'),\n path: joinPath(basePath, 'pest-management/ai-detection'),\n icon: <ScanSearch size={20} />,\n order: 14.5,\n group: 'farming',\n },\n\n // Production\n {\n id: 'healthybowl-production',\n label: t('healthybowl.nav.production', 'Production'),\n path: joinPath(basePath, 'production'),\n icon: <Factory size={20} />,\n order: 20,\n group: 'business',\n },\n\n // Products\n {\n id: 'healthybowl-products',\n label: t('healthybowl.nav.products', 'Products'),\n path: joinPath(basePath, 'products'),\n icon: <Package size={20} />,\n order: 21,\n group: 'business',\n },\n\n // Marketplace\n {\n id: 'healthybowl-marketplace',\n label: t('healthybowl.nav.marketplace', 'Marketplace'),\n path: joinPath(basePath, 'marketplace'),\n icon: <ShoppingCart size={20} />,\n order: 22,\n group: 'business',\n },\n\n // Co-operative / FPO aggregation (BOFF-6023)\n {\n id: 'healthybowl-coop',\n label: t('healthybowl.nav.coop', 'Co-operative'),\n path: joinPath(basePath, 'coop'),\n icon: <Users2 size={20} />,\n order: 22.5,\n group: 'business',\n },\n\n // Financial\n {\n id: 'healthybowl-financial',\n label: t('healthybowl.nav.financial', 'Financial'),\n path: joinPath(basePath, 'financial'),\n icon: <DollarSign size={20} />,\n order: 23,\n group: 'business',\n },\n\n // Financier portfolio (B2B2C bridge)\n {\n id: 'healthybowl-financier',\n label: t('healthybowl.nav.financier', 'Financier'),\n path: joinPath(basePath, 'financier'),\n icon: <Banknote size={20} />,\n order: 24,\n group: 'business',\n },\n\n // Compliance\n {\n id: 'healthybowl-compliance',\n label: t('healthybowl.nav.compliance', 'Compliance'),\n path: joinPath(basePath, 'compliance'),\n icon: <ShieldCheck size={20} />,\n order: 30,\n group: 'compliance',\n },\n\n // Traceability\n {\n id: 'healthybowl-traceability',\n label: t('healthybowl.nav.traceability', 'Traceability'),\n path: joinPath(basePath, 'traceability'),\n icon: <ScanLine size={20} />,\n order: 31,\n group: 'compliance',\n },\n\n // Sustainability — Carbon & Climate (BOFF-2896)\n {\n id: 'healthybowl-sustainability',\n label: t('healthybowl.nav.sustainability', 'Sustainability'),\n path: joinPath(basePath, 'sustainability'),\n icon: <Leaf size={20} />,\n order: 32,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-carbon',\n label: t('healthybowl.nav.sustainabilityCarbon', 'Carbon & GHG'),\n path: joinPath(basePath, 'sustainability/carbon'),\n icon: <Factory size={20} />,\n order: 32.1,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-soil',\n label: t('healthybowl.nav.sustainabilitySoil', 'Soil Carbon'),\n path: joinPath(basePath, 'sustainability/soil-carbon'),\n icon: <Sprout size={20} />,\n order: 32.2,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-credits',\n label: t('healthybowl.nav.sustainabilityCredits', 'Carbon Credits'),\n path: joinPath(basePath, 'sustainability/credits'),\n icon: <Award size={20} />,\n order: 32.3,\n group: 'compliance',\n },\n {\n id: 'healthybowl-sustainability-eudr',\n label: t('healthybowl.nav.sustainabilityEudr', 'EUDR Due-Diligence'),\n path: joinPath(basePath, 'sustainability/eudr'),\n icon: <Globe size={20} />,\n order: 32.4,\n group: 'compliance',\n },\n\n // Government Schemes\n {\n id: 'healthybowl-schemes',\n label: t('healthybowl.nav.governmentSchemes', 'Gov. Schemes'),\n path: joinPath(basePath, 'government-schemes'),\n icon: <Landmark size={20} />,\n order: 40,\n group: 'support',\n },\n\n // Network\n {\n id: 'healthybowl-network',\n label: t('healthybowl.nav.network', 'Network'),\n path: joinPath(basePath, 'network'),\n icon: <Users size={20} />,\n order: 41,\n group: 'support',\n },\n\n // Analytics\n {\n id: 'healthybowl-analytics',\n label: t('healthybowl.nav.analytics', 'Analytics'),\n path: joinPath(basePath, 'analytics'),\n icon: <BarChart3 size={20} />,\n order: 42,\n group: 'support',\n },\n\n // My Advisors (UC-16 — farmer side)\n {\n id: 'healthybowl-advisors',\n label: t('healthybowl.nav.advisors', 'My Advisors'),\n path: joinPath(basePath, 'advisors'),\n icon: <UserCheck size={20} />,\n order: 43,\n group: 'support',\n },\n\n // Consultant portfolio (UC-16 — consultant side)\n {\n id: 'healthybowl-consultant',\n label: t('healthybowl.nav.consultant', 'Consultant'),\n path: joinPath(basePath, 'consultant'),\n icon: <Stethoscope size={20} />,\n order: 44,\n group: 'support',\n },\n ];\n\n // All sections are reachable. Marketplace (UC-08), Network (UC-12) and\n // Traceability (UC-11) render real read data + their real create flows\n // (createMarketplaceProduct / createCommunityPost / createTraceBatch); the\n // few genuinely-unbacked actions (checkout, booking, QR resolution) show\n // honest \"not available yet\" states in-page rather than hiding the section.\n // The operational carbon kill switch hides only Sustainability items;\n // Compliance and Traceability remain available.\n const navItems = filterHealthyBowlNavItemsForCarbon(allNavItems, carbonEnabled);\n const cleanup = registerNavItems(navItems);\n return cleanup;\n }, [registerNavItems, basePath, carbonEnabled, t]);\n\n // Register footer items\n useEffect(() => {\n if (!registerFooterItems) return;\n\n const footerItems = [\n {\n id: 'healthybowl-status',\n label: t('healthybowl.footer.ready', 'HealthyBowl Ready'),\n type: 'status' as const,\n order: 10,\n section: 'left' as const,\n },\n ];\n\n const cleanup = registerFooterItems(footerItems);\n return cleanup;\n }, [registerFooterItems, t]);\n\n return (\n <HealthyBowlProvider {...props}>\n {/* Logical CSS utilities flip an icon's *position* under RTL, but not its glyph. Navigational\n arrows/chevrons must also point the other way, so mirror the horizontal ones. Vertical\n chevrons (up/down, e.g. accordions) are unaffected by scaleX. Scoped to [dir=rtl] so it is\n inert in LTR. See BOFF-6119. */}\n <style>{RTL_ICON_MIRROR_CSS}</style>\n <ErrorBoundary>\n <ConfirmProvider>\n <OfflineSyncProvider>\n <HealthyBowlRoutes />\n </OfflineSyncProvider>\n </ConfirmProvider>\n </ErrorBoundary>\n </HealthyBowlProvider>\n );\n};\n\nexport const HealthyBowlRoot: FC<HealthyBowlRootProps> = (props) => (\n <FeatureFlagProvider\n key={props.workspaceId ?? 'no-workspace'}\n workspaceId={props.workspaceId ?? null}\n gateway=\"global\"\n flagKeys={HEALTHYBOWL_CARBON_FEATURE_FLAG_KEYS}\n defaultEnabled={true}\n >\n <HealthyBowlRootContent {...props} />\n </FeatureFlagProvider>\n);\n"],"mappings":";;;;;;;;;;;;;AA0EA,IAAM,oBAAc,IAAI,IAAY,CAAC,CAAC,GAKhC,IAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,EACG,KAAK,MAAM,eAAe,GAAG,EAC7B,KAAK,GAAG,EACR,OAAO,wBAAwB,GAE5B,IAA8B,IAAI,IAAI;CAC1C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,EAAmC,GAAqB,GAAmC;CACzG,OAAO,IAAgB,IAAW,EAAS,QAAQ,MAAS,CAAC,EAA4B,IAA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rC,MAAM,kBAAC,GAAD,EAAa,MAAM,GAAK,CAAA;IAC9B,OAAO;IACP,OAAO;GACT;EAUkD,GAAa,CAChC,CAC1B;CACT,GAAG;EAAC;EAAkB;EAAU;EAAe;CAAC,CAAC,GAGjD,QAAgB;EACT,OAaL,OADgB,EAAoB,CATlC;GACE,IAAI;GACJ,OAAO,EAAE,4BAA4B,mBAAmB;GACxD,MAAM;GACN,OAAO;GACP,SAAS;EACX,CAGkC,CAC7B;CACT,GAAG,CAAC,GAAqB,CAAC,CAAC,GAGzB,kBAAC,GAAD;EAAqB,GAAI;YAAzB,CAKE,kBAAC,SAAD,EAAA,UAAQ,EAA2B,CAAA,GACnC,kBAAC,GAAD,EAAA,UACE,kBAAC,GAAD,EAAA,UACE,kBAAC,GAAD,EAAA,UACE,kBAAC,GAAD,CAAoB,CAAA,EACD,CAAA,EACN,CAAA,EACJ,CAAA,CACI;;AAEzB,GAEa,KAA6C,MACxD,kBAAC,GAAD;CAEE,aAAa,EAAM,eAAe;CAClC,SAAQ;CACR,UAAU;CACV,gBAAgB;WAEhB,kBAAC,GAAD,EAAwB,GAAI,EAAQ,CAAA;AACjB,GAPd,EAAM,eAAe,cAOP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HBEntityImages.js","names":[],"sources":["../../../src/healthybowl/components/HBEntityImages.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, type FC } from 'react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient } from '@apollo/client/react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { ImagePlus, Loader2, X } from 'lucide-react';\nimport { cn } from '../utils/helpers';\n\n/**\n * Reuse-first entity images. HealthyBowl owns the image *set* (a `String[]` of\n * file ids persisted on each entity's `imageIds`); the shared fe-libs storage\n * flow (`useSaveToFiles` → wspace-files-svc) handles the real upload and the\n * `getFileDownloadUrl` query resolves presigned thumbnail URLs for display.\n * We never stand up a parallel blob store. This mirrors `HBEntityTags` and the\n * proven `ComplianceDocumentsPage` upload/download pattern.\n *\n * Controlled component: the parent holds `imageIds` (sent to create/update\n * mutations) and `onChange` updates it. Thumbnails are resolved lazily and\n * cached per file id so a re-render (or a fresh array reference) doesn't\n * re-fetch every URL.\n */\n\n// Resolve a presigned download URL for a real uploaded file (wspace-files-svc).\nconst GET_FILE_DOWNLOAD_URL = gql`\n query HealthyBowlImageDownloadUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\n/** Entity folder segment — uploads land under `/HealthyBowl/<Entity>`. */\nexport type HBImageEntity = 'Farm' | 'Field' | 'Crop' | 'Animal';\n\ninterface HBEntityImagesProps {\n /** Currently-stored file ids (the entity's `imageIds`). */\n imageIds: string[];\n /** Called with the next id list after an upload or removal. */\n onChange: (ids: string[]) => void;\n /** The entity these images belong to — drives the storage folder path. */\n entity: HBImageEntity;\n /** Render thumbnails only (no upload/remove) — for read-only detail views. */\n readOnly?: boolean;\n /** Maximum number of images. Defaults to 8. */\n max?: number;\n className?: string;\n}\n\nexport const HBEntityImages: FC<HBEntityImagesProps> = ({\n imageIds,\n onChange,\n entity,\n readOnly,\n max = 8,\n className,\n}) => {\n const client = useApolloClient();\n const { save: saveToFiles, isPending: uploading } = useSaveToFiles();\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n // Resolved presigned URLs keyed by file id. A null value means \"resolution\n // failed\" (so we render a fallback tile instead of retrying forever).\n const [urls, setUrls] = useState<Record<string, string | null>>({});\n const [uploadError, setUploadError] = useState<string | null>(null);\n\n // Lazily resolve a presigned URL for every id we haven't seen yet. The effect\n // is keyed on the id-set string so a fresh array reference doesn't re-run it.\n const idsKey = imageIds.join('|');\n useEffect(() => {\n let cancelled = false;\n const missing = imageIds.filter((id) => !(id in urls));\n if (missing.length === 0) return undefined;\n void Promise.all(\n missing.map(async (id) => {\n try {\n const res = await client.query<{ getFileDownloadUrl: string | null }>({\n query: GET_FILE_DOWNLOAD_URL,\n variables: { id },\n fetchPolicy: 'network-only',\n });\n return [id, res.data?.getFileDownloadUrl ?? null] as const;\n } catch {\n return [id, null] as const;\n }\n })\n ).then((entries) => {\n if (cancelled) return;\n setUrls((prev) => {\n const next = { ...prev };\n for (const [id, url] of entries) next[id] = url;\n return next;\n });\n });\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on idsKey to avoid array-identity churn\n }, [idsKey, client]);\n\n const handleFilesSelected = useCallback(\n async (e: React.ChangeEvent<HTMLInputElement>) => {\n const files = Array.from(e.target.files ?? []);\n if (fileInputRef.current) fileInputRef.current.value = '';\n if (files.length === 0) return;\n setUploadError(null);\n const remaining = Math.max(0, max - imageIds.length);\n const toUpload = files.slice(0, remaining);\n const uploadedIds: string[] = [];\n try {\n for (const file of toUpload) {\n const saved = await saveToFiles({\n source: {\n kind: 'blob',\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n getBlob: async () => ({\n blob: file,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n }),\n },\n folderPath: `/HealthyBowl/${entity}`,\n });\n uploadedIds.push(saved.id);\n }\n } catch (err) {\n setUploadError(err instanceof Error ? err.message : 'Could not upload the image.');\n }\n if (uploadedIds.length > 0) onChange([...imageIds, ...uploadedIds]);\n },\n [saveToFiles, entity, imageIds, max, onChange]\n );\n\n const handleRemove = useCallback((id: string) => onChange(imageIds.filter((x) => x !== id)), [imageIds, onChange]);\n\n if (readOnly) {\n if (imageIds.length === 0) return null;\n return (\n <div className={cn('flex flex-wrap gap-2', className)}>\n {imageIds.map((id) => (\n <Thumbnail key={id} url={urls[id]} />\n ))}\n </div>\n );\n }\n\n const atMax = imageIds.length >= max;\n\n return (\n <div className={cn('space-y-2', className)}>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\"image/*\"\n multiple\n className=\"hidden\"\n onChange={handleFilesSelected}\n />\n <div className=\"flex flex-wrap gap-2\">\n {imageIds.map((id) => (\n <div key={id} className=\"group relative\">\n <Thumbnail url={urls[id]} />\n <button\n type=\"button\"\n onClick={() => handleRemove(id)}\n aria-label=\"Remove image\"\n className=\"absolute -end-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-border-subtle bg-bg-surface text-text-secondary shadow-sm hover:text-status-error-text\"\n >\n <X className=\"h-3 w-3\" />\n </button>\n </div>\n ))}\n {!atMax && (\n <button\n type=\"button\"\n onClick={() => fileInputRef.current?.click()}\n disabled={uploading}\n className=\"flex h-16 w-16 flex-col items-center justify-center gap-1 rounded-md border border-dashed border-border-subtle bg-bg-surface text-text-secondary hover:bg-bg-sunken/50 disabled:opacity-60\"\n >\n {uploading ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : <ImagePlus className=\"h-4 w-4\" />}\n <span className=\"text-[10px]\">{uploading ? 'Uploading…' : 'Add'}</span>\n </button>\n )}\n </div>\n <p className=\"text-xs text-text-secondary\">\n {atMax\n ? `Maximum of ${max} images reached.`\n : `Upload images (stored securely in your workspace Files). ${imageIds.length}/${max} added.`}\n </p>\n {uploadError && <p className=\"text-xs text-status-error-text\">{uploadError}</p>}\n </div>\n );\n};\n\n/** A single thumbnail tile. Shows the image, a loading shimmer, or a fallback. */\nconst Thumbnail: FC<{ url: string | null | undefined }> = ({ url }) => {\n if (url === undefined) {\n return <div className=\"h-16 w-16 animate-pulse rounded-md border border-border-subtle bg-bg-sunken\" />;\n }\n if (url === null) {\n return (\n <div className=\"flex h-16 w-16 items-center justify-center rounded-md border border-border-subtle bg-bg-sunken text-text-secondary\">\n <ImagePlus className=\"h-4 w-4\" />\n </div>\n );\n }\n return (\n <img\n src={url}\n alt=\"Entity\"\n className=\"h-16 w-16 rounded-md border border-border-subtle object-cover\"\n loading=\"lazy\"\n />\n );\n};\n"],"mappings":";;;;;;;;AAsBA,IAAM,IAAwB,CAAG;;;;GAuBpB,KAA2C,EACtD,aACA,aACA,WACA,aACA,SAAM,GACN,mBACI;CACJ,IAAM,IAAS,EAAgB,GACzB,EAAE,MAAM,GAAa,WAAW,MAAc,EAAe,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,kBAAC,QAAD;MAAM,WAAU;gBAAe,IAAY,eAAe;KAAY,CAAA,CAChE;MAEP;;GACL,kBAAC,KAAD;IAAG,WAAU;cACV,IACG,cAAc,EAAI,oBAClB,4DAA4D,EAAS,OAAO,GAAG,EAAI;GACtF,CAAA;GACF,KAAe,kBAAC,KAAD;IAAG,WAAU;cAAkC;GAAe,CAAA;EAC3E;;AAET,GAGM,KAAqD,EAAE,aACvD,MAAQ,KAAA,IACH,kBAAC,OAAD,EAAK,WAAU,8EAA+E,CAAA,IAEnG,MAAQ,OAER,kBAAC,OAAD;CAAK,WAAU;WACb,kBAAC,GAAD,EAAW,WAAU,UAAW,CAAA;AAC7B,CAAA,IAIP,kBAAC,OAAD;CACE,KAAK;CACL,KAAI;CACJ,WAAU;CACV,SAAQ;AACT,CAAA"}
|
|
1
|
+
{"version":3,"file":"HBEntityImages.js","names":[],"sources":["../../../src/healthybowl/components/HBEntityImages.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, type FC } from 'react';\nimport { gql } from '@apollo/client';\nimport { useApolloClient } from '@apollo/client/react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { ImagePlus, Loader2, X } from 'lucide-react';\nimport { cn } from '../utils/helpers';\n\n/**\n * Reuse-first entity images. HealthyBowl owns the image *set* (a `String[]` of\n * file ids persisted on each entity's `imageIds`); the shared fe-libs storage\n * flow (`useSaveToFiles` → wspace-files-svc) handles the real upload and the\n * `getFileDownloadUrl` query resolves presigned thumbnail URLs for display.\n * We never stand up a parallel blob store. This mirrors `HBEntityTags` and the\n * proven `ComplianceDocumentsPage` upload/download pattern.\n *\n * Controlled component: the parent holds `imageIds` (sent to create/update\n * mutations) and `onChange` updates it. Thumbnails are resolved lazily and\n * cached per file id so a re-render (or a fresh array reference) doesn't\n * re-fetch every URL.\n */\n\n// Resolve a presigned download URL for a real uploaded file (wspace-files-svc).\nconst GET_FILE_DOWNLOAD_URL = gql`\n query HealthyBowlImageDownloadUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\n/** Entity folder segment — uploads land under `/HealthyBowl/<Entity>`. */\nexport type HBImageEntity = 'Farm' | 'Field' | 'Crop' | 'Animal' | 'Inspection';\n\ninterface HBEntityImagesProps {\n /** Currently-stored file ids (the entity's `imageIds`). */\n imageIds: string[];\n /** Called with the next id list after an upload or removal. */\n onChange: (ids: string[]) => void;\n /** The entity these images belong to — drives the storage folder path. */\n entity: HBImageEntity;\n /** Render thumbnails only (no upload/remove) — for read-only detail views. */\n readOnly?: boolean;\n /** Maximum number of images. Defaults to 8. */\n max?: number;\n className?: string;\n}\n\nexport const HBEntityImages: FC<HBEntityImagesProps> = ({\n imageIds,\n onChange,\n entity,\n readOnly,\n max = 8,\n className,\n}) => {\n const client = useApolloClient();\n const { save: saveToFiles, isPending: uploading } = useSaveToFiles();\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n // Resolved presigned URLs keyed by file id. A null value means \"resolution\n // failed\" (so we render a fallback tile instead of retrying forever).\n const [urls, setUrls] = useState<Record<string, string | null>>({});\n const [uploadError, setUploadError] = useState<string | null>(null);\n\n // Lazily resolve a presigned URL for every id we haven't seen yet. The effect\n // is keyed on the id-set string so a fresh array reference doesn't re-run it.\n const idsKey = imageIds.join('|');\n useEffect(() => {\n let cancelled = false;\n const missing = imageIds.filter((id) => !(id in urls));\n if (missing.length === 0) return undefined;\n void Promise.all(\n missing.map(async (id) => {\n try {\n const res = await client.query<{ getFileDownloadUrl: string | null }>({\n query: GET_FILE_DOWNLOAD_URL,\n variables: { id },\n fetchPolicy: 'network-only',\n });\n return [id, res.data?.getFileDownloadUrl ?? null] as const;\n } catch {\n return [id, null] as const;\n }\n })\n ).then((entries) => {\n if (cancelled) return;\n setUrls((prev) => {\n const next = { ...prev };\n for (const [id, url] of entries) next[id] = url;\n return next;\n });\n });\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on idsKey to avoid array-identity churn\n }, [idsKey, client]);\n\n const handleFilesSelected = useCallback(\n async (e: React.ChangeEvent<HTMLInputElement>) => {\n const files = Array.from(e.target.files ?? []);\n if (fileInputRef.current) fileInputRef.current.value = '';\n if (files.length === 0) return;\n setUploadError(null);\n const remaining = Math.max(0, max - imageIds.length);\n const toUpload = files.slice(0, remaining);\n const uploadedIds: string[] = [];\n try {\n for (const file of toUpload) {\n const saved = await saveToFiles({\n source: {\n kind: 'blob',\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n getBlob: async () => ({\n blob: file,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n }),\n },\n folderPath: `/HealthyBowl/${entity}`,\n });\n uploadedIds.push(saved.id);\n }\n } catch (err) {\n setUploadError(err instanceof Error ? err.message : 'Could not upload the image.');\n }\n if (uploadedIds.length > 0) onChange([...imageIds, ...uploadedIds]);\n },\n [saveToFiles, entity, imageIds, max, onChange]\n );\n\n const handleRemove = useCallback((id: string) => onChange(imageIds.filter((x) => x !== id)), [imageIds, onChange]);\n\n if (readOnly) {\n if (imageIds.length === 0) return null;\n return (\n <div className={cn('flex flex-wrap gap-2', className)}>\n {imageIds.map((id) => (\n <Thumbnail key={id} url={urls[id]} />\n ))}\n </div>\n );\n }\n\n const atMax = imageIds.length >= max;\n\n return (\n <div className={cn('space-y-2', className)}>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\"image/*\"\n multiple\n className=\"hidden\"\n onChange={handleFilesSelected}\n />\n <div className=\"flex flex-wrap gap-2\">\n {imageIds.map((id) => (\n <div key={id} className=\"group relative\">\n <Thumbnail url={urls[id]} />\n <button\n type=\"button\"\n onClick={() => handleRemove(id)}\n aria-label=\"Remove image\"\n className=\"absolute -end-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-border-subtle bg-bg-surface text-text-secondary shadow-sm hover:text-status-error-text\"\n >\n <X className=\"h-3 w-3\" />\n </button>\n </div>\n ))}\n {!atMax && (\n <button\n type=\"button\"\n onClick={() => fileInputRef.current?.click()}\n disabled={uploading}\n className=\"flex h-16 w-16 flex-col items-center justify-center gap-1 rounded-md border border-dashed border-border-subtle bg-bg-surface text-text-secondary hover:bg-bg-sunken/50 disabled:opacity-60\"\n >\n {uploading ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : <ImagePlus className=\"h-4 w-4\" />}\n <span className=\"text-[10px]\">{uploading ? 'Uploading…' : 'Add'}</span>\n </button>\n )}\n </div>\n <p className=\"text-xs text-text-secondary\">\n {atMax\n ? `Maximum of ${max} images reached.`\n : `Upload images (stored securely in your workspace Files). ${imageIds.length}/${max} added.`}\n </p>\n {uploadError && <p className=\"text-xs text-status-error-text\">{uploadError}</p>}\n </div>\n );\n};\n\n/** A single thumbnail tile. Shows the image, a loading shimmer, or a fallback. */\nconst Thumbnail: FC<{ url: string | null | undefined }> = ({ url }) => {\n if (url === undefined) {\n return <div className=\"h-16 w-16 animate-pulse rounded-md border border-border-subtle bg-bg-sunken\" />;\n }\n if (url === null) {\n return (\n <div className=\"flex h-16 w-16 items-center justify-center rounded-md border border-border-subtle bg-bg-sunken text-text-secondary\">\n <ImagePlus className=\"h-4 w-4\" />\n </div>\n );\n }\n return (\n <img\n src={url}\n alt=\"Entity\"\n className=\"h-16 w-16 rounded-md border border-border-subtle object-cover\"\n loading=\"lazy\"\n />\n );\n};\n"],"mappings":";;;;;;;;AAsBA,IAAM,IAAwB,CAAG;;;;GAuBpB,KAA2C,EACtD,aACA,aACA,WACA,aACA,SAAM,GACN,mBACI;CACJ,IAAM,IAAS,EAAgB,GACzB,EAAE,MAAM,GAAa,WAAW,MAAc,EAAe,GAC7D,IAAe,EAAyB,IAAI,GAI5C,CAAC,GAAM,KAAW,EAAwC,CAAC,CAAC,GAC5D,CAAC,GAAa,KAAkB,EAAwB,IAAI;CAKlE,QAAgB;EACd,IAAI,IAAY,IACV,IAAU,EAAS,QAAQ,MAAO,EAAE,KAAM,EAAK;EACjD,MAAQ,WAAW,GAsBvB,OArBA,QAAa,IACX,EAAQ,IAAI,O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KAAqD,EAAE,aACvD,MAAQ,KAAA,IACH,kBAAC,OAAD,EAAK,WAAU,8EAA+E,CAAA,IAEnG,MAAQ,OAER,kBAAC,OAAD;CAAK,WAAU;WACb,kBAAC,GAAD,EAAW,WAAU,UAAW,CAAA;AAC7B,CAAA,IAIP,kBAAC,OAAD;CACE,KAAK;CACL,KAAI;CACJ,WAAU;CACV,SAAQ;AACT,CAAA"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
|
|
2
|
+
import { useCallback as t, useEffect as n, useMemo as r, useState as i } from "react";
|
|
3
|
+
import { gql as a } from "@apollo/client";
|
|
4
|
+
import { useLazyQuery as o } from "@apollo/client/react";
|
|
5
|
+
//#region src/healthybowl/hooks/useTraceScanActivity.ts
|
|
6
|
+
var s = a`
|
|
7
|
+
query HealthyBowlTraceScanActivity($id: ID!, $context: ContextInput!) {
|
|
8
|
+
getHealthyBowlTraceScanActivity(id: $id, context: $context) {
|
|
9
|
+
total
|
|
10
|
+
events {
|
|
11
|
+
deviceType
|
|
12
|
+
timestamp
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
`, c = [
|
|
17
|
+
"mobile",
|
|
18
|
+
"tablet",
|
|
19
|
+
"desktop",
|
|
20
|
+
"unknown"
|
|
21
|
+
], l = (e) => c.includes(e);
|
|
22
|
+
function u(e) {
|
|
23
|
+
let t = {
|
|
24
|
+
mobile: 0,
|
|
25
|
+
tablet: 0,
|
|
26
|
+
desktop: 0,
|
|
27
|
+
unknown: 0
|
|
28
|
+
};
|
|
29
|
+
for (let n of e) {
|
|
30
|
+
let e = n.deviceType.trim().toLowerCase();
|
|
31
|
+
t[l(e) ? e : "unknown"] += 1;
|
|
32
|
+
}
|
|
33
|
+
return t;
|
|
34
|
+
}
|
|
35
|
+
function d(a) {
|
|
36
|
+
let { workspaceId: c } = e(), l = r(() => ({ workspaceId: c }), [c]), [u, d] = i(null), [f, p] = i(!1), [m, h] = i(!1), [g] = o(s, { fetchPolicy: "cache-and-network" }), _ = t(async (e) => (await g({ variables: {
|
|
37
|
+
id: e,
|
|
38
|
+
context: l
|
|
39
|
+
} })).data?.getHealthyBowlTraceScanActivity ?? null, [g, l]);
|
|
40
|
+
return n(() => {
|
|
41
|
+
if (!a || !c) {
|
|
42
|
+
d(null), h(!1), p(!1);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
let e = !1;
|
|
46
|
+
return p(!0), h(!1), _(a).then((t) => {
|
|
47
|
+
e || (d(t), h(t === null));
|
|
48
|
+
}).catch(() => {
|
|
49
|
+
e || (d(null), h(!0));
|
|
50
|
+
}).finally(() => {
|
|
51
|
+
e || p(!1);
|
|
52
|
+
}), () => {
|
|
53
|
+
e = !0;
|
|
54
|
+
};
|
|
55
|
+
}, [
|
|
56
|
+
a,
|
|
57
|
+
c,
|
|
58
|
+
_
|
|
59
|
+
]), {
|
|
60
|
+
activity: u,
|
|
61
|
+
loading: f,
|
|
62
|
+
failed: m
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
export { c as SCAN_DEVICE_TYPES, u as countByDevice, d as useTraceScanActivity };
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=useTraceScanActivity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useTraceScanActivity.js","names":[],"sources":["../../../src/healthybowl/hooks/useTraceScanActivity.ts"],"sourcesContent":["/**\n * Public-portal scan activity for one trace batch (BOFF-6177).\n *\n * `getHealthyBowlTraceScanActivity` is analytics-backed and keyed to a SINGLE batch, so this is\n * deliberately a per-selection read rather than a column on the batches table: rendering a scan\n * count per row would fan out one gateway round-trip per row.\n *\n * The document is hand-written `gql` — the same raw-gql escape hatch `useHealthyBowlCompliance`\n * and `useSuccessionPlanning` use — because this repo's `graphql/wspace.graphql` snapshot predates\n * the field and the generated hooks therefore don't cover it.\n *\n * @module healthybowl\n */\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { gql } from '@apollo/client';\nimport { useLazyQuery } from '@apollo/client/react';\n\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n/** A single scan of a batch's public trace page. `deviceType` is lowercase from the service. */\nexport interface TraceScanEvent {\n deviceType: string;\n timestamp: string;\n}\n\nexport interface TraceScanActivity {\n total: number;\n events: TraceScanEvent[];\n}\n\ninterface ScanActivityQueryData {\n getHealthyBowlTraceScanActivity: TraceScanActivity;\n}\n\nconst SCAN_ACTIVITY_QUERY = gql`\n query HealthyBowlTraceScanActivity($id: ID!, $context: ContextInput!) {\n getHealthyBowlTraceScanActivity(id: $id, context: $context) {\n total\n events {\n deviceType\n timestamp\n }\n }\n }\n`;\n\n/** Device buckets the service emits (`classifyScanDevice`), in the order we render them. */\nexport const SCAN_DEVICE_TYPES = ['mobile', 'tablet', 'desktop', 'unknown'] as const;\nexport type ScanDeviceType = (typeof SCAN_DEVICE_TYPES)[number];\n\nconst isKnownDevice = (value: string): value is ScanDeviceType =>\n (SCAN_DEVICE_TYPES as readonly string[]).includes(value);\n\n/** Count scans per device bucket, normalising the service's lowercase values. */\nexport function countByDevice(events: TraceScanEvent[]): Record<ScanDeviceType, number> {\n const counts: Record<ScanDeviceType, number> = { mobile: 0, tablet: 0, desktop: 0, unknown: 0 };\n for (const event of events) {\n const key = event.deviceType.trim().toLowerCase();\n counts[isKnownDevice(key) ? key : 'unknown'] += 1;\n }\n return counts;\n}\n\n/**\n * Loads scan activity for `batchId`, or nothing when it is null (an unpublished batch has no\n * public page, so it cannot have been scanned — we don't ask).\n *\n * The service defaults the window to the last 90 days when no dates are supplied, which is what\n * the caller must say when it labels the total.\n */\nexport function useTraceScanActivity(batchId: string | null) {\n const { workspaceId } = useHealthyBowl();\n const context = useMemo(() => ({ workspaceId }), [workspaceId]);\n\n const [activity, setActivity] = useState<TraceScanActivity | null>(null);\n const [loading, setLoading] = useState(false);\n const [failed, setFailed] = useState(false);\n\n const [runQuery] = useLazyQuery<ScanActivityQueryData>(SCAN_ACTIVITY_QUERY, {\n fetchPolicy: 'cache-and-network',\n });\n\n const load = useCallback(\n async (id: string): Promise<TraceScanActivity | null> => {\n const res = await runQuery({ variables: { id, context } });\n return res.data?.getHealthyBowlTraceScanActivity ?? null;\n },\n [runQuery, context]\n );\n\n useEffect(() => {\n if (!batchId || !workspaceId) {\n setActivity(null);\n setFailed(false);\n setLoading(false);\n return;\n }\n let cancelled = false;\n setLoading(true);\n setFailed(false);\n load(batchId)\n .then((result) => {\n if (cancelled) return;\n setActivity(result);\n // A null payload is a failed read, not \"zero scans\" — the caller must not print 0 for it.\n setFailed(result === null);\n })\n .catch(() => {\n if (cancelled) return;\n setActivity(null);\n setFailed(true);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [batchId, workspaceId, load]);\n\n return { activity, loading, failed };\n}\n"],"mappings":";;;;;AAkCA,IAAM,IAAsB,CAAG;;;;;;;;;;GAalB,IAAoB;CAAC;CAAU;CAAU;CAAW;AAAS,GAGpE,KAAiB,MACpB,EAAwC,SAAS,CAAK;AAGzD,SAAgB,EAAc,GAA0D;CACtF,IAAM,IAAyC;EAAE,QAAQ;EAAG,QAAQ;EAAG,SAAS;EAAG,SAAS;CAAE;CAC9F,KAAK,IAAM,KAAS,GAAQ;EAC1B,IAAM,IAAM,EAAM,WAAW,KAAK,EAAE,YAAY;EAChD,EAAO,EAAc,CAAG,IAAI,IAAM,cAAc;CAClD;CACA,OAAO;AACT;AASA,SAAgB,EAAqB,GAAwB;CAC3D,IAAM,EAAE,mBAAgB,EAAe,GACjC,IAAU,SAAe,EAAE,eAAY,IAAI,CAAC,CAAW,CAAC,GAExD,CAAC,GAAU,KAAe,EAAmC,IAAI,GACjE,CAAC,GAAS,KAAc,EAAS,EAAK,GACtC,CAAC,GAAQ,KAAa,EAAS,EAAK,GAEpC,CAAC,KAAY,EAAoC,GAAqB,EAC1E,aAAa,oBACf,CAAC,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