InventoryPage.tsx 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199
  1. import { useState, useMemo, useEffect, useRef, useCallback, type ReactNode } from 'react';
  2. import { useSearchParams } from 'react-router-dom';
  3. import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import {
  6. Plus, Loader2, Trash2, Archive, RotateCcw, Edit2, Package,
  7. Search, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight,
  8. TrendingDown, Layers, Printer, AlertTriangle, X, Clock, LayoutGrid, TableProperties, Columns,
  9. ArrowUp, ArrowDown, ArrowUpDown, Group, ChevronDown, Check, RefreshCw, TrendingUp, Lock, Copy, Eraser, MapPin,
  10. Upload, Download, Store,
  11. } from 'lucide-react';
  12. import { ForecastPanel } from '../components/ForecastPanel';
  13. import { api, spoolbuddyApi, ApiError } from '../api/client';
  14. import type { InventorySpool, SpoolCatalogEntry, LocationHASensorReading } from '../api/client';
  15. import { Button } from '../components/Button';
  16. import { FilamentSwatch } from '../components/FilamentSwatch';
  17. import { describeHASensorReading, iconForHASensor } from '../utils/haSensorDisplay';
  18. import { buildFilamentBackground } from '../components/filamentSwatchHelpers';
  19. import {SpoolFormModal, type SpoolFormMode} from '../components/SpoolFormModal';
  20. import { ConfirmModal } from '../components/ConfirmModal';
  21. import { ColumnConfigModal, type ColumnConfig } from '../components/ColumnConfigModal';
  22. import { LabelTemplatePickerModal } from '../components/LabelTemplatePickerModal';
  23. import { SpoolCsvImportModal } from '../components/SpoolCsvImportModal';
  24. import { LocationsModal } from '../components/LocationsModal';
  25. import { SuppliersModal } from '../components/SuppliersModal';
  26. import { BulkEditSpoolsModal } from '../components/BulkEditSpoolsModal';
  27. import { useToast } from '../contexts/ToastContext';
  28. import { useAuth } from '../contexts/AuthContext';
  29. import { colorSortKey, resolveSpoolColorName } from '../utils/colors';
  30. import { useColorCatalogVersion } from '../hooks/useColorCatalogVersion';
  31. import { getCurrencySymbol } from '../utils/currency';
  32. import { formatDateInput, parseUTCDate, type DateFormat } from '../utils/date';
  33. import { formatSlotLabel } from '../utils/amsHelpers';
  34. import { filterSpoolsByQuery } from '../utils/inventorySearch';
  35. import {
  36. inventoryLocationsQueryKey,
  37. invalidateSpoolAndLocationQueries,
  38. } from '../utils/inventoryQueries';
  39. import { aggregateGroupSpool } from '../utils/inventoryGrouping';
  40. import {
  41. locationSensorReadingAlertStatus,
  42. locationSensorValueColorClass,
  43. useLocationSensorColorPrefs,
  44. type LocationSensorAlertColor,
  45. } from '../utils/locationSensorDefaults';
  46. type ArchiveFilter = 'active' | 'archived';
  47. type UsageFilter = 'all' | 'used' | 'new' | 'lowstock';
  48. type ViewMode = 'table' | 'cards' | 'forecast';
  49. type SortDirection = 'asc' | 'desc';
  50. type SortState = { column: string; direction: SortDirection } | null;
  51. type DisplayItem =
  52. | { type: 'single'; spool: InventorySpool }
  53. | { type: 'group'; key: string; spools: InventorySpool[]; representative: InventorySpool };
  54. function dedupeAndSort(values: Array<string | null | undefined>): string[] {
  55. const set = new Set<string>();
  56. for (const v of values) {
  57. if (typeof v === 'string') {
  58. const trimmed = v.trim();
  59. if (trimmed) set.add(trimmed);
  60. }
  61. }
  62. return Array.from(set).sort((a, b) => a.localeCompare(b));
  63. }
  64. function spoolGroupKey(s: InventorySpool): string {
  65. // Include extra_colors + effect_type so the "Group similar" toggle does
  66. // not collapse two spools that share the base colour but differ on
  67. // gradient stops or visual effect (#1154).
  68. return `${s.material}|${s.subtype || ''}|${s.brand || ''}|${s.color_name || ''}|${s.rgba || ''}|${s.extra_colors || ''}|${s.effect_type || ''}|${s.label_weight}`;
  69. }
  70. // Column definitions for the inventory table
  71. const COLUMN_CONFIG_KEY = 'bambuddy-inventory-columns';
  72. const DEFAULT_COLUMNS: ColumnConfig[] = [
  73. { id: 'id', label: '#', visible: true },
  74. { id: 'added_time', label: 'Added', visible: true },
  75. { id: 'encode_time', label: 'Encoded', visible: false },
  76. { id: 'last_used_time', label: 'Last Used', visible: false },
  77. { id: 'rgba', label: 'Color', visible: true },
  78. { id: 'material', label: 'Material', visible: true },
  79. { id: 'subtype', label: 'Subtype', visible: true },
  80. { id: 'color_name', label: 'Color Name', visible: false },
  81. { id: 'brand', label: 'Brand', visible: true },
  82. { id: 'slicer_filament', label: 'Slicer Filament', visible: false },
  83. { id: 'location', label: 'Location', visible: true },
  84. { id: 'storage_location', label: 'Storage Location', visible: false },
  85. { id: 'temperature', label: 'Temperature', visible: false },
  86. { id: 'humidity', label: 'Humidity', visible: false },
  87. { id: 'battery', label: 'Battery', visible: false },
  88. { id: 'label_weight', label: 'Label', visible: true },
  89. { id: 'net', label: 'Net', visible: true },
  90. { id: 'gross', label: 'Gross', visible: false },
  91. { id: 'added_full', label: 'Full', visible: false },
  92. { id: 'used', label: 'Used', visible: false },
  93. { id: 'printed_total', label: 'Printed Total', visible: false },
  94. { id: 'printed_since_weight', label: 'Printed Since Weight', visible: false },
  95. { id: 'note', label: 'Note', visible: false },
  96. { id: 'suppliers', label: 'Suppliers', visible: false },
  97. { id: 'pa_k', label: 'PA(K)', visible: true },
  98. { id: 'tag_id', label: 'Tag ID', visible: false },
  99. { id: 'data_origin', label: 'Data Origin', visible: false },
  100. { id: 'tag_type', label: 'Linked Tag Type', visible: false },
  101. { id: 'stock', label: 'Stock', visible: false },
  102. { id: 'remaining', label: 'Remaining', visible: true },
  103. { id: 'spool_name', label: 'Spool', visible: false },
  104. { id: 'cost_per_kg', label: 'Cost/kg', visible: false },
  105. { id: 'weight_check', label: 'Weight Check', visible: false },
  106. ];
  107. function loadColumnConfig(): ColumnConfig[] {
  108. try {
  109. const stored = localStorage.getItem(COLUMN_CONFIG_KEY);
  110. if (stored) {
  111. const parsed = JSON.parse(stored) as ColumnConfig[];
  112. const defaultIds = new Set(DEFAULT_COLUMNS.map((c) => c.id));
  113. const storedIds = new Set(parsed.map((c) => c.id));
  114. // Keep stored columns that still exist in defaults
  115. const validStored = parsed.filter((c) => defaultIds.has(c.id));
  116. const merged = [...validStored];
  117. for (const col of DEFAULT_COLUMNS) {
  118. if (storedIds.has(col.id)) continue;
  119. const defaultIndex = DEFAULT_COLUMNS.indexOf(col);
  120. let insertAt = merged.length;
  121. for (let i = defaultIndex - 1; i >= 0; i--) {
  122. const idx = merged.findIndex((c) => c.id === DEFAULT_COLUMNS[i].id);
  123. if (idx !== -1) {
  124. insertAt = idx + 1;
  125. break;
  126. }
  127. }
  128. merged.splice(insertAt, 0, col);
  129. }
  130. return merged;
  131. }
  132. } catch {
  133. // Ignore errors
  134. }
  135. return DEFAULT_COLUMNS.map((c) => ({ ...c }));
  136. }
  137. function saveColumnConfig(config: ColumnConfig[]) {
  138. try {
  139. localStorage.setItem(COLUMN_CONFIG_KEY, JSON.stringify(config));
  140. } catch {
  141. // Ignore errors
  142. }
  143. }
  144. function formatWeight(g: number, useKg = false): string {
  145. if (useKg && g >= 1000) return `${(g / 1000).toFixed(1)}kg`;
  146. return `${Math.round(g)}g`;
  147. }
  148. // Material color mapping for pills
  149. const MATERIAL_COLORS: Record<string, string> = {
  150. PLA: 'bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400',
  151. ABS: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400',
  152. PETG: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  153. TPU: 'bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400',
  154. ASA: 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400',
  155. PA: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  156. PC: 'bg-cyan-100 dark:bg-cyan-500/20 text-cyan-700 dark:text-cyan-400',
  157. PET: 'bg-sky-100 dark:bg-sky-500/20 text-sky-700 dark:text-sky-400',
  158. };
  159. type TFn = (key: string, opts?: Record<string, unknown>) => string;
  160. function formatInventoryDate(dateStr: string | null, dateFormat: DateFormat = 'system'): string {
  161. if (!dateStr) return '-';
  162. const date = parseUTCDate(dateStr);
  163. if (!date) return '-';
  164. return formatDateInput(date, dateFormat);
  165. }
  166. // Slim shape for the LOCATION column — only the fields actually rendered.
  167. // Sourced from either local SpoolAssignment (lokal) or SpoolmanSlotAssignment
  168. // (Spoolman mode), so we can't reuse SpoolAssignment without dummy values.
  169. type LocationDisplay = {
  170. printer_id: number;
  171. printer_name: string | null;
  172. ams_id: number;
  173. tray_id: number;
  174. ams_label: string | null;
  175. };
  176. type CellCtx = {
  177. spool: InventorySpool;
  178. remaining: number;
  179. pct: number;
  180. assignmentMap: Record<number, LocationDisplay>;
  181. catalogMap: Record<number, SpoolCatalogEntry>;
  182. locationReadingsMap: Record<number, LocationHASensorReading[]>;
  183. currencySymbol: string;
  184. dateFormat: DateFormat;
  185. t: TFn;
  186. onSyncWeight?: (spool: InventorySpool) => void;
  187. colorizeLocationSensors: boolean;
  188. locationSensorAboveColor: LocationSensorAlertColor;
  189. locationSensorBelowColor: LocationSensorAlertColor;
  190. locationSensorOptimalColor: LocationSensorAlertColor;
  191. };
  192. // Column header labels (25 columns — matching SpoolBuddy exactly)
  193. const columnHeaders: Record<string, (t: TFn) => string> = {
  194. id: () => '#',
  195. added_time: () => 'Added',
  196. encode_time: () => 'Encoded',
  197. last_used_time: () => 'Last Used',
  198. rgba: (t) => t('inventory.color'),
  199. material: (t) => t('inventory.material'),
  200. subtype: (t) => t('inventory.subtype'),
  201. color_name: (t) => t('inventory.colorName'),
  202. brand: (t) => t('inventory.brand'),
  203. slicer_filament: (t) => t('inventory.slicerFilament'),
  204. location: () => 'Location',
  205. storage_location: (t) => t('inventory.storageLocation'),
  206. temperature: (t) => t('inventory.temperature'),
  207. humidity: (t) => t('inventory.humidity'),
  208. battery: (t) => t('inventory.battery'),
  209. label_weight: (t) => t('inventory.labelWeight'),
  210. net: (t) => t('inventory.net'),
  211. gross: () => 'Gross',
  212. added_full: () => 'Full',
  213. used: (t) => t('inventory.weightUsed'),
  214. printed_total: () => 'Printed Total',
  215. printed_since_weight: () => 'Printed Since Weight',
  216. note: (t) => t('inventory.note'),
  217. suppliers: (t) => t('inventory.suppliers.label'),
  218. pa_k: () => 'PA(K)',
  219. tag_id: () => 'Tag ID',
  220. data_origin: () => 'Data Origin',
  221. tag_type: () => 'Linked Tag Type',
  222. stock: (t) => t('inventory.stock'),
  223. remaining: (t) => t('inventory.remaining'),
  224. spool_name: (t) => t('inventory.spoolName'),
  225. cost_per_kg: (t) => t('inventory.costPerKg'),
  226. weight_check: (t) => t('inventory.weightCheck'),
  227. };
  228. // Column cell renderers (25 columns — matching SpoolBuddy exactly)
  229. const columnCells: Record<string, (ctx: CellCtx) => ReactNode> = {
  230. id: ({ spool }) => (
  231. <span className="text-sm font-medium text-white">{spool.id}</span>
  232. ),
  233. added_time: ({ spool, dateFormat }) => (
  234. <span className="text-sm text-bambu-gray">{formatInventoryDate(spool.created_at, dateFormat)}</span>
  235. ),
  236. encode_time: ({ spool, dateFormat }) => (
  237. <span className="text-sm text-bambu-gray">{formatInventoryDate(spool.encode_time, dateFormat)}</span>
  238. ),
  239. last_used_time: ({ spool, dateFormat }) => (
  240. <span className="text-sm text-bambu-gray">{spool.last_used ? formatInventoryDate(spool.last_used, dateFormat) : 'Never'}</span>
  241. ),
  242. rgba: ({ spool }) => (
  243. <div className="flex items-center justify-center">
  244. <FilamentSwatch
  245. rgba={spool.rgba}
  246. extraColors={spool.extra_colors}
  247. effectType={spool.effect_type}
  248. effectSize="table"
  249. subtype={spool.subtype}
  250. />
  251. </div>
  252. ),
  253. material: ({ spool }) => (
  254. <span className="text-sm text-white">{spool.material}</span>
  255. ),
  256. subtype: ({ spool }) => (
  257. <span className="text-sm text-bambu-gray">{spool.subtype || '-'}</span>
  258. ),
  259. color_name: ({ spool }) => (
  260. <span className="text-sm text-bambu-gray">{resolveSpoolColorName(spool.color_name, spool.rgba, spool.color_name_is_synthesized) || '-'}</span>
  261. ),
  262. brand: ({ spool }) => (
  263. <span className="text-sm text-bambu-gray">{spool.brand || '-'}</span>
  264. ),
  265. slicer_filament: ({ spool }) => (
  266. <span className="text-sm text-bambu-gray" title={spool.slicer_filament || undefined}>
  267. {spool.slicer_filament_name || spool.slicer_filament || '-'}
  268. </span>
  269. ),
  270. location: ({ spool, assignmentMap }) => {
  271. const assignment = assignmentMap[spool.id];
  272. if (!assignment) return <span className="text-sm text-bambu-gray">-</span>;
  273. const printerLabel = assignment.printer_name || `Printer ${assignment.printer_id}`;
  274. const isExternal = assignment.ams_id === 254 || assignment.ams_id === 255;
  275. const isHt = !isExternal && assignment.ams_id >= 128;
  276. const slotLabel = formatSlotLabel(assignment.ams_id, assignment.tray_id, isHt, isExternal);
  277. return (
  278. <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400">
  279. {printerLabel} {slotLabel}{assignment.ams_label ? ` (${assignment.ams_label})` : ''}
  280. </span>
  281. );
  282. },
  283. storage_location: ({ spool }) => {
  284. if (!spool.storage_location) return <span className="text-sm text-bambu-gray">-</span>;
  285. return (
  286. <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400">
  287. {spool.storage_location}
  288. </span>
  289. );
  290. },
  291. temperature: ({ spool, locationReadingsMap, t, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor }) => {
  292. const reading = spool.location_id
  293. ? locationReadingsMap[spool.location_id]?.find((r) => r.device_class === 'temperature')
  294. : undefined;
  295. if (!reading) return <span className="text-sm text-bambu-gray/50">-</span>;
  296. return (
  297. <span
  298. title={reading.name}
  299. className={`text-sm ${locationSensorCellColor(reading, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor)}`}
  300. >
  301. {describeLocationSensor(reading, t)}
  302. </span>
  303. );
  304. },
  305. humidity: ({ spool, locationReadingsMap, t, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor }) => {
  306. const reading = spool.location_id
  307. ? locationReadingsMap[spool.location_id]?.find((r) => r.device_class === 'humidity')
  308. : undefined;
  309. if (!reading) return <span className="text-sm text-bambu-gray/50">-</span>;
  310. return (
  311. <span
  312. title={reading.name}
  313. className={`text-sm ${locationSensorCellColor(reading, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor)}`}
  314. >
  315. {describeLocationSensor(reading, t)}
  316. </span>
  317. );
  318. },
  319. battery: ({ spool, locationReadingsMap, t, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor }) => {
  320. const reading = spool.location_id
  321. ? locationReadingsMap[spool.location_id]?.find((r) => r.device_class === 'battery')
  322. : undefined;
  323. if (!reading) return <span className="text-sm text-bambu-gray/50">-</span>;
  324. return (
  325. <span
  326. title={reading.name}
  327. className={`text-sm ${locationSensorCellColor(reading, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor)}`}
  328. >
  329. {describeLocationSensor(reading, t)}
  330. </span>
  331. );
  332. },
  333. label_weight: ({ spool }) => (
  334. <span className="text-sm text-white">{formatWeight(spool.label_weight)}</span>
  335. ),
  336. net: ({ remaining }) => (
  337. <span className="text-sm text-white">{formatWeight(remaining)}</span>
  338. ),
  339. gross: ({ spool, remaining }) => (
  340. <span className="text-sm text-bambu-gray">{formatWeight(remaining + spool.core_weight)}</span>
  341. ),
  342. added_full: ({ spool }) => (
  343. <span className="text-sm text-bambu-gray">{spool.added_full == null ? '-' : spool.added_full ? 'Yes' : 'No'}</span>
  344. ),
  345. used: ({ spool }) => (
  346. <span className="text-sm text-bambu-gray">{spool.weight_used > 0 ? formatWeight(spool.weight_used) : '-'}</span>
  347. ),
  348. printed_total: () => (
  349. <span className="text-sm text-bambu-gray/50">-</span>
  350. ),
  351. printed_since_weight: () => (
  352. <span className="text-sm text-bambu-gray/50">-</span>
  353. ),
  354. note: ({ spool }) => (
  355. <span className="text-sm text-bambu-gray max-w-[150px] truncate block" title={spool.note || undefined}>{spool.note || '-'}</span>
  356. ),
  357. // Supplier chips (#2988): purchase source first and highlighted; the
  358. // others read as alternative sources. Tooltip carries the supplier's
  359. // article number when set.
  360. suppliers: ({ spool }) => {
  361. const links = spool.suppliers ?? [];
  362. if (links.length === 0) return <span className="text-sm text-bambu-gray">-</span>;
  363. const sorted = [...links].sort((a, b) => Number(b.is_purchase_source) - Number(a.is_purchase_source));
  364. return (
  365. <div className="flex flex-wrap gap-1 max-w-[220px]">
  366. {sorted.map((link) => (
  367. <span
  368. key={link.id}
  369. title={link.supplier_article_number || undefined}
  370. className={`inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium ${
  371. link.is_purchase_source
  372. ? 'bg-bambu-green/20 text-bambu-green'
  373. : 'bg-bambu-gray/10 text-bambu-gray'
  374. }`}
  375. >
  376. {link.supplier_name}
  377. </span>
  378. ))}
  379. </div>
  380. );
  381. },
  382. pa_k: ({ spool }) => {
  383. const count = spool.k_profiles?.length ?? 0;
  384. if (count === 0) return <span className="text-sm text-bambu-gray">-</span>;
  385. return (
  386. <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green">
  387. K
  388. </span>
  389. );
  390. },
  391. tag_id: ({ spool }) => {
  392. const tag = spool.tag_uid || spool.tray_uuid;
  393. if (!tag) return <span className="text-sm text-bambu-gray/50">-</span>;
  394. return (
  395. <span className="text-sm text-bambu-gray font-mono" title={tag}>
  396. {tag.length > 12 ? `${tag.slice(0, 6)}...${tag.slice(-4)}` : tag}
  397. </span>
  398. );
  399. },
  400. data_origin: ({ spool }) => (
  401. <span className="text-sm text-bambu-gray">{spool.data_origin || '-'}</span>
  402. ),
  403. tag_type: ({ spool }) => (
  404. <span className="text-sm text-bambu-gray">{spool.tag_type || '-'}</span>
  405. ),
  406. stock: ({ spool, t }) => {
  407. if (!spool.slicer_filament) {
  408. return (
  409. <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400">
  410. {t('inventory.stock')}
  411. </span>
  412. );
  413. }
  414. return <span className="text-sm text-bambu-gray">-</span>;
  415. },
  416. remaining: ({ remaining, pct }) => (
  417. <div className="flex items-center gap-2">
  418. <div className="flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden">
  419. <div
  420. className={`h-full rounded-full ${pct > 50 ? 'bg-bambu-green' : pct > 20 ? 'bg-yellow-500' : 'bg-red-500'}`}
  421. style={{ width: `${Math.min(pct, 100)}%` }}
  422. />
  423. </div>
  424. <span className="text-xs text-bambu-gray min-w-[40px] text-right">{Math.round(remaining)}g</span>
  425. </div>
  426. ),
  427. spool_name: ({ spool, catalogMap }) => {
  428. const entry = spool.core_weight_catalog_id != null ? catalogMap[spool.core_weight_catalog_id] : undefined;
  429. return <span className="text-sm text-bambu-gray">{entry?.name || '-'}</span>;
  430. },
  431. cost_per_kg: ({ spool, currencySymbol }) => (
  432. <span className="text-sm text-bambu-gray">
  433. {spool.cost_per_kg != null ? `${currencySymbol}${spool.cost_per_kg.toFixed(2)}` : '-'}
  434. </span>
  435. ),
  436. weight_check: ({ spool, onSyncWeight }) => {
  437. const scaleWeight = spool.last_scale_weight;
  438. if (scaleWeight == null) return <span className="text-sm text-bambu-gray/50" title="No scale measurement">-</span>;
  439. const coreWeight = spool.core_weight || 0;
  440. const calculatedWeight = Math.max(0, spool.label_weight - spool.weight_used) + coreWeight;
  441. // Edge case: scale < core_weight means spool is empty or not on scale — treat as match
  442. let difference: number;
  443. let isMatch: boolean;
  444. if (scaleWeight < coreWeight) {
  445. difference = scaleWeight - coreWeight;
  446. isMatch = true;
  447. } else {
  448. difference = scaleWeight - calculatedWeight;
  449. isMatch = Math.abs(difference) <= 50;
  450. }
  451. const diffStr = difference > 0 ? `+${Math.round(difference)}` : `${Math.round(difference)}`;
  452. const tooltip = isMatch
  453. ? `Scale: ${Math.round(scaleWeight)}g\nCalculated: ${Math.round(calculatedWeight)}g\nDifference: ${diffStr}g (within tolerance)`
  454. : `Scale: ${Math.round(scaleWeight)}g\nCalculated: ${Math.round(calculatedWeight)}g\nDifference: ${diffStr}g (mismatch!)`;
  455. return (
  456. <div
  457. className={`flex items-center gap-1 text-sm font-medium ${isMatch ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}
  458. title={tooltip}
  459. >
  460. <span>{Math.round(scaleWeight)}g</span>
  461. {isMatch ? (
  462. <Check className="w-3 h-3" />
  463. ) : (
  464. <>
  465. <AlertTriangle className="w-3 h-3" />
  466. {onSyncWeight && (
  467. <button
  468. type="button"
  469. onClick={(e) => {
  470. e.stopPropagation();
  471. e.preventDefault();
  472. onSyncWeight(spool);
  473. }}
  474. className="p-1 hover:bg-bambu-green/20 rounded transition-colors text-bambu-green"
  475. title="Sync: trust scale weight and reset tracking"
  476. >
  477. <RefreshCw className="w-3.5 h-3.5" />
  478. </button>
  479. )}
  480. </>
  481. )}
  482. </div>
  483. );
  484. },
  485. };
  486. // Sort value extractors — return a comparable value for each sortable column
  487. const columnSortValues: Record<
  488. string,
  489. (
  490. spool: InventorySpool,
  491. assignmentMap: Record<number, LocationDisplay>,
  492. locationReadingsMap: Record<number, LocationHASensorReading[]>
  493. ) => string | number
  494. > = {
  495. id: (s) => s.id,
  496. added_time: (s) => s.created_at || '',
  497. encode_time: (s) => s.encode_time || '',
  498. last_used_time: (s) => s.last_used || '',
  499. material: (s) => (s.material || '').toLowerCase(),
  500. subtype: (s) => (s.subtype || '').toLowerCase(),
  501. color_name: (s) => (s.color_name || '').toLowerCase(),
  502. // Sorts the swatch column itself (#2729). Multi-colour spools sort on their
  503. // primary colour — extra_colors are gradient stops, and a spool has to sit in
  504. // exactly one place in the list.
  505. rgba: (s) => colorSortKey(s.rgba),
  506. brand: (s) => (s.brand || '').toLowerCase(),
  507. slicer_filament: (s) => (s.slicer_filament_name || s.slicer_filament || '').toLowerCase(),
  508. location: (s, am) => {
  509. const a = am[s.id];
  510. if (!a) return '';
  511. const isExt = a.ams_id === 254 || a.ams_id === 255;
  512. const isHt = !isExt && a.ams_id >= 128;
  513. const label = a.ams_label ? ` (${a.ams_label})` : '';
  514. return `${a.printer_name || ''} ${formatSlotLabel(a.ams_id, a.tray_id, isHt, isExt)}${label}`;
  515. },
  516. storage_location: (s) => (s.storage_location || '').toLowerCase(),
  517. label_weight: (s) => s.label_weight,
  518. net: (s) => Math.max(0, s.label_weight - s.weight_used),
  519. gross: (s) => Math.max(0, s.label_weight - s.weight_used) + s.core_weight,
  520. used: (s) => s.weight_used,
  521. remaining: (s) => s.label_weight > 0 ? Math.max(0, s.label_weight - s.weight_used) / s.label_weight : 0,
  522. note: (s) => (s.note || '').toLowerCase(),
  523. // Sorts on the purchase-source supplier, falling back to the first
  524. // assignment — a spool has to sit in exactly one place in the list.
  525. suppliers: (s) => {
  526. const links = s.suppliers ?? [];
  527. const primary = links.find((l) => l.is_purchase_source) ?? links[0];
  528. return (primary?.supplier_name || '').toLowerCase();
  529. },
  530. data_origin: (s) => (s.data_origin || '').toLowerCase(),
  531. tag_type: (s) => (s.tag_type || '').toLowerCase(),
  532. stock: (s) => s.slicer_filament ? 1 : 0,
  533. spool_name: (s) => s.core_weight_catalog_id ?? 0,
  534. cost_per_kg: (s) => s.cost_per_kg ?? 0,
  535. weight_check: (s) => {
  536. if (s.last_scale_weight == null) return -1;
  537. const expectedGross = Math.max(0, s.label_weight - s.weight_used) + s.core_weight;
  538. return Math.abs(s.last_scale_weight - expectedGross);
  539. },
  540. temperature: (s, _am, lrm) => {
  541. const readings = s.location_id ? lrm[s.location_id] : undefined;
  542. return readings?.find((r) => r.device_class === 'temperature')?.value ?? -Infinity;
  543. },
  544. humidity: (s, _am, lrm) => {
  545. const readings = s.location_id ? lrm[s.location_id] : undefined;
  546. return readings?.find((r) => r.device_class === 'humidity')?.value ?? -Infinity;
  547. },
  548. battery: (s, _am, lrm) => {
  549. const readings = s.location_id ? lrm[s.location_id] : undefined;
  550. return readings?.find((r) => r.device_class === 'battery')?.value ?? -Infinity;
  551. },
  552. };
  553. const SORT_STATE_KEY = 'bambuddy-inventory-sort';
  554. function loadSortState(): SortState {
  555. try {
  556. const stored = localStorage.getItem(SORT_STATE_KEY);
  557. if (stored) return JSON.parse(stored);
  558. } catch { /* ignore */ }
  559. return null;
  560. }
  561. function saveSortState(state: SortState) {
  562. try {
  563. if (state) {
  564. localStorage.setItem(SORT_STATE_KEY, JSON.stringify(state));
  565. } else {
  566. localStorage.removeItem(SORT_STATE_KEY);
  567. }
  568. } catch { /* ignore */ }
  569. }
  570. // Wrapper: detects Spoolman mode and passes it to the shared inventory UI
  571. export default function InventoryPageRouter() {
  572. const { data: spoolmanSettings } = useQuery({
  573. queryKey: ['spoolman-settings'],
  574. queryFn: api.getSpoolmanSettings,
  575. staleTime: 5 * 60 * 1000,
  576. });
  577. const spoolmanModeReady = spoolmanSettings !== undefined;
  578. const spoolmanMode =
  579. spoolmanSettings?.spoolman_enabled === 'true' && !!spoolmanSettings?.spoolman_url;
  580. return <InventoryPage spoolmanMode={spoolmanMode} spoolmanModeReady={spoolmanModeReady} />;
  581. }
  582. function InventoryPage({ spoolmanMode = false, spoolmanModeReady = true }: { spoolmanMode?: boolean; spoolmanModeReady?: boolean }) {
  583. const { t } = useTranslation();
  584. // The spool filter below resolves colour names through the catalog; its
  585. // memo has to recompute when the catalog finishes loading (#3090).
  586. const colorCatalogVersion = useColorCatalogVersion();
  587. const queryClient = useQueryClient();
  588. const { showToast } = useToast();
  589. const { hasPermission, loading: authLoading } = useAuth();
  590. const canViewForecast = !authLoading && hasPermission('inventory:forecast_read');
  591. const [searchParams, setSearchParams] = useSearchParams();
  592. const [formModal, setFormModal] = useState<{ spool?: InventorySpool | null; mode: SpoolFormMode } | null>(null);
  593. const deepLinkHandled = useRef(false);
  594. const [confirmAction, setConfirmAction] = useState<
  595. | { type: 'delete' | 'archive' | 'reset-consumed-counter'; spoolId: number }
  596. | { type: 'reset-all-consumed-counters' }
  597. | null
  598. >(null);
  599. // Label printing (#809). null = closed; otherwise the IDs to print labels for.
  600. const [labelPickerSpoolIds, setLabelPickerSpoolIds] = useState<number[] | null>(null);
  601. // CSV import/export (#1576). Local inventory only — hidden in Spoolman mode.
  602. const [csvImportOpen, setCsvImportOpen] = useState(false);
  603. const [exportingCsv, setExportingCsv] = useState(false);
  604. const [locationsModalOpen, setLocationsModalOpen] = useState(false);
  605. const [suppliersModalOpen, setSuppliersModalOpen] = useState(false);
  606. // Filter state
  607. const [archiveFilter, setArchiveFilter] = useState<ArchiveFilter>('active');
  608. const [usageFilter, setUsageFilter] = useState<UsageFilter>('all');
  609. const [materialFilter, setMaterialFilter] = useState('');
  610. const [brandFilter, setBrandFilter] = useState('');
  611. const [categoryFilter, setCategoryFilter] = useState('');
  612. // Filter on an assigned supplier (#2988), same shape as category.
  613. const [supplierFilter, setSupplierFilter] = useState('');
  614. const [spoolFilter, setSpoolFilter] = useState('');
  615. const [stockFilter, setStockFilter] = useState<'all' | 'stock' | 'configured'>('all');
  616. const [search, setSearch] = useState('');
  617. const [viewMode, setViewMode] = useState<ViewMode>('table');
  618. const [sortState, setSortState] = useState<SortState>(loadSortState);
  619. const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(loadColumnConfig);
  620. const [showColumnModal, setShowColumnModal] = useState(false);
  621. const [groupSimilar, setGroupSimilar] = useState(() => {
  622. try {
  623. return localStorage.getItem('bambuddy-inventory-group') === 'true';
  624. } catch { return false; }
  625. });
  626. const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
  627. // Bulk-selection state for batch actions on the spool list (#1795).
  628. // Cleared when the user switches filter/tab/page because cross-page selection
  629. // produces a confusing toolbar count vs. visible-row count delta.
  630. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  631. const [bulkEditOpen, setBulkEditOpen] = useState(false);
  632. const [bulkConfirmAction, setBulkConfirmAction] = useState<'delete' | 'archive' | 'restore' | 'reset-consumed-counter' | null>(null);
  633. const toggleSelected = useCallback((id: number) => {
  634. setSelectedIds((prev) => {
  635. const next = new Set(prev);
  636. if (next.has(id)) next.delete(id);
  637. else next.add(id);
  638. return next;
  639. });
  640. }, []);
  641. const clearSelection = useCallback(() => setSelectedIds(new Set()), []);
  642. // Clear selection on any filter/tab change so the toolbar count stays
  643. // honest vs. what the user is actually looking at.
  644. useEffect(() => {
  645. setSelectedIds(new Set());
  646. }, [archiveFilter, usageFilter, materialFilter, brandFilter, categoryFilter, supplierFilter, spoolFilter, stockFilter, search]);
  647. // Pagination state (pageSize persisted to localStorage)
  648. const [pageIndex, setPageIndex] = useState(0);
  649. const [pageSize, setPageSize] = useState(() => {
  650. try {
  651. const stored = localStorage.getItem('bambuddy-inventory-pageSize');
  652. if (stored) {
  653. const n = Number(stored);
  654. if ([15, 30, 50, 100, -1].includes(n)) return n;
  655. }
  656. } catch { /* ignore */ }
  657. return 15;
  658. });
  659. const { data: settings } = useQuery({
  660. queryKey: ['settings'],
  661. queryFn: api.getSettings,
  662. });
  663. const dateFormat: DateFormat = settings?.date_format || 'system';
  664. const locationSensorPollIntervalMs = (settings?.location_sensor_poll_interval || 120) * 1000;
  665. const {
  666. colorize: colorizeLocationSensors,
  667. aboveColor: locationSensorAboveColor,
  668. belowColor: locationSensorBelowColor,
  669. optimalColor: locationSensorOptimalColor,
  670. } = useLocationSensorColorPrefs();
  671. // Query key and fetch function differ based on data source
  672. const spoolsQueryKey = spoolmanMode ? ['spoolman-inventory-spools'] : ['inventory-spools'];
  673. const refreshSpoolQueries = () => invalidateSpoolAndLocationQueries(queryClient, spoolsQueryKey);
  674. const { data: spools, isLoading } = useQuery({
  675. queryKey: spoolsQueryKey,
  676. queryFn: () =>
  677. spoolmanMode ? api.getSpoolmanInventorySpools(true) : api.getSpools(true),
  678. refetchInterval: 30000,
  679. });
  680. // CSV export (#1576) — downloads the active inventory as a CSV file.
  681. const handleExportCsv = useCallback(async () => {
  682. setExportingCsv(true);
  683. try {
  684. await api.exportSpoolsCsv();
  685. } catch (err) {
  686. showToast(
  687. err instanceof Error ? err.message : t('inventory.csv.exportError', 'Export failed'),
  688. 'error',
  689. );
  690. } finally {
  691. setExportingCsv(false);
  692. }
  693. }, [showToast, t]);
  694. // Shown as the tooltip on both CSV buttons when they're disabled in Spoolman mode.
  695. const spoolmanCsvHint = spoolmanMode
  696. ? t('inventory.csv.spoolmanHint', 'In Spoolman mode, use Spoolman\'s built-in CSV import/export.')
  697. : undefined;
  698. const { data: storageLocations = [] } = useQuery({
  699. queryKey: inventoryLocationsQueryKey,
  700. queryFn: api.getLocations,
  701. });
  702. // Deep-link / filter: ?location_id=<id> or ?location_id=__none__
  703. const _rawLocationParam = searchParams.get('location_id');
  704. const storageLocationFilter =
  705. _rawLocationParam === '__none__'
  706. ? '__none__'
  707. : _rawLocationParam && /^\d+$/.test(_rawLocationParam) && Number(_rawLocationParam) > 0
  708. ? _rawLocationParam
  709. : '';
  710. // Deep-link: open edit modal for ?spool=<id>
  711. // Prefer the already-loaded spool list (no extra API call); fall back to a
  712. // targeted fetch for the rare case where the full list hasn't arrived yet.
  713. const _rawSpoolParam = searchParams.get('spool');
  714. // Only accept strings of digits representing a positive integer — guards against
  715. // NaN (Number('abc')), 0, negatives, and floats like '1.5' that would produce
  716. // an invalid path parameter and trigger unnecessary 422 responses from the API.
  717. const deepLinkSpoolId =
  718. _rawSpoolParam && /^\d+$/.test(_rawSpoolParam) && Number(_rawSpoolParam) > 0
  719. ? Number(_rawSpoolParam)
  720. : null;
  721. const deepLinkInList = spools?.find((s) => s.id === deepLinkSpoolId) ?? null;
  722. const clearDeepLinkParam = useCallback(() => {
  723. deepLinkHandled.current = true;
  724. setSearchParams((prev) => { prev.delete('spool'); return prev; }, { replace: true });
  725. }, [setSearchParams]);
  726. // Targeted fetch — only fires when mode is known and spool isn't in the list yet
  727. const { data: deepLinkSpool, isError: deepLinkFetchFailed, error: deepLinkError } = useQuery({
  728. queryKey: spoolmanMode
  729. ? ['spoolman-inventory-spool', deepLinkSpoolId]
  730. : ['inventory-spool', deepLinkSpoolId],
  731. queryFn: () =>
  732. spoolmanMode
  733. ? api.getSpoolmanInventorySpool(deepLinkSpoolId!)
  734. : api.getSpool(deepLinkSpoolId!),
  735. enabled: spoolmanModeReady && deepLinkSpoolId !== null && deepLinkInList === null,
  736. staleTime: Infinity,
  737. retry: (failureCount, error) =>
  738. failureCount < 2 && !(error instanceof ApiError && error.status === 404),
  739. });
  740. useEffect(() => {
  741. if (deepLinkHandled.current) return;
  742. // Case 1: spool is already in the fetched list
  743. if (spoolmanModeReady && deepLinkSpoolId && deepLinkInList) {
  744. clearDeepLinkParam();
  745. setFormModal({ spool: deepLinkInList, mode: 'edit' });
  746. return;
  747. }
  748. // Case 2: spool was fetched individually
  749. if (deepLinkSpool) {
  750. clearDeepLinkParam();
  751. setFormModal({ spool: deepLinkSpool, mode: 'edit' });
  752. return;
  753. }
  754. // Case 3: fetch failed
  755. if (deepLinkFetchFailed) {
  756. clearDeepLinkParam();
  757. const is404 = deepLinkError instanceof ApiError && deepLinkError.status === 404;
  758. showToast(t(is404 ? 'inventory.deepLinkSpoolNotFound' : 'inventory.deepLinkFetchFailed'), 'error');
  759. }
  760. }, [
  761. spoolmanModeReady,
  762. deepLinkSpoolId,
  763. deepLinkInList,
  764. deepLinkSpool,
  765. deepLinkFetchFailed,
  766. deepLinkError,
  767. clearDeepLinkParam,
  768. showToast,
  769. t,
  770. ]);
  771. const { data: assignments } = useQuery({
  772. queryKey: ['spool-assignments'],
  773. queryFn: () => api.getAssignments(),
  774. refetchInterval: 30000,
  775. });
  776. // Spoolman-mode slot assignments. spool.id IS the spoolman_spool_id, so this
  777. // feeds into the same assignmentMap that the LOCATION column reads.
  778. const {
  779. data: spoolmanSlotAssignments = [],
  780. isError: spoolmanSlotAssignmentsError,
  781. } = useQuery({
  782. queryKey: ['spoolman-slot-assignments-all'],
  783. queryFn: () => api.getSpoolmanSlotAssignments(),
  784. enabled: spoolmanMode,
  785. refetchInterval: 30000,
  786. staleTime: 10000,
  787. retry: 1,
  788. });
  789. // Surface a single toast when the slot-assignment endpoint goes down — the
  790. // LOCATION column would otherwise silently show "-" for every Spoolman spool.
  791. // useRef guard prevents repeated toasts during refetchInterval polls.
  792. const slotErrorToastShown = useRef(false);
  793. useEffect(() => {
  794. if (spoolmanSlotAssignmentsError && !slotErrorToastShown.current) {
  795. slotErrorToastShown.current = true;
  796. showToast(t('inventory.spoolmanUnreachable'), 'error');
  797. } else if (!spoolmanSlotAssignmentsError) {
  798. slotErrorToastShown.current = false;
  799. }
  800. }, [spoolmanSlotAssignmentsError, showToast, t]);
  801. const { data: catalogEntries } = useQuery({
  802. queryKey: ['spool-catalog'],
  803. queryFn: () => api.getSpoolCatalog(),
  804. });
  805. const deleteMutation = useMutation({
  806. mutationFn: (id: number) =>
  807. spoolmanMode ? api.deleteSpoolmanInventorySpool(id) : api.deleteSpool(id),
  808. onSuccess: () => {
  809. refreshSpoolQueries();
  810. showToast(t('inventory.spoolDeleted'), 'success');
  811. },
  812. onError: (error: Error) => {
  813. if (error instanceof ApiError && error.status === 404) {
  814. showToast(t('inventory.deleteSpoolNotFound'), 'error');
  815. } else if (error instanceof ApiError && error.status === 503) {
  816. showToast(t('inventory.spoolmanUnreachable'), 'error');
  817. } else {
  818. showToast(t('inventory.deleteFailed'), 'error');
  819. }
  820. },
  821. });
  822. const archiveMutation = useMutation({
  823. mutationFn: (id: number) =>
  824. spoolmanMode ? api.archiveSpoolmanInventorySpool(id) : api.archiveSpool(id),
  825. onSuccess: () => {
  826. refreshSpoolQueries();
  827. showToast(t('inventory.spoolArchived'), 'success');
  828. },
  829. onError: (error: Error) => {
  830. if (error instanceof ApiError && error.status === 404) {
  831. showToast(t('inventory.archiveSpoolNotFound'), 'error');
  832. } else if (error instanceof ApiError && error.status === 503) {
  833. showToast(t('inventory.spoolmanUnreachable'), 'error');
  834. } else {
  835. showToast(t('inventory.archiveFailed'), 'error');
  836. }
  837. },
  838. });
  839. const restoreMutation = useMutation({
  840. mutationFn: (id: number) =>
  841. spoolmanMode ? api.restoreSpoolmanInventorySpool(id) : api.restoreSpool(id),
  842. onSuccess: () => {
  843. refreshSpoolQueries();
  844. showToast(t('inventory.spoolRestored'), 'success');
  845. },
  846. onError: (error: Error) => {
  847. if (error instanceof ApiError && error.status === 404) {
  848. showToast(t('inventory.restoreSpoolNotFound'), 'error');
  849. } else if (error instanceof ApiError && error.status === 503) {
  850. showToast(t('inventory.spoolmanUnreachable'), 'error');
  851. } else {
  852. showToast(t('inventory.restoreFailed'), 'error');
  853. }
  854. },
  855. });
  856. const resetConsumedCounterMutation = useMutation({
  857. mutationFn: (id: number) =>
  858. spoolmanMode
  859. ? api.resetSpoolmanInventorySpoolConsumedCounter(id)
  860. : api.resetSpoolConsumedCounter(id),
  861. onSuccess: () => {
  862. queryClient.invalidateQueries({ queryKey: spoolsQueryKey });
  863. showToast(t('inventory.consumedCounterReset'), 'success');
  864. },
  865. onError: () => {
  866. showToast(t('inventory.resetConsumedCounterFailed'), 'error');
  867. },
  868. });
  869. const bulkResetConsumedCounterMutation = useMutation({
  870. mutationFn: (ids: number[]) =>
  871. spoolmanMode
  872. ? api.bulkResetSpoolmanInventorySpoolConsumedCounter(ids)
  873. : api.bulkResetSpoolConsumedCounter(ids),
  874. onSuccess: (data) => {
  875. queryClient.invalidateQueries({ queryKey: spoolsQueryKey });
  876. showToast(t('inventory.allConsumedCountersReset', { count: data.reset }), 'success');
  877. // Close any open bulk-confirm modal + clear selection so the toolbar
  878. // collapses after the action — matches the other three bulk mutations
  879. // and stops the confirm dialog from lingering after Reset.
  880. setBulkConfirmAction(null);
  881. clearSelection();
  882. },
  883. onError: () => {
  884. showToast(t('inventory.resetConsumedCounterFailed'), 'error');
  885. },
  886. });
  887. // Bulk action mutations (#1795). Each invalidates the same query keys as
  888. // the per-spool equivalents so the table refreshes with the new state.
  889. // Helper: count items that didn't succeed across the two response shapes
  890. // (internal mode returns not_found, Spoolman returns errors[]). When the
  891. // success count is 0 OR any failures occurred, surface that to the user
  892. // instead of the silent green-toast-and-clear flow the first cut shipped.
  893. const failedCount = (data: { not_found?: number[]; errors?: Array<{ id: number }> }): number =>
  894. (data.not_found?.length ?? 0) + (data.errors?.length ?? 0);
  895. const bulkUpdateMutation = useMutation({
  896. mutationFn: async ({ ids, update }: { ids: number[]; update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>> }): Promise<{ updated: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }> => {
  897. if (spoolmanMode) return api.bulkUpdateSpoolmanInventorySpools(ids, update);
  898. return api.bulkUpdateSpools(ids, update);
  899. },
  900. onSuccess: (data) => {
  901. refreshSpoolQueries();
  902. const failed = failedCount(data);
  903. if (data.updated === 0) {
  904. showToast(t('inventory.bulk.updateAllFailed', { count: failed }), 'error');
  905. return; // keep modal open + selection intact so user can retry
  906. }
  907. if (failed > 0) {
  908. showToast(t('inventory.bulk.updatePartial', { ok: data.updated, failed }), 'warning');
  909. } else {
  910. showToast(t('inventory.bulk.updateSuccess', { count: data.updated }), 'success');
  911. }
  912. setBulkEditOpen(false);
  913. clearSelection();
  914. },
  915. onError: (err: Error) => {
  916. showToast(err.message || t('inventory.bulk.updateFailed'), 'error');
  917. },
  918. });
  919. const bulkDeleteMutation = useMutation({
  920. mutationFn: async (ids: number[]): Promise<{ deleted: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }> => {
  921. if (spoolmanMode) return api.bulkDeleteSpoolmanInventorySpools(ids);
  922. return api.bulkDeleteSpools(ids);
  923. },
  924. onSuccess: (data) => {
  925. refreshSpoolQueries();
  926. const failed = failedCount(data);
  927. if (data.deleted === 0) {
  928. showToast(t('inventory.bulk.deleteAllFailed', { count: failed }), 'error');
  929. return;
  930. }
  931. if (failed > 0) {
  932. showToast(t('inventory.bulk.deletePartial', { ok: data.deleted, failed }), 'warning');
  933. } else {
  934. showToast(t('inventory.bulk.deleteSuccess', { count: data.deleted }), 'success');
  935. }
  936. setBulkConfirmAction(null);
  937. clearSelection();
  938. },
  939. onError: (err: Error) => {
  940. showToast(err.message || t('inventory.bulk.deleteFailed'), 'error');
  941. },
  942. });
  943. const bulkArchiveMutation = useMutation({
  944. mutationFn: async (ids: number[]): Promise<{ archived: number; already_archived?: number[]; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }> => {
  945. if (spoolmanMode) return api.bulkArchiveSpoolmanInventorySpools(ids);
  946. return api.bulkArchiveSpools(ids);
  947. },
  948. onSuccess: (data) => {
  949. refreshSpoolQueries();
  950. // already-archived rows are NOT failures — they're correctly idempotent.
  951. const failed = failedCount(data);
  952. if (data.archived === 0 && failed > 0) {
  953. showToast(t('inventory.bulk.archiveAllFailed', { count: failed }), 'error');
  954. return;
  955. }
  956. if (failed > 0) {
  957. showToast(t('inventory.bulk.archivePartial', { ok: data.archived, failed }), 'warning');
  958. } else {
  959. showToast(t('inventory.bulk.archiveSuccess', { count: data.archived }), 'success');
  960. }
  961. setBulkConfirmAction(null);
  962. clearSelection();
  963. },
  964. onError: (err: Error) => {
  965. showToast(err.message || t('inventory.bulk.archiveFailed'), 'error');
  966. },
  967. });
  968. const bulkRestoreMutation = useMutation({
  969. mutationFn: async (ids: number[]): Promise<{ restored: number; already_active?: number[]; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }> => {
  970. if (spoolmanMode) return api.bulkRestoreSpoolmanInventorySpools(ids);
  971. return api.bulkRestoreSpools(ids);
  972. },
  973. onSuccess: (data) => {
  974. refreshSpoolQueries();
  975. const failed = failedCount(data);
  976. if (data.restored === 0 && failed > 0) {
  977. showToast(t('inventory.bulk.restoreAllFailed', { count: failed }), 'error');
  978. return;
  979. }
  980. if (failed > 0) {
  981. showToast(t('inventory.bulk.restorePartial', { ok: data.restored, failed }), 'warning');
  982. } else {
  983. showToast(t('inventory.bulk.restoreSuccess', { count: data.restored }), 'success');
  984. }
  985. setBulkConfirmAction(null);
  986. clearSelection();
  987. },
  988. onError: (err: Error) => {
  989. showToast(err.message || t('inventory.bulk.restoreFailed'), 'error');
  990. },
  991. });
  992. // Spool IDs the "Reset all usage" button bulk-targets. Includes archived
  993. // spools too — without them, the broadened "Total Consumed" stat (which
  994. // sums archived consumption per the #1390 follow-up) would stay non-zero
  995. // after a Reset-all click, surprising the user. Backend reset endpoints
  996. // (both internal and Spoolman) already accept archived IDs without a
  997. // route-level guard, so this just removes the frontend filter.
  998. const resetableSpoolIds = useMemo(
  999. () => (spools ?? []).map((s) => s.id),
  1000. [spools],
  1001. );
  1002. const handleSyncWeight = async (spool: InventorySpool) => {
  1003. if (spool.last_scale_weight == null) return;
  1004. try {
  1005. if (spoolmanMode) {
  1006. await api.syncSpoolmanSpoolWeight(spool.id, spool.last_scale_weight);
  1007. } else {
  1008. await spoolbuddyApi.updateSpoolWeight(spool.id, spool.last_scale_weight);
  1009. }
  1010. queryClient.invalidateQueries({ queryKey: spoolsQueryKey });
  1011. const spoolName = [
  1012. spool.brand,
  1013. spool.material,
  1014. resolveSpoolColorName(spool.color_name, spool.rgba, spool.color_name_is_synthesized),
  1015. ]
  1016. .filter(Boolean)
  1017. .join(' ');
  1018. showToast(`Synced "${spoolName}" to scale weight`, 'success');
  1019. } catch (e) {
  1020. const is404 = e instanceof ApiError && e.status === 404;
  1021. const is503 = e instanceof ApiError && e.status === 503;
  1022. if (is404) showToast(t('inventory.syncWeightSpoolNotFound'), 'error');
  1023. else if (is503) showToast(t('inventory.syncWeightSpoolmanUnreachable'), 'error');
  1024. else showToast(t('inventory.syncWeightFailed'), 'error');
  1025. }
  1026. };
  1027. // Low stock threshold from backend settings
  1028. const lowStockThreshold = settings?.low_stock_threshold ?? 20;
  1029. const [showThresholdInput, setShowThresholdInput] = useState(false);
  1030. const [thresholdInput, setThresholdInput] = useState(lowStockThreshold.toString());
  1031. // Sync thresholdInput when lowStockThreshold changes and input is not shown
  1032. useEffect(() => {
  1033. if (!showThresholdInput) {
  1034. setThresholdInput(lowStockThreshold.toString());
  1035. }
  1036. }, [lowStockThreshold, showThresholdInput]);
  1037. const updateThresholdMutation = useMutation({
  1038. mutationFn: (threshold: number) => api.updateSettings({ low_stock_threshold: threshold }),
  1039. onSuccess: () => {
  1040. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1041. showToast(t('common.saved'), 'success');
  1042. setShowThresholdInput(false);
  1043. },
  1044. onError: () => {
  1045. showToast(t('inventory.lowStockThresholdError'), 'error');
  1046. },
  1047. });
  1048. // Stats calculation.
  1049. //
  1050. // "Total Consumed" sums over ALL spools (active AND archived) because it's
  1051. // a running counter — past consumption of a now-archived spool is real
  1052. // history and silently dropping it on archive made the running total
  1053. // collapse mysteriously (#1390 follow-up). The other aggregates
  1054. // (totalWeight, lowStock, byMaterial, activeCount) describe what's
  1055. // currently in active inventory and stay active-only.
  1056. const stats = useMemo(() => {
  1057. if (!spools) return null;
  1058. let totalWeight = 0;
  1059. let totalConsumed = 0;
  1060. let lowStock = 0;
  1061. let activeCount = 0;
  1062. const byMaterial: Record<string, { count: number; weight: number }> = {};
  1063. for (const s of spools) {
  1064. // "Total Consumed" is the resettable counter (weight_used - baseline)
  1065. // rather than raw weight_used so the per-spool / bulk eraser zeroes
  1066. // the stat without inflating remaining back to label_weight (#1390).
  1067. // Computed before the archived-skip below so archived consumption
  1068. // stays in the running total.
  1069. totalConsumed += Math.max(0, s.weight_used - (s.weight_used_baseline ?? 0));
  1070. if (s.archived_at) continue;
  1071. activeCount++;
  1072. const remaining = Math.max(0, s.label_weight - s.weight_used);
  1073. totalWeight += remaining;
  1074. const pct = s.label_weight > 0 ? (remaining / s.label_weight) * 100 : 0;
  1075. const threshold = s.low_stock_threshold_pct ?? lowStockThreshold;
  1076. if (pct < threshold) lowStock++;
  1077. const mat = s.material || 'Unknown';
  1078. if (!byMaterial[mat]) byMaterial[mat] = { count: 0, weight: 0 };
  1079. byMaterial[mat].count++;
  1080. byMaterial[mat].weight += remaining;
  1081. }
  1082. return { totalWeight, totalConsumed, lowStock, byMaterial, totalSpools: activeCount };
  1083. }, [spools, lowStockThreshold]);
  1084. const inPrinterCount =
  1085. (assignments?.length ?? 0) + (spoolmanMode ? spoolmanSlotAssignments.length : 0);
  1086. const currencySymbol = getCurrencySymbol(settings?.currency || 'USD');
  1087. // Map spool_id -> location display data for the LOCATION column.
  1088. // Local SpoolAssignment entries first, then Spoolman SlotAssignment fills in
  1089. // remaining IDs. Local wins on collision (defensive — modes are exclusive in
  1090. // practice, but a stray pair with the same numeric id would otherwise be
  1091. // unpredictable). spool.id IS the spoolman_spool_id in Spoolman mode.
  1092. const assignmentMap = useMemo<Record<number, LocationDisplay>>(() => {
  1093. const map: Record<number, LocationDisplay> = {};
  1094. for (const a of assignments || []) {
  1095. map[a.spool_id] = {
  1096. printer_id: a.printer_id,
  1097. printer_name: a.printer_name,
  1098. ams_id: a.ams_id,
  1099. tray_id: a.tray_id,
  1100. ams_label: a.ams_label ?? null,
  1101. };
  1102. }
  1103. for (const a of spoolmanSlotAssignments) {
  1104. // Defensive: skip malformed entries (missing or invalid spool id, ams id,
  1105. // tray id). The Pydantic response model on the backend should already
  1106. // reject these, but MITM proxies and stale CDN responses can drop fields.
  1107. if (
  1108. typeof a?.spoolman_spool_id !== 'number' ||
  1109. a.spoolman_spool_id <= 0 ||
  1110. typeof a.printer_id !== 'number' ||
  1111. typeof a.ams_id !== 'number' ||
  1112. typeof a.tray_id !== 'number'
  1113. ) continue;
  1114. if (!map[a.spoolman_spool_id]) {
  1115. map[a.spoolman_spool_id] = {
  1116. printer_id: a.printer_id,
  1117. printer_name: a.printer_name ?? null,
  1118. ams_id: a.ams_id,
  1119. tray_id: a.tray_id,
  1120. ams_label: a.ams_label ?? null,
  1121. };
  1122. }
  1123. }
  1124. return map;
  1125. }, [assignments, spoolmanSlotAssignments]);
  1126. // Map catalog_id -> catalog entry for spool name column
  1127. const catalogMap = useMemo(() => {
  1128. const map: Record<number, SpoolCatalogEntry> = {};
  1129. for (const e of catalogEntries || []) {
  1130. map[e.id] = e;
  1131. }
  1132. return map;
  1133. }, [catalogEntries]);
  1134. // Not polled — it only changes via explicit create/edit/delete, all of
  1135. // which already invalidate this key, and it also seeds the SpoolCard
  1136. // footers below (same query key, so they share this fetch instead of each
  1137. // issuing their own).
  1138. const { data: locationHaSensorsList } = useQuery({
  1139. queryKey: ['locationHaSensors'],
  1140. queryFn: () => api.getLocationHASensors(),
  1141. });
  1142. const locationIdsWithSensors = useMemo(
  1143. () => new Set((locationHaSensorsList ?? []).map((s) => s.location_id)),
  1144. [locationHaSensorsList]
  1145. );
  1146. const usedLocationIds = useMemo(() => {
  1147. const ids = new Set<number>();
  1148. for (const s of spools || []) {
  1149. // Skip locations with no bound sensor at all — polling them would only
  1150. // ever come back empty, and most installs have far more storage
  1151. // locations than ones actually wired up to Home Assistant.
  1152. if (s.location_id && locationIdsWithSensors.has(s.location_id)) ids.add(s.location_id);
  1153. }
  1154. return Array.from(ids);
  1155. }, [spools, locationIdsWithSensors]);
  1156. // Card view always needs readings (the SpoolCard footer below reads this
  1157. // same cache and filters to show_on_card itself); table view only needs
  1158. // them when a sensor column is actually visible, since the default
  1159. // column config hides all three.
  1160. const needsLocationReadings =
  1161. viewMode === 'cards' ||
  1162. (viewMode === 'table' &&
  1163. columnConfig.some((c) => c.visible && (c.id === 'temperature' || c.id === 'humidity' || c.id === 'battery')));
  1164. const locationReadingsQueries = useQueries({
  1165. queries: usedLocationIds.map((locationId) => ({
  1166. queryKey: ['locationHaSensorReadings', locationId],
  1167. queryFn: () => api.getLocationHASensorReadings(locationId, false),
  1168. refetchInterval: locationSensorPollIntervalMs,
  1169. enabled: needsLocationReadings,
  1170. })),
  1171. });
  1172. const locationReadingsMap = useMemo(() => {
  1173. const map: Record<number, LocationHASensorReading[]> = {};
  1174. usedLocationIds.forEach((locationId, i) => {
  1175. const data = locationReadingsQueries[i]?.data;
  1176. if (data) map[locationId] = data;
  1177. });
  1178. return map;
  1179. }, [usedLocationIds, locationReadingsQueries]);
  1180. // Top materials by weight for stat card pills
  1181. const topMaterials = useMemo(() => {
  1182. if (!stats) return [];
  1183. return Object.entries(stats.byMaterial)
  1184. .sort((a, b) => b[1].weight - a[1].weight)
  1185. .slice(0, 4);
  1186. }, [stats]);
  1187. // Filtering pipeline
  1188. const filteredSpools = useMemo(() => {
  1189. // Named so this memo depends on it: the global search below resolves
  1190. // colour names through the catalog, which `resolveSpoolColorName` reads
  1191. // from module state the linter cannot follow. Without it a query typed
  1192. // before the catalog loads keeps its empty result (#3090).
  1193. void colorCatalogVersion;
  1194. let filtered = spools || [];
  1195. // Archive filter
  1196. if (archiveFilter === 'active') {
  1197. filtered = filtered.filter((s) => !s.archived_at);
  1198. } else {
  1199. filtered = filtered.filter((s) => !!s.archived_at);
  1200. }
  1201. // Usage filter
  1202. if (usageFilter === 'used') {
  1203. filtered = filtered.filter((s) => s.weight_used > 0);
  1204. } else if (usageFilter === 'new') {
  1205. filtered = filtered.filter((s) => s.weight_used === 0);
  1206. } else if (usageFilter === 'lowstock') {
  1207. filtered = filtered.filter((s) => {
  1208. const remaining = Math.max(0, s.label_weight - s.weight_used);
  1209. const pct = s.label_weight > 0 ? (remaining / s.label_weight) * 100 : 0;
  1210. const threshold = s.low_stock_threshold_pct ?? lowStockThreshold;
  1211. return pct < threshold;
  1212. });
  1213. }
  1214. // Material dropdown
  1215. if (materialFilter) {
  1216. filtered = filtered.filter((s) => s.material === materialFilter);
  1217. }
  1218. // Brand dropdown
  1219. if (brandFilter) {
  1220. filtered = filtered.filter((s) => s.brand === brandFilter);
  1221. }
  1222. // Category dropdown (#729)
  1223. if (categoryFilter) {
  1224. if (categoryFilter === '__none__') {
  1225. filtered = filtered.filter((s) => !s.category);
  1226. } else {
  1227. filtered = filtered.filter((s) => s.category === categoryFilter);
  1228. }
  1229. }
  1230. // Supplier dropdown (#2988): "everything from supplier X" matches ANY
  1231. // assignment, purchase source or alternative; `__none__` finds spools
  1232. // without supplier assignments.
  1233. if (supplierFilter) {
  1234. if (supplierFilter === '__none__') {
  1235. filtered = filtered.filter((s) => (s.suppliers ?? []).length === 0);
  1236. } else {
  1237. const supplierId = Number(supplierFilter);
  1238. filtered = filtered.filter((s) => (s.suppliers ?? []).some((l) => l.supplier_id === supplierId));
  1239. }
  1240. }
  1241. // Spool name dropdown
  1242. if (spoolFilter) {
  1243. const catalogId = Number(spoolFilter);
  1244. filtered = filtered.filter((s) => s.core_weight_catalog_id === catalogId);
  1245. }
  1246. // Storage location dropdown (#1400). `__none__` lets the user find
  1247. // spools that haven't been assigned a storage location yet.
  1248. if (storageLocationFilter) {
  1249. if (storageLocationFilter === '__none__') {
  1250. filtered = filtered.filter((s) => !s.location_id && !s.storage_location?.trim());
  1251. } else {
  1252. const locId = Number(storageLocationFilter);
  1253. const locName = storageLocations.find((l) => l.id === locId)?.name?.trim().toLowerCase();
  1254. filtered = filtered.filter((s) => {
  1255. if (s.location_id != null) return s.location_id === locId;
  1256. if (locName) return (s.storage_location || '').trim().toLowerCase() === locName;
  1257. return false;
  1258. });
  1259. }
  1260. }
  1261. // Stock filter
  1262. if (stockFilter === 'stock') {
  1263. filtered = filtered.filter((s) => !s.slicer_filament);
  1264. } else if (stockFilter === 'configured') {
  1265. filtered = filtered.filter((s) => !!s.slicer_filament);
  1266. }
  1267. // Global search
  1268. if (search) {
  1269. filtered = filterSpoolsByQuery(filtered, search);
  1270. }
  1271. return filtered;
  1272. }, [spools, archiveFilter, usageFilter, materialFilter, brandFilter, categoryFilter, supplierFilter, spoolFilter, stockFilter, storageLocationFilter, search, lowStockThreshold, storageLocations, colorCatalogVersion]);
  1273. // Reset page on filter changes
  1274. const resetPage = () => setPageIndex(0);
  1275. const setStorageLocationFilter = useCallback((value: string) => {
  1276. setSearchParams((prev) => {
  1277. prev.delete('location_id');
  1278. if (value) {
  1279. prev.set('location_id', value);
  1280. }
  1281. return prev;
  1282. }, { replace: true });
  1283. resetPage();
  1284. }, [setSearchParams]);
  1285. // Unique values for filter dropdowns
  1286. const uniqueMaterials = [...new Set(spools?.map((s) => s.material) || [])].sort();
  1287. const uniqueBrands = [...new Set(spools?.map((s) => s.brand).filter(Boolean) || [])].sort() as string[];
  1288. const uniqueCategories = [...new Set(spools?.map((s) => s.category?.trim()).filter(Boolean) as string[] || [])].sort();
  1289. const hasUncategorized = (spools ?? []).some((s) => !s.category);
  1290. // #2988: suppliers seen across the inventory, for the filter dropdown.
  1291. const uniqueSuppliers = useMemo(() => {
  1292. const byId = new Map<number, string>();
  1293. for (const s of spools ?? []) {
  1294. for (const link of s.suppliers ?? []) {
  1295. byId.set(link.supplier_id, link.supplier_name);
  1296. }
  1297. }
  1298. return [...byId.entries()].map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name));
  1299. }, [spools]);
  1300. const hasUnsupplied = (spools ?? []).some((s) => (s.suppliers ?? []).length === 0);
  1301. const uniqueSpoolCatalogIds = [...new Set(spools?.map((s) => s.core_weight_catalog_id).filter((id): id is number => id != null) || [])].sort((a, b) => {
  1302. const nameA = (catalogMap[a]?.name || '').toLowerCase();
  1303. const nameB = (catalogMap[b]?.name || '').toLowerCase();
  1304. return nameA.localeCompare(nameB);
  1305. });
  1306. // #1400: storage-location distinct values. `.trim()` so accidental
  1307. // trailing whitespace doesn't show up as a separate option.
  1308. const hasUnsetStorageLocation = (spools ?? []).some((s) => !s.location_id && !s.storage_location?.trim());
  1309. // Check if any filters are non-default
  1310. const hasActiveFilters = archiveFilter !== 'active' || usageFilter !== 'all' || !!materialFilter || !!brandFilter || !!categoryFilter || !!supplierFilter || !!spoolFilter || !!storageLocationFilter || stockFilter !== 'all' || !!search;
  1311. const handleColumnConfigSave = (config: ColumnConfig[]) => {
  1312. setColumnConfig(config);
  1313. saveColumnConfig(config);
  1314. };
  1315. // Visible column IDs in order
  1316. const visibleColumns = useMemo(
  1317. () => columnConfig.filter((c) => c.visible).map((c) => c.id),
  1318. [columnConfig]
  1319. );
  1320. const handleSort = (colId: string) => {
  1321. if (!columnSortValues[colId]) return; // Not sortable
  1322. setSortState((prev) => {
  1323. let next: SortState;
  1324. if (prev?.column === colId) {
  1325. // Toggle direction, or clear on third click
  1326. next = prev.direction === 'asc' ? { column: colId, direction: 'desc' } : null;
  1327. } else {
  1328. next = { column: colId, direction: 'asc' };
  1329. }
  1330. saveSortState(next);
  1331. return next;
  1332. });
  1333. resetPage();
  1334. };
  1335. // Sort filtered spools
  1336. const sortedSpools = useMemo(() => {
  1337. if (!sortState) return filteredSpools;
  1338. const extractor = columnSortValues[sortState.column];
  1339. if (!extractor) return filteredSpools;
  1340. const sorted = [...filteredSpools].sort((a, b) => {
  1341. const va = extractor(a, assignmentMap, locationReadingsMap);
  1342. const vb = extractor(b, assignmentMap, locationReadingsMap);
  1343. if (va < vb) return sortState.direction === 'asc' ? -1 : 1;
  1344. if (va > vb) return sortState.direction === 'asc' ? 1 : -1;
  1345. return 0;
  1346. });
  1347. return sorted;
  1348. }, [filteredSpools, sortState, assignmentMap, locationReadingsMap]);
  1349. // Group similar spools when toggle is active
  1350. const displayItems = useMemo((): DisplayItem[] => {
  1351. if (!groupSimilar) return sortedSpools.map((s) => ({ type: 'single' as const, spool: s }));
  1352. const groups = new Map<string, InventorySpool[]>();
  1353. for (const spool of sortedSpools) {
  1354. // Only group unused & unassigned spools
  1355. if (spool.weight_used > 0 || assignmentMap[spool.id]) {
  1356. // Will be added as singles in the walk below
  1357. } else {
  1358. const key = spoolGroupKey(spool);
  1359. const arr = groups.get(key);
  1360. if (arr) arr.push(spool);
  1361. else groups.set(key, [spool]);
  1362. }
  1363. }
  1364. const items: DisplayItem[] = [];
  1365. const processedKeys = new Set<string>();
  1366. // Walk sortedSpools order so groups appear at the position of their first member
  1367. for (const spool of sortedSpools) {
  1368. if (spool.weight_used > 0 || assignmentMap[spool.id]) {
  1369. items.push({ type: 'single', spool });
  1370. continue;
  1371. }
  1372. const key = spoolGroupKey(spool);
  1373. if (processedKeys.has(key)) continue;
  1374. processedKeys.add(key);
  1375. const members = groups.get(key)!;
  1376. if (members.length === 1) {
  1377. items.push({ type: 'single', spool: members[0] });
  1378. } else {
  1379. items.push({ type: 'group', key, spools: members, representative: members[0] });
  1380. }
  1381. }
  1382. return items;
  1383. }, [sortedSpools, groupSimilar, assignmentMap]);
  1384. // Pagination (after sorting) — pageSize -1 means "All"
  1385. const showAll = pageSize === -1;
  1386. const totalDisplayItems = displayItems.length;
  1387. const effectivePageSize = showAll ? totalDisplayItems || 1 : pageSize;
  1388. const totalPages = Math.max(1, Math.ceil(totalDisplayItems / effectivePageSize));
  1389. const safePageIndex = showAll ? 0 : Math.min(pageIndex, totalPages - 1);
  1390. const pagedItems = showAll
  1391. ? displayItems
  1392. : displayItems.slice(safePageIndex * effectivePageSize, (safePageIndex + 1) * effectivePageSize);
  1393. const toggleGroupSimilar = () => {
  1394. const next = !groupSimilar;
  1395. setGroupSimilar(next);
  1396. setExpandedGroups(new Set());
  1397. resetPage();
  1398. try { localStorage.setItem('bambuddy-inventory-group', String(next)); } catch { /* ignore */ }
  1399. };
  1400. const toggleGroupExpand = (key: string) => {
  1401. setExpandedGroups((prev) => {
  1402. const next = new Set(prev);
  1403. if (next.has(key)) next.delete(key);
  1404. else next.add(key);
  1405. return next;
  1406. });
  1407. };
  1408. const handlePageSizeChange = (size: number) => {
  1409. setPageSize(size);
  1410. setPageIndex(0);
  1411. try { localStorage.setItem('bambuddy-inventory-pageSize', String(size)); } catch { /* ignore */ }
  1412. };
  1413. const clearAllFilters = () => {
  1414. setArchiveFilter('active');
  1415. setUsageFilter('all');
  1416. setMaterialFilter('');
  1417. setBrandFilter('');
  1418. setCategoryFilter('');
  1419. setSupplierFilter('');
  1420. setSpoolFilter('');
  1421. setStockFilter('all');
  1422. setSearch('');
  1423. setSearchParams((prev) => {
  1424. prev.delete('location_id');
  1425. return prev;
  1426. }, { replace: true });
  1427. resetPage();
  1428. };
  1429. return (
  1430. <div className="p-4 md:p-8 space-y-6">
  1431. {/* Header. Stacks below sm and the actions wrap (#2813): five buttons
  1432. side by side are ~600px, and nothing in that row can shrink, so on a
  1433. phone the header pushed past the viewport and took the whole page
  1434. with it -- <main> is the scroll container, so everything inside it
  1435. panned sideways. Same pattern the Statistics, Settings and Archives
  1436. headers use, and the filter bar further down this page. */}
  1437. <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
  1438. <div>
  1439. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  1440. <Package className="w-7 h-7 text-bambu-green" />
  1441. {t('inventory.title')}
  1442. </h1>
  1443. <p className="text-bambu-gray mt-1">{t('inventory.subtitle')}</p>
  1444. </div>
  1445. <div className="flex flex-wrap items-center gap-2">
  1446. {/* CSV import/export (#1576). Operates on Bambuddy's local inventory.
  1447. In Spoolman mode the buttons stay visible (feature parity) but are
  1448. disabled with a hint pointing at Spoolman's own CSV export, since
  1449. Spoolman owns the data store in that mode. */}
  1450. <Button
  1451. variant="secondary"
  1452. disabled={spoolmanMode}
  1453. onClick={() => setCsvImportOpen(true)}
  1454. title={spoolmanCsvHint}
  1455. >
  1456. <Upload className="w-4 h-4" />
  1457. {t('inventory.csv.importButton', 'Import CSV')}
  1458. </Button>
  1459. <Button
  1460. variant="secondary"
  1461. disabled={spoolmanMode || exportingCsv}
  1462. onClick={handleExportCsv}
  1463. title={spoolmanCsvHint}
  1464. >
  1465. {exportingCsv ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
  1466. {t('inventory.csv.exportButton', 'Export CSV')}
  1467. </Button>
  1468. <Button variant="secondary" onClick={() => setLocationsModalOpen(true)}>
  1469. <MapPin className="w-4 h-4" />
  1470. {t('locations.manage')}
  1471. </Button>
  1472. {/* Suppliers (#2988): inventory master data like Locations, so the
  1473. modal opens from the same toolbar — in both inventory modes. */}
  1474. <Button variant="secondary" onClick={() => setSuppliersModalOpen(true)}>
  1475. <Store className="w-4 h-4" />
  1476. {t('inventory.suppliers.title')}
  1477. </Button>
  1478. <Button
  1479. variant="secondary"
  1480. disabled={filteredSpools.length === 0}
  1481. // Pre-select every visible spool so the user lands in "all
  1482. // checked", then refines downward in the modal. Per-card icon
  1483. // pre-selects only that spool — both flows share the same picker.
  1484. onClick={() => setLabelPickerSpoolIds(filteredSpools.map((s) => s.id))}
  1485. title={
  1486. filteredSpools.length === 0
  1487. ? t('inventory.labels.noSpoolsTitle', 'No spools to label')
  1488. : t('inventory.labels.bulkTitle', 'Pick spools to print labels for from the {{count}} currently shown', { count: filteredSpools.length })
  1489. }
  1490. >
  1491. <Printer className="w-4 h-4" />
  1492. {t('inventory.labels.printLabels', 'Print labels…')}
  1493. </Button>
  1494. <Button onClick={() => setFormModal({ spool: null, mode: 'create' })}>
  1495. <Plus className="w-4 h-4" />
  1496. {t('inventory.addSpool')}
  1497. </Button>
  1498. </div>
  1499. </div>
  1500. {/* Stats Bar */}
  1501. {stats && !isLoading && (
  1502. <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
  1503. {/* Total Inventory */}
  1504. <div className="bg-bambu-dark-secondary rounded-lg p-4">
  1505. <div className="flex items-center gap-2 mb-1">
  1506. <Package className="w-4 h-4 text-bambu-green" />
  1507. <span className="text-xs text-bambu-gray font-medium uppercase tracking-wide">{t('inventory.totalInventory')}</span>
  1508. </div>
  1509. <div className="text-xl font-bold text-white">{formatWeight(stats.totalWeight, true)}</div>
  1510. <div className="text-xs text-bambu-gray mt-1">{stats.totalSpools} {stats.totalSpools !== 1 ? t('inventory.spools') : t('inventory.spool')}</div>
  1511. </div>
  1512. {/* Total Consumed */}
  1513. <div className="bg-bambu-dark-secondary rounded-lg p-4">
  1514. <div className="flex items-center justify-between gap-2 mb-1">
  1515. <div className="flex items-center gap-2">
  1516. <TrendingDown className="w-4 h-4 text-blue-600 dark:text-blue-400" />
  1517. <span className="text-xs text-bambu-gray font-medium uppercase tracking-wide">{t('inventory.totalConsumed')}</span>
  1518. </div>
  1519. {stats.totalConsumed > 0 && resetableSpoolIds.length > 0 && (
  1520. <button
  1521. onClick={() => setConfirmAction({ type: 'reset-all-consumed-counters' })}
  1522. className="p-1 text-bambu-gray hover:text-red-600 dark:hover:text-red-400 rounded transition-colors"
  1523. title={t('inventory.resetAllConsumedCountersTooltip')}
  1524. aria-label={t('inventory.resetAllConsumedCounters')}
  1525. >
  1526. <Eraser className="w-3.5 h-3.5" />
  1527. </button>
  1528. )}
  1529. </div>
  1530. <div className="text-xl font-bold text-white">{formatWeight(stats.totalConsumed, true)}</div>
  1531. <div className="text-xs text-bambu-gray mt-1">{t('inventory.sinceTracking')}</div>
  1532. </div>
  1533. {/* By Material */}
  1534. <div className="bg-bambu-dark-secondary rounded-lg p-4">
  1535. <div className="flex items-center gap-2 mb-1">
  1536. <Layers className="w-4 h-4 text-green-600 dark:text-green-400" />
  1537. <span className="text-xs text-bambu-gray font-medium uppercase tracking-wide">{t('inventory.byMaterial')}</span>
  1538. </div>
  1539. <div className="flex flex-wrap gap-1.5 mt-1">
  1540. {topMaterials.map(([mat, data]) => (
  1541. <span
  1542. key={mat}
  1543. className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${MATERIAL_COLORS[mat] || 'bg-bambu-dark-tertiary text-bambu-gray'}`}
  1544. >
  1545. {mat} <span className="opacity-70">{formatWeight(data.weight, true)}</span>
  1546. </span>
  1547. ))}
  1548. </div>
  1549. </div>
  1550. {/* In Printer */}
  1551. <div className="bg-bambu-dark-secondary rounded-lg p-4">
  1552. <div className="flex items-center gap-2 mb-1">
  1553. <Printer className="w-4 h-4 text-purple-600 dark:text-purple-400" />
  1554. <span className="text-xs text-bambu-gray font-medium uppercase tracking-wide">{t('inventory.inPrinter')}</span>
  1555. </div>
  1556. <div className="text-xl font-bold text-white">{inPrinterCount}</div>
  1557. <div className="text-xs text-bambu-gray mt-1">{t('inventory.loadedInAms')}</div>
  1558. </div>
  1559. {/* Low Stock */}
  1560. <div className="bg-bambu-dark-secondary rounded-lg p-4">
  1561. <div className="flex items-center gap-2 mb-1">
  1562. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400" />
  1563. <span className="text-xs text-bambu-gray font-medium uppercase tracking-wide">{t('inventory.lowStock')}</span>
  1564. </div>
  1565. <div className={`text-xl font-bold ${stats.lowStock > 0 ? 'text-yellow-700 dark:text-yellow-400' : 'text-white'}`}>{stats.lowStock}</div>
  1566. <div className="text-xs text-bambu-gray mt-1 flex items-center gap-2">
  1567. {showThresholdInput ? (
  1568. <form
  1569. onSubmit={e => {
  1570. e.preventDefault();
  1571. const val = parseFloat(thresholdInput);
  1572. if (!isNaN(val) && val >= 0.1 && val <= 99.9) {
  1573. updateThresholdMutation.mutate(val);
  1574. } else {
  1575. showToast(t('inventory.lowStockThresholdError'), 'error');
  1576. }
  1577. }}
  1578. className="flex items-center gap-2"
  1579. >
  1580. <span className="text-xs text-bambu-gray">{'<'}</span>
  1581. <input
  1582. type="text"
  1583. inputMode="decimal"
  1584. pattern="^\d{0,2}(\.\d?)?$"
  1585. maxLength={4}
  1586. value={thresholdInput}
  1587. onChange={e => {
  1588. // Only allow up to 2 digits before decimal and 1 after
  1589. const val = e.target.value.replace(/[^\d.]/g, '');
  1590. if (/^\d{0,2}(\.\d?)?$/.test(val)) {
  1591. setThresholdInput(val);
  1592. }
  1593. }}
  1594. className="px-1.5 py-1 rounded border border-bambu-dark-tertiary text-xs text-white bg-bambu-dark-secondary focus:outline-none focus:border-bambu-green w-14 text-center"
  1595. onWheel={e => e.currentTarget.blur()}
  1596. disabled={updateThresholdMutation.isPending}
  1597. />
  1598. <span className="text-xs text-bambu-gray">%</span>
  1599. <Button type="submit" size="sm" disabled={updateThresholdMutation.isPending}>{t('common.save')}</Button>
  1600. <Button type="button" size="sm" variant="ghost" onClick={() => setShowThresholdInput(false)} disabled={updateThresholdMutation.isPending}>{t('common.cancel')}</Button>
  1601. </form>
  1602. ) : (
  1603. <>
  1604. <span className="text-bambu-gray">{'< '}{lowStockThreshold}%</span>
  1605. <button
  1606. className="p-1.5 text-bambu-gray hover:text-white rounded transition-colors"
  1607. title={t('common.edit')}
  1608. onClick={() => {
  1609. setThresholdInput(lowStockThreshold.toString());
  1610. setShowThresholdInput(true);
  1611. }}
  1612. >
  1613. <Edit2 className="w-4 h-4" />
  1614. </button>
  1615. </>
  1616. )}
  1617. </div>
  1618. </div>
  1619. </div>
  1620. )}
  1621. {/* Toolbar: Search + View toggle */}
  1622. <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
  1623. <div className={`relative flex-1 max-w-md ${viewMode === 'forecast' ? 'invisible pointer-events-none' : ''}`}>
  1624. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  1625. <input
  1626. type="text"
  1627. value={search}
  1628. onChange={(e) => { setSearch(e.target.value); resetPage(); }}
  1629. placeholder={t('inventory.search')}
  1630. className="w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  1631. />
  1632. {search && (
  1633. <button
  1634. onClick={() => { setSearch(''); resetPage(); }}
  1635. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  1636. >
  1637. <X className="w-4 h-4" />
  1638. </button>
  1639. )}
  1640. </div>
  1641. <div className="flex items-center gap-2">
  1642. {/* Columns button (table view only) */}
  1643. {viewMode === 'table' && (
  1644. <button
  1645. onClick={() => setShowColumnModal(true)}
  1646. className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors"
  1647. title={t('inventory.configureColumns')}
  1648. >
  1649. <Columns className="w-4 h-4" />
  1650. <span className="hidden sm:inline">{t('inventory.columns')}</span>
  1651. </button>
  1652. )}
  1653. {/* Group similar toggle — hidden in forecast mode */}
  1654. {viewMode !== 'forecast' && (
  1655. <button
  1656. onClick={toggleGroupSimilar}
  1657. className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${
  1658. groupSimilar
  1659. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1660. : 'text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1661. }`}
  1662. title={t('inventory.groupSimilar')}
  1663. >
  1664. <Group className="w-4 h-4" />
  1665. <span className="hidden sm:inline">{t('inventory.groupSimilar')}</span>
  1666. </button>
  1667. )}
  1668. {/* Table / Cards toggle */}
  1669. <div className="flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden">
  1670. <button
  1671. onClick={() => setViewMode('table')}
  1672. className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${
  1673. viewMode === 'table'
  1674. ? 'bg-bambu-green text-white'
  1675. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1676. }`}
  1677. >
  1678. <TableProperties className="w-4 h-4" />
  1679. <span className="hidden sm:inline">{t('inventory.table')}</span>
  1680. </button>
  1681. <button
  1682. onClick={() => setViewMode('cards')}
  1683. className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${
  1684. viewMode === 'cards'
  1685. ? 'bg-bambu-green text-white'
  1686. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1687. }`}
  1688. >
  1689. <LayoutGrid className="w-4 h-4" />
  1690. <span className="hidden sm:inline">{t('inventory.cards')}</span>
  1691. </button>
  1692. <button
  1693. onClick={() => canViewForecast && setViewMode('forecast')}
  1694. disabled={!canViewForecast}
  1695. title={canViewForecast ? undefined : t('forecast.noReadAccess')}
  1696. className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${
  1697. viewMode === 'forecast'
  1698. ? 'bg-bambu-green text-white'
  1699. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1700. }`}
  1701. >
  1702. {canViewForecast ? <TrendingUp className="w-4 h-4" /> : <Lock className="w-4 h-4" />}
  1703. <span className="hidden sm:inline">{t('forecast.title')}</span>
  1704. </button>
  1705. </div>
  1706. </div>
  1707. </div>
  1708. {/* Filter chips row — hidden in forecast mode */}
  1709. <div className={`flex flex-wrap items-center gap-2 ${viewMode === 'forecast' ? 'hidden' : ''}`}>
  1710. {/* Active / Archived chips */}
  1711. <div className="flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden">
  1712. <button
  1713. onClick={() => { setArchiveFilter('active'); resetPage(); }}
  1714. className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${
  1715. archiveFilter === 'active'
  1716. ? 'bg-bambu-green/20 text-bambu-green'
  1717. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1718. }`}
  1719. >
  1720. <Package className="w-3.5 h-3.5" />
  1721. {t('inventory.active')}
  1722. </button>
  1723. <button
  1724. onClick={() => { setArchiveFilter('archived'); resetPage(); }}
  1725. className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${
  1726. archiveFilter === 'archived'
  1727. ? 'bg-bambu-green/20 text-bambu-green'
  1728. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1729. }`}
  1730. >
  1731. <Archive className="w-3.5 h-3.5" />
  1732. {t('inventory.archived')}
  1733. </button>
  1734. </div>
  1735. <div className="w-px h-5 bg-bambu-dark-tertiary" />
  1736. {/* All / Used / New chips */}
  1737. <div className="flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden">
  1738. <button
  1739. onClick={() => { setUsageFilter('all'); resetPage(); }}
  1740. className={`px-3 py-1.5 text-xs font-medium transition-colors ${
  1741. usageFilter === 'all'
  1742. ? 'bg-bambu-green/20 text-bambu-green'
  1743. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1744. }`}
  1745. >
  1746. {t('inventory.all')}
  1747. </button>
  1748. <button
  1749. onClick={() => { setUsageFilter('used'); resetPage(); }}
  1750. className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${
  1751. usageFilter === 'used'
  1752. ? 'bg-bambu-green/20 text-bambu-green'
  1753. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1754. }`}
  1755. >
  1756. <Clock className="w-3.5 h-3.5" />
  1757. {t('inventory.used')}
  1758. </button>
  1759. <button
  1760. onClick={() => { setUsageFilter('new'); resetPage(); }}
  1761. className={`px-3 py-1.5 text-xs font-medium transition-colors ${
  1762. usageFilter === 'new'
  1763. ? 'bg-bambu-green/20 text-bambu-green'
  1764. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1765. }`}
  1766. >
  1767. {t('inventory.new')}
  1768. </button>
  1769. <button
  1770. onClick={() => { setUsageFilter('lowstock'); resetPage(); }}
  1771. className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${
  1772. usageFilter === 'lowstock'
  1773. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  1774. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1775. }`}
  1776. >
  1777. <AlertTriangle className="w-3.5 h-3.5" />
  1778. {t('inventory.lowStock')}
  1779. </button>
  1780. </div>
  1781. {/* Stock filter chips */}
  1782. <div className="flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden">
  1783. <button
  1784. onClick={() => { setStockFilter('all'); resetPage(); }}
  1785. className={`px-3 py-1.5 text-xs font-medium transition-colors ${
  1786. stockFilter === 'all'
  1787. ? 'bg-bambu-green/20 text-bambu-green'
  1788. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1789. }`}
  1790. >
  1791. {t('inventory.all')}
  1792. </button>
  1793. <button
  1794. onClick={() => { setStockFilter('stock'); resetPage(); }}
  1795. className={`px-3 py-1.5 text-xs font-medium transition-colors ${
  1796. stockFilter === 'stock'
  1797. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  1798. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1799. }`}
  1800. >
  1801. {t('inventory.stock')}
  1802. </button>
  1803. <button
  1804. onClick={() => { setStockFilter('configured'); resetPage(); }}
  1805. className={`px-3 py-1.5 text-xs font-medium transition-colors ${
  1806. stockFilter === 'configured'
  1807. ? 'bg-bambu-green/20 text-bambu-green'
  1808. : 'text-bambu-gray hover:bg-bambu-dark-tertiary'
  1809. }`}
  1810. >
  1811. {t('inventory.configured')}
  1812. </button>
  1813. </div>
  1814. <div className="w-px h-5 bg-bambu-dark-tertiary" />
  1815. {/* Material dropdown chip */}
  1816. <select
  1817. value={materialFilter}
  1818. onChange={(e) => { setMaterialFilter(e.target.value); resetPage(); }}
  1819. className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${
  1820. materialFilter
  1821. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1822. : 'bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1823. }`}
  1824. >
  1825. <option value="">{t('inventory.material')}</option>
  1826. {uniqueMaterials.map((m) => (
  1827. <option key={m} value={m}>{m}</option>
  1828. ))}
  1829. </select>
  1830. {/* Brand dropdown chip */}
  1831. <select
  1832. value={brandFilter}
  1833. onChange={(e) => { setBrandFilter(e.target.value); resetPage(); }}
  1834. className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${
  1835. brandFilter
  1836. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1837. : 'bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1838. }`}
  1839. >
  1840. <option value="">{t('inventory.brand')}</option>
  1841. {uniqueBrands.map((b) => (
  1842. <option key={b} value={b}>{b}</option>
  1843. ))}
  1844. </select>
  1845. {/* Category dropdown chip (#729) — only render once at least one
  1846. spool carries a category, otherwise it's noise. */}
  1847. {(uniqueCategories.length > 0 || categoryFilter) && (
  1848. <select
  1849. value={categoryFilter}
  1850. onChange={(e) => { setCategoryFilter(e.target.value); resetPage(); }}
  1851. className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${
  1852. categoryFilter
  1853. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1854. : 'bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1855. }`}
  1856. >
  1857. <option value="">{t('inventory.category')}</option>
  1858. {uniqueCategories.map((c) => (
  1859. <option key={c} value={c}>{c}</option>
  1860. ))}
  1861. {hasUncategorized && (
  1862. <option value="__none__">{t('inventory.categoryNone')}</option>
  1863. )}
  1864. </select>
  1865. )}
  1866. {/* Supplier dropdown chip (#2988) — same render rule as the category
  1867. chip: hidden until at least one spool carries an assignment. */}
  1868. {(uniqueSuppliers.length > 0 || supplierFilter) && (
  1869. <select
  1870. value={supplierFilter}
  1871. onChange={(e) => { setSupplierFilter(e.target.value); resetPage(); }}
  1872. className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${
  1873. supplierFilter
  1874. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1875. : 'bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1876. }`}
  1877. >
  1878. <option value="">{t('inventory.suppliers.label')}</option>
  1879. {uniqueSuppliers.map((supplier) => (
  1880. <option key={supplier.id} value={String(supplier.id)}>{supplier.name}</option>
  1881. ))}
  1882. {hasUnsupplied && (
  1883. <option value="__none__">{t('inventory.suppliers.none')}</option>
  1884. )}
  1885. </select>
  1886. )}
  1887. {/* Spool name dropdown chip */}
  1888. {uniqueSpoolCatalogIds.length > 0 && (
  1889. <select
  1890. value={spoolFilter}
  1891. onChange={(e) => { setSpoolFilter(e.target.value); resetPage(); }}
  1892. className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${
  1893. spoolFilter
  1894. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1895. : 'bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1896. }`}
  1897. >
  1898. <option value="">{t('inventory.spoolName')}</option>
  1899. {uniqueSpoolCatalogIds.map((id) => (
  1900. <option key={id} value={id}>{catalogMap[id]?.name || `#${id}`}</option>
  1901. ))}
  1902. </select>
  1903. )}
  1904. {/* Storage location dropdown chip (#1400) — only render when at
  1905. least one spool carries a storage location, otherwise it's noise
  1906. (matches the category chip pattern). */}
  1907. {(storageLocations.length > 0 || storageLocationFilter) && (
  1908. <select
  1909. value={storageLocationFilter}
  1910. onChange={(e) => { setStorageLocationFilter(e.target.value); }}
  1911. className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${
  1912. storageLocationFilter
  1913. ? 'bg-bambu-green/20 text-bambu-green border-bambu-green/30'
  1914. : 'bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary'
  1915. }`}
  1916. >
  1917. <option value="">{t('inventory.storageLocation')}</option>
  1918. {storageLocations.map((loc) => (
  1919. <option key={loc.id} value={String(loc.id)}>{loc.name}</option>
  1920. ))}
  1921. {hasUnsetStorageLocation && (
  1922. <option value="__none__">{t('inventory.storageLocationNone')}</option>
  1923. )}
  1924. </select>
  1925. )}
  1926. {/* Clear filters */}
  1927. {hasActiveFilters && (
  1928. <>
  1929. <div className="w-px h-5 bg-bambu-dark-tertiary" />
  1930. <button
  1931. onClick={clearAllFilters}
  1932. className="flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors"
  1933. >
  1934. <X className="w-3.5 h-3.5" />
  1935. {t('inventory.clearFilters')}
  1936. </button>
  1937. </>
  1938. )}
  1939. {/* Results count — hidden in forecast mode */}
  1940. {viewMode !== 'forecast' && (
  1941. <span className="ml-auto text-xs text-bambu-gray">
  1942. {sortedSpools.length} {sortedSpools.length !== 1 ? t('inventory.spools') : t('inventory.spool')}
  1943. {groupSimilar && totalDisplayItems < sortedSpools.length && ` (${totalDisplayItems} ${t('inventory.groupedRows')})`}
  1944. </span>
  1945. )}
  1946. </div>
  1947. {/* Bulk action toolbar (#1795). Appears as soon as at least one
  1948. spool is selected; sticky so it stays visible while the user
  1949. scrolls a long list. */}
  1950. {selectedIds.size > 0 && viewMode !== 'forecast' && (
  1951. <div className="sticky top-2 z-10 mb-4 flex items-center gap-2 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg backdrop-blur-sm">
  1952. <span className="text-sm text-bambu-green font-medium">
  1953. {t('inventory.bulk.selectionCount', { count: selectedIds.size })}
  1954. </span>
  1955. <div className="ml-auto flex flex-wrap items-center gap-2">
  1956. <Button size="sm" variant="secondary" onClick={() => setBulkEditOpen(true)}>
  1957. <Edit2 className="w-3.5 h-3.5 mr-1.5" />
  1958. {t('inventory.bulk.edit')}
  1959. </Button>
  1960. <Button size="sm" variant="secondary" onClick={() => setLabelPickerSpoolIds([...selectedIds])}>
  1961. <Printer className="w-3.5 h-3.5 mr-1.5" />
  1962. {t('inventory.bulk.printLabels')}
  1963. </Button>
  1964. <Button size="sm" variant="secondary" onClick={() => setBulkConfirmAction('reset-consumed-counter')}>
  1965. <Eraser className="w-3.5 h-3.5 mr-1.5" />
  1966. {t('inventory.bulk.resetUsage')}
  1967. </Button>
  1968. {archiveFilter === 'archived' ? (
  1969. <Button size="sm" variant="secondary" onClick={() => setBulkConfirmAction('restore')}>
  1970. <RotateCcw className="w-3.5 h-3.5 mr-1.5" />
  1971. {t('inventory.bulk.restore')}
  1972. </Button>
  1973. ) : (
  1974. <Button size="sm" variant="secondary" onClick={() => setBulkConfirmAction('archive')}>
  1975. <Archive className="w-3.5 h-3.5 mr-1.5" />
  1976. {t('inventory.bulk.archive')}
  1977. </Button>
  1978. )}
  1979. <Button size="sm" variant="danger" onClick={() => setBulkConfirmAction('delete')}>
  1980. <Trash2 className="w-3.5 h-3.5 mr-1.5" />
  1981. {t('inventory.bulk.delete')}
  1982. </Button>
  1983. <button
  1984. className="p-1.5 text-bambu-gray hover:text-white rounded transition-colors"
  1985. onClick={clearSelection}
  1986. title={t('inventory.bulk.clearSelection')}
  1987. aria-label={t('inventory.bulk.clearSelection')}
  1988. >
  1989. <X className="w-4 h-4" />
  1990. </button>
  1991. </div>
  1992. </div>
  1993. )}
  1994. {/* Content */}
  1995. {isLoading ? (
  1996. <div className="flex justify-center py-16">
  1997. <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
  1998. </div>
  1999. ) : viewMode === 'forecast' ? (
  2000. /* Forecast view */
  2001. <ForecastPanel spools={spools || []} />
  2002. ) : viewMode === 'cards' ? (
  2003. /* Cards view */
  2004. pagedItems.length > 0 ? (
  2005. <>
  2006. <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
  2007. {pagedItems.map((item) => {
  2008. if (item.type === 'group') {
  2009. const { key, spools: groupSpools, representative: rep } = item;
  2010. // Total remaining filament across the group (#1368) — the
  2011. // headline number for the collapsed card, vs one member's.
  2012. const groupRemaining = groupSpools.reduce(
  2013. (sum, s) => sum + Math.max(0, s.label_weight - s.weight_used),
  2014. 0,
  2015. );
  2016. const groupBannerStyle = buildFilamentBackground({
  2017. rgba: rep.rgba,
  2018. extraColors: rep.extra_colors,
  2019. effectType: rep.effect_type,
  2020. subtype: rep.subtype,
  2021. effectSize: 'groupheader',
  2022. });
  2023. const isExpanded = expandedGroups.has(key);
  2024. return (
  2025. <div key={`group-${key}`} className="col-span-full">
  2026. {/* Group header card */}
  2027. <div
  2028. className="bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-green/30 hover:border-bambu-green transition-colors cursor-pointer"
  2029. onClick={() => toggleGroupExpand(key)}
  2030. >
  2031. <div className="h-10 flex items-center px-4 gap-3" style={groupBannerStyle}>
  2032. <span className="bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium">
  2033. {resolveSpoolColorName(rep.color_name, rep.rgba, rep.color_name_is_synthesized) || '-'}
  2034. </span>
  2035. </div>
  2036. <div className="px-4 py-3 flex items-center justify-between">
  2037. <div className="flex items-center gap-3">
  2038. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isExpanded ? '' : '-rotate-90'}`} />
  2039. <div>
  2040. <h3 className="font-semibold text-white">{rep.material}{rep.subtype ? ` ${rep.subtype}` : ''}</h3>
  2041. <p className="text-sm text-bambu-gray">{rep.brand || '-'}</p>
  2042. </div>
  2043. </div>
  2044. <div className="flex items-center gap-2">
  2045. <span className="text-sm text-bambu-gray" title={t('inventory.remaining')}>
  2046. {formatWeight(groupRemaining)}
  2047. </span>
  2048. <span className="text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full">
  2049. {t('inventory.groupedSpools', { count: groupSpools.length })}
  2050. </span>
  2051. </div>
  2052. </div>
  2053. </div>
  2054. {/* Expanded individual spools */}
  2055. {isExpanded && (
  2056. <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mt-2 ml-4">
  2057. {groupSpools.map((spool) => {
  2058. const remaining = Math.max(0, spool.label_weight - spool.weight_used);
  2059. const pct = spool.label_weight > 0 ? (remaining / spool.label_weight) * 100 : 0;
  2060. return (
  2061. <SpoolCard
  2062. key={spool.id}
  2063. spool={spool}
  2064. remaining={remaining}
  2065. pct={pct}
  2066. onClick={() => setFormModal({ spool, mode: 'edit' })}
  2067. onPrintLabel={() => setLabelPickerSpoolIds([spool.id])}
  2068. onCopy={() => setFormModal({ spool: spool, mode: 'copy' })}
  2069. t={t}
  2070. colorizeLocationSensors={colorizeLocationSensors}
  2071. locationSensorAboveColor={locationSensorAboveColor}
  2072. locationSensorBelowColor={locationSensorBelowColor}
  2073. locationSensorOptimalColor={locationSensorOptimalColor}
  2074. />
  2075. );
  2076. })}
  2077. </div>
  2078. )}
  2079. </div>
  2080. );
  2081. }
  2082. const spool = item.spool;
  2083. const remaining = Math.max(0, spool.label_weight - spool.weight_used);
  2084. const pct = spool.label_weight > 0 ? (remaining / spool.label_weight) * 100 : 0;
  2085. return (
  2086. <SpoolCard
  2087. key={spool.id}
  2088. spool={spool}
  2089. remaining={remaining}
  2090. pct={pct}
  2091. onClick={() => setFormModal({ spool, mode: 'edit' })}
  2092. onPrintLabel={() => setLabelPickerSpoolIds([spool.id])}
  2093. onCopy={() => setFormModal({ spool: spool, mode: 'copy' })}
  2094. t={t}
  2095. colorizeLocationSensors={colorizeLocationSensors}
  2096. locationSensorAboveColor={locationSensorAboveColor}
  2097. locationSensorBelowColor={locationSensorBelowColor}
  2098. locationSensorOptimalColor={locationSensorOptimalColor}
  2099. />
  2100. );
  2101. })}
  2102. </div>
  2103. {/* Pagination for cards */}
  2104. <PaginationBar
  2105. pageIndex={safePageIndex}
  2106. pageSize={pageSize}
  2107. totalRows={totalDisplayItems}
  2108. totalPages={totalPages}
  2109. onPageChange={setPageIndex}
  2110. onPageSizeChange={handlePageSizeChange}
  2111. t={t}
  2112. />
  2113. </>
  2114. ) : (
  2115. <EmptyFilterState
  2116. hasFilters={hasActiveFilters}
  2117. onAddSpool={() => setFormModal({ spool: null, mode: 'create' })}
  2118. t={t}
  2119. />
  2120. )
  2121. ) : (
  2122. /* Table view */
  2123. pagedItems.length > 0 ? (
  2124. <div className="bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary">
  2125. <div className="overflow-x-auto">
  2126. <table className="w-full">
  2127. <thead>
  2128. <tr className="border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30">
  2129. <th className="w-10 px-3 py-3">
  2130. <input
  2131. type="checkbox"
  2132. className="h-4 w-4 cursor-pointer"
  2133. aria-label={t('inventory.bulk.selectAllVisible')}
  2134. checked={pagedItems.length > 0 && pagedItems.every((item) => {
  2135. const ids = item.type === 'group' ? item.spools.map((s) => s.id) : [item.spool.id];
  2136. return ids.every((id) => selectedIds.has(id));
  2137. })}
  2138. onChange={(e) => {
  2139. if (e.target.checked) {
  2140. const next = new Set(selectedIds);
  2141. for (const item of pagedItems) {
  2142. const ids = item.type === 'group' ? item.spools.map((s) => s.id) : [item.spool.id];
  2143. for (const id of ids) next.add(id);
  2144. }
  2145. setSelectedIds(next);
  2146. } else {
  2147. const next = new Set(selectedIds);
  2148. for (const item of pagedItems) {
  2149. const ids = item.type === 'group' ? item.spools.map((s) => s.id) : [item.spool.id];
  2150. for (const id of ids) next.delete(id);
  2151. }
  2152. setSelectedIds(next);
  2153. }
  2154. }}
  2155. />
  2156. </th>
  2157. {visibleColumns.map((colId) => {
  2158. const sortable = !!columnSortValues[colId];
  2159. const isActive = sortState?.column === colId;
  2160. return (
  2161. <th
  2162. key={colId}
  2163. className={`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${colId === 'remaining' ? 'min-w-[150px]' : ''} ${
  2164. sortable ? 'cursor-pointer hover:text-bambu-green transition-colors' : ''
  2165. } ${isActive ? 'text-bambu-green' : 'text-bambu-gray'}`}
  2166. onClick={sortable ? () => handleSort(colId) : undefined}
  2167. >
  2168. <span className="inline-flex items-center gap-1">
  2169. {columnHeaders[colId]?.(t) ?? colId}
  2170. {sortable && (
  2171. isActive
  2172. ? sortState.direction === 'asc'
  2173. ? <ArrowUp className="w-3 h-3" />
  2174. : <ArrowDown className="w-3 h-3" />
  2175. : <ArrowUpDown className="w-3 h-3 opacity-30" />
  2176. )}
  2177. </span>
  2178. </th>
  2179. );
  2180. })}
  2181. <th className="text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide">{t('common.actions')}</th>
  2182. </tr>
  2183. </thead>
  2184. <tbody>
  2185. {pagedItems.map((item) => {
  2186. if (item.type === 'group') {
  2187. const { key, spools: groupSpools } = item;
  2188. const isExpanded = expandedGroups.has(key);
  2189. // Header row shows group totals (#1368): an aggregate
  2190. // spool plus remaining / pct summed across all members.
  2191. const headerSpool = aggregateGroupSpool(groupSpools);
  2192. const remaining = Math.max(0, headerSpool.label_weight - headerSpool.weight_used);
  2193. const pct = headerSpool.label_weight > 0 ? (remaining / headerSpool.label_weight) * 100 : 0;
  2194. return (
  2195. <SpoolTableGroup
  2196. key={`group-${key}`}
  2197. spools={groupSpools}
  2198. headerSpool={headerSpool}
  2199. remaining={remaining}
  2200. pct={pct}
  2201. isExpanded={isExpanded}
  2202. onToggle={() => toggleGroupExpand(key)}
  2203. selectedIds={selectedIds}
  2204. onToggleSelected={toggleSelected}
  2205. onToggleGroupSelected={(ids, select) => {
  2206. setSelectedIds((prev) => {
  2207. const next = new Set(prev);
  2208. for (const id of ids) {
  2209. if (select) next.add(id);
  2210. else next.delete(id);
  2211. }
  2212. return next;
  2213. });
  2214. }}
  2215. onEdit={(s) => setFormModal({ spool: s, mode: 'edit' })}
  2216. onCopy={(s) => setFormModal({ spool: s, mode: 'copy' })}
  2217. onArchive={(id) => setConfirmAction({ type: 'archive', spoolId: id })}
  2218. onDelete={(id) => setConfirmAction({ type: 'delete', spoolId: id })}
  2219. onPrintLabel={(id) => setLabelPickerSpoolIds([id])}
  2220. onResetConsumedCounter={(id) => setConfirmAction({ type: 'reset-consumed-counter', spoolId: id })}
  2221. visibleColumns={visibleColumns}
  2222. assignmentMap={assignmentMap}
  2223. catalogMap={catalogMap}
  2224. locationReadingsMap={locationReadingsMap}
  2225. currencySymbol={currencySymbol}
  2226. dateFormat={dateFormat}
  2227. t={t}
  2228. onSyncWeight={handleSyncWeight}
  2229. colorizeLocationSensors={colorizeLocationSensors}
  2230. locationSensorAboveColor={locationSensorAboveColor}
  2231. locationSensorBelowColor={locationSensorBelowColor}
  2232. locationSensorOptimalColor={locationSensorOptimalColor}
  2233. />
  2234. );
  2235. }
  2236. const spool = item.spool;
  2237. const remaining = Math.max(0, spool.label_weight - spool.weight_used);
  2238. const pct = spool.label_weight > 0 ? (remaining / spool.label_weight) * 100 : 0;
  2239. return (
  2240. <SpoolTableRow
  2241. key={spool.id}
  2242. spool={spool}
  2243. remaining={remaining}
  2244. pct={pct}
  2245. isSelected={selectedIds.has(spool.id)}
  2246. onToggleSelected={() => toggleSelected(spool.id)}
  2247. onEdit={() => setFormModal({ spool, mode: 'edit' })}
  2248. onCopy={() => setFormModal({ spool: spool, mode: 'copy' })}
  2249. onRestore={() => restoreMutation.mutate(spool.id)}
  2250. onArchive={() => setConfirmAction({ type: 'archive', spoolId: spool.id })}
  2251. onDelete={() => setConfirmAction({ type: 'delete', spoolId: spool.id })}
  2252. onPrintLabel={() => setLabelPickerSpoolIds([spool.id])}
  2253. onResetConsumedCounter={() => setConfirmAction({ type: 'reset-consumed-counter', spoolId: spool.id })}
  2254. visibleColumns={visibleColumns}
  2255. assignmentMap={assignmentMap}
  2256. catalogMap={catalogMap}
  2257. locationReadingsMap={locationReadingsMap}
  2258. currencySymbol={currencySymbol}
  2259. dateFormat={dateFormat}
  2260. t={t}
  2261. onSyncWeight={handleSyncWeight}
  2262. colorizeLocationSensors={colorizeLocationSensors}
  2263. locationSensorAboveColor={locationSensorAboveColor}
  2264. locationSensorBelowColor={locationSensorBelowColor}
  2265. locationSensorOptimalColor={locationSensorOptimalColor}
  2266. />
  2267. );
  2268. })}
  2269. </tbody>
  2270. </table>
  2271. </div>
  2272. {/* Pagination inside card footer */}
  2273. <div className="flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm">
  2274. <span className="text-bambu-gray">
  2275. {showAll
  2276. ? `${totalDisplayItems} ${totalDisplayItems !== 1 ? t('inventory.spools') : t('inventory.spool')}`
  2277. : <>{t('inventory.showing')} {safePageIndex * effectivePageSize + 1} {t('inventory.to')}{' '}
  2278. {Math.min((safePageIndex + 1) * effectivePageSize, totalDisplayItems)}{' '}
  2279. {t('inventory.of')} {totalDisplayItems} {t('inventory.spools')}</>
  2280. }
  2281. </span>
  2282. <div className="flex items-center gap-2">
  2283. <span className="text-bambu-gray">{t('inventory.show')}</span>
  2284. <select
  2285. value={pageSize}
  2286. onChange={(e) => handlePageSizeChange(Number(e.target.value))}
  2287. className="px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green"
  2288. >
  2289. {[15, 30, 50, 100].map((n) => (
  2290. <option key={n} value={n}>{n}</option>
  2291. ))}
  2292. <option value={-1}>{t('inventory.all')}</option>
  2293. </select>
  2294. {!showAll && (
  2295. <>
  2296. <button
  2297. onClick={() => setPageIndex(0)}
  2298. disabled={safePageIndex === 0}
  2299. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2300. title="First page"
  2301. >
  2302. <ChevronsLeft className="w-4 h-4" />
  2303. </button>
  2304. <button
  2305. onClick={() => setPageIndex((p) => Math.max(0, p - 1))}
  2306. disabled={safePageIndex === 0}
  2307. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2308. >
  2309. <ChevronLeft className="w-4 h-4" />
  2310. </button>
  2311. <span className="text-bambu-gray px-2 whitespace-nowrap">
  2312. {t('inventory.page')} {safePageIndex + 1} {t('inventory.of')} {totalPages}
  2313. </span>
  2314. <button
  2315. onClick={() => setPageIndex((p) => Math.min(totalPages - 1, p + 1))}
  2316. disabled={safePageIndex >= totalPages - 1}
  2317. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2318. >
  2319. <ChevronRight className="w-4 h-4" />
  2320. </button>
  2321. <button
  2322. onClick={() => setPageIndex(totalPages - 1)}
  2323. disabled={safePageIndex >= totalPages - 1}
  2324. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2325. title="Last page"
  2326. >
  2327. <ChevronsRight className="w-4 h-4" />
  2328. </button>
  2329. </>
  2330. )}
  2331. </div>
  2332. </div>
  2333. </div>
  2334. ) : (
  2335. <EmptyFilterState
  2336. hasFilters={hasActiveFilters}
  2337. onAddSpool={() => setFormModal({ spool: null, mode: 'create' })}
  2338. t={t}
  2339. />
  2340. )
  2341. )}
  2342. {/* Spool Form Modal */}
  2343. {formModal !== null && (
  2344. <SpoolFormModal
  2345. isOpen={true}
  2346. onClose={() => setFormModal(null)}
  2347. spool={formModal.spool}
  2348. mode={formModal.mode}
  2349. currencySymbol={currencySymbol}
  2350. spoolmanMode={spoolmanMode}
  2351. spoolsQueryKey={spoolsQueryKey}
  2352. />
  2353. )}
  2354. {/* Confirm Modal (delete / archive / reset-consumed-counter / reset-all-consumed-counters) */}
  2355. {confirmAction && (
  2356. <ConfirmModal
  2357. title={
  2358. confirmAction.type === 'delete' ? t('common.delete') :
  2359. confirmAction.type === 'archive' ? t('inventory.archive') :
  2360. confirmAction.type === 'reset-consumed-counter' ? t('inventory.resetConsumedCounter') :
  2361. t('inventory.resetAllConsumedCounters')
  2362. }
  2363. message={
  2364. confirmAction.type === 'delete' ? t('inventory.deleteConfirm') :
  2365. confirmAction.type === 'archive' ? t('inventory.archiveConfirm') :
  2366. confirmAction.type === 'reset-consumed-counter' ? t('inventory.resetConsumedCounterConfirm') :
  2367. t('inventory.resetAllConsumedCountersConfirm', { count: resetableSpoolIds.length })
  2368. }
  2369. confirmText={
  2370. confirmAction.type === 'delete' ? t('common.delete') :
  2371. confirmAction.type === 'archive' ? t('inventory.archive') :
  2372. t('inventory.resetConsumedCounter')
  2373. }
  2374. variant={confirmAction.type === 'archive' ? 'warning' : 'danger'}
  2375. onConfirm={() => {
  2376. if (confirmAction.type === 'delete') {
  2377. deleteMutation.mutate(confirmAction.spoolId);
  2378. } else if (confirmAction.type === 'archive') {
  2379. archiveMutation.mutate(confirmAction.spoolId);
  2380. } else if (confirmAction.type === 'reset-consumed-counter') {
  2381. resetConsumedCounterMutation.mutate(confirmAction.spoolId);
  2382. } else {
  2383. bulkResetConsumedCounterMutation.mutate(resetableSpoolIds);
  2384. }
  2385. setConfirmAction(null);
  2386. }}
  2387. onCancel={() => setConfirmAction(null)}
  2388. />
  2389. )}
  2390. {/* Column Config Modal */}
  2391. <ColumnConfigModal
  2392. isOpen={showColumnModal}
  2393. onClose={() => setShowColumnModal(false)}
  2394. columns={columnConfig}
  2395. defaultColumns={DEFAULT_COLUMNS}
  2396. onSave={handleColumnConfigSave}
  2397. />
  2398. <LabelTemplatePickerModal
  2399. isOpen={labelPickerSpoolIds !== null}
  2400. onClose={() => setLabelPickerSpoolIds(null)}
  2401. availableSpools={filteredSpools}
  2402. initialSelectedIds={labelPickerSpoolIds ?? []}
  2403. spoolmanMode={spoolmanMode}
  2404. />
  2405. <BulkEditSpoolsModal
  2406. isOpen={bulkEditOpen}
  2407. selectedCount={selectedIds.size}
  2408. isPending={bulkUpdateMutation.isPending}
  2409. availableLocations={storageLocations.map((l) => ({ id: l.id, name: l.name }))}
  2410. availableMaterials={dedupeAndSort((spools ?? []).map((s) => s.material))}
  2411. availableSubtypes={dedupeAndSort((spools ?? []).map((s) => s.subtype))}
  2412. availableBrands={dedupeAndSort((spools ?? []).map((s) => s.brand))}
  2413. availableCategories={dedupeAndSort((spools ?? []).map((s) => s.category))}
  2414. availableSlicerFilaments={dedupeAndSort((spools ?? []).map((s) => s.slicer_filament))}
  2415. availableSlicerFilamentNames={dedupeAndSort((spools ?? []).map((s) => s.slicer_filament_name))}
  2416. onClose={() => setBulkEditOpen(false)}
  2417. onApply={(patch) => bulkUpdateMutation.mutate({ ids: [...selectedIds], update: patch })}
  2418. />
  2419. {bulkConfirmAction && (
  2420. <ConfirmModal
  2421. title={
  2422. bulkConfirmAction === 'delete' ? t('inventory.bulk.deleteTitle') :
  2423. bulkConfirmAction === 'archive' ? t('inventory.bulk.archiveTitle') :
  2424. bulkConfirmAction === 'restore' ? t('inventory.bulk.restoreTitle') :
  2425. t('inventory.bulk.resetUsageTitle')
  2426. }
  2427. message={
  2428. bulkConfirmAction === 'delete' ? t('inventory.bulk.deleteMessage', { count: selectedIds.size }) :
  2429. bulkConfirmAction === 'archive' ? t('inventory.bulk.archiveMessage', { count: selectedIds.size }) :
  2430. bulkConfirmAction === 'restore' ? t('inventory.bulk.restoreMessage', { count: selectedIds.size }) :
  2431. t('inventory.bulk.resetUsageMessage', { count: selectedIds.size })
  2432. }
  2433. confirmText={
  2434. bulkConfirmAction === 'delete' ? t('common.delete') :
  2435. bulkConfirmAction === 'archive' ? t('inventory.archive') :
  2436. bulkConfirmAction === 'restore' ? t('inventory.restore') :
  2437. t('inventory.resetConsumedCounter')
  2438. }
  2439. variant={bulkConfirmAction === 'delete' ? 'danger' : 'warning'}
  2440. isLoading={
  2441. bulkDeleteMutation.isPending ||
  2442. bulkArchiveMutation.isPending ||
  2443. bulkRestoreMutation.isPending ||
  2444. bulkResetConsumedCounterMutation.isPending
  2445. }
  2446. onConfirm={() => {
  2447. const ids = [...selectedIds];
  2448. if (bulkConfirmAction === 'delete') bulkDeleteMutation.mutate(ids);
  2449. else if (bulkConfirmAction === 'archive') bulkArchiveMutation.mutate(ids);
  2450. else if (bulkConfirmAction === 'restore') bulkRestoreMutation.mutate(ids);
  2451. else bulkResetConsumedCounterMutation.mutate(ids);
  2452. }}
  2453. onCancel={() => setBulkConfirmAction(null)}
  2454. />
  2455. )}
  2456. {csvImportOpen && (
  2457. <SpoolCsvImportModal
  2458. onClose={() => setCsvImportOpen(false)}
  2459. onImported={(created) => {
  2460. setCsvImportOpen(false);
  2461. queryClient.invalidateQueries({ queryKey: spoolsQueryKey });
  2462. showToast(t('inventory.csv.importSuccess', '{{count}} spools imported', { count: created }), 'success');
  2463. }}
  2464. />
  2465. )}
  2466. <LocationsModal
  2467. open={locationsModalOpen}
  2468. onClose={() => setLocationsModalOpen(false)}
  2469. onPickLocation={(id) => setStorageLocationFilter(String(id))}
  2470. />
  2471. <SuppliersModal open={suppliersModalOpen} onClose={() => setSuppliersModalOpen(false)} />
  2472. </div>
  2473. );
  2474. }
  2475. /* Pagination bar (reused for cards view) */
  2476. function PaginationBar({
  2477. pageIndex, pageSize, totalRows, totalPages, onPageChange, onPageSizeChange, t,
  2478. }: {
  2479. pageIndex: number;
  2480. pageSize: number;
  2481. totalRows: number;
  2482. totalPages: number;
  2483. onPageChange: (page: number) => void;
  2484. onPageSizeChange: (size: number) => void;
  2485. t: (key: string) => string;
  2486. }) {
  2487. const isShowAll = pageSize === -1;
  2488. if (totalPages <= 1 && !isShowAll) return null;
  2489. const effectiveSize = isShowAll ? totalRows || 1 : pageSize;
  2490. return (
  2491. <div className="flex items-center justify-between pt-2 text-sm">
  2492. <span className="text-bambu-gray">
  2493. {isShowAll
  2494. ? `${totalRows} ${totalRows !== 1 ? t('inventory.spools') : t('inventory.spool')}`
  2495. : <>{t('inventory.showing')} {pageIndex * effectiveSize + 1} {t('inventory.to')}{' '}
  2496. {Math.min((pageIndex + 1) * effectiveSize, totalRows)}{' '}
  2497. {t('inventory.of')} {totalRows} {t('inventory.spools')}</>
  2498. }
  2499. </span>
  2500. <div className="flex items-center gap-2">
  2501. <span className="text-bambu-gray">{t('inventory.show')}</span>
  2502. <select
  2503. value={pageSize}
  2504. onChange={(e) => onPageSizeChange(Number(e.target.value))}
  2505. className="px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green"
  2506. >
  2507. {[15, 30, 50, 100].map((n) => (
  2508. <option key={n} value={n}>{n}</option>
  2509. ))}
  2510. <option value={-1}>{t('inventory.all')}</option>
  2511. </select>
  2512. {!isShowAll && (
  2513. <>
  2514. <button
  2515. onClick={() => onPageChange(0)}
  2516. disabled={pageIndex === 0}
  2517. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2518. >
  2519. <ChevronsLeft className="w-4 h-4" />
  2520. </button>
  2521. <button
  2522. onClick={() => onPageChange(Math.max(0, pageIndex - 1))}
  2523. disabled={pageIndex === 0}
  2524. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2525. >
  2526. <ChevronLeft className="w-4 h-4" />
  2527. </button>
  2528. <span className="text-bambu-gray px-2 whitespace-nowrap">
  2529. {t('inventory.page')} {pageIndex + 1} {t('inventory.of')} {totalPages}
  2530. </span>
  2531. <button
  2532. onClick={() => onPageChange(Math.min(totalPages - 1, pageIndex + 1))}
  2533. disabled={pageIndex >= totalPages - 1}
  2534. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2535. >
  2536. <ChevronRight className="w-4 h-4" />
  2537. </button>
  2538. <button
  2539. onClick={() => onPageChange(totalPages - 1)}
  2540. disabled={pageIndex >= totalPages - 1}
  2541. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  2542. >
  2543. <ChevronsRight className="w-4 h-4" />
  2544. </button>
  2545. </>
  2546. )}
  2547. </div>
  2548. </div>
  2549. );
  2550. }
  2551. /* Spool card for cards view */
  2552. function SpoolCard({
  2553. spool, remaining, pct, onClick, onPrintLabel, onCopy, t,
  2554. colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor,
  2555. }: {
  2556. spool: InventorySpool;
  2557. remaining: number;
  2558. pct: number;
  2559. onClick: () => void;
  2560. onPrintLabel?: () => void;
  2561. onCopy?: () => void;
  2562. t: (key: string, opts?: Record<string, unknown>) => string;
  2563. colorizeLocationSensors: boolean;
  2564. locationSensorAboveColor: LocationSensorAlertColor;
  2565. locationSensorBelowColor: LocationSensorAlertColor;
  2566. locationSensorOptimalColor: LocationSensorAlertColor;
  2567. }) {
  2568. const bannerStyle = buildFilamentBackground({
  2569. rgba: spool.rgba,
  2570. extraColors: spool.extra_colors,
  2571. effectType: spool.effect_type,
  2572. subtype: spool.subtype,
  2573. effectSize: 'card',
  2574. });
  2575. return (
  2576. <div
  2577. className={`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${spool.archived_at ? 'opacity-50' : ''}`}
  2578. onClick={onClick}
  2579. >
  2580. <div className="h-14 flex items-center justify-center" style={bannerStyle}>
  2581. <span className="bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium">
  2582. {resolveSpoolColorName(spool.color_name, spool.rgba, spool.color_name_is_synthesized) || '-'}
  2583. </span>
  2584. {onCopy && (
  2585. <button
  2586. type="button"
  2587. onClick={(e) => { e.stopPropagation(); onCopy(); }}
  2588. className="p-1.5 bg-black/20 hover:bg-black/40 text-white rounded-full transition-colors"
  2589. title={t('inventory.copySpool')}
  2590. >
  2591. <Copy className="w-3.5 h-3.5" />
  2592. </button>
  2593. )}
  2594. </div>
  2595. <div className="p-4 space-y-3">
  2596. <div className="flex items-start justify-between gap-2">
  2597. <div>
  2598. <h3 className="font-semibold text-white">
  2599. {spool.material}{spool.subtype ? ` ${spool.subtype}` : ''}
  2600. </h3>
  2601. <p className="text-sm text-bambu-gray">{spool.brand || '-'}</p>
  2602. </div>
  2603. <div className="flex items-center gap-1">
  2604. {onPrintLabel && (
  2605. <button
  2606. onClick={(e) => { e.stopPropagation(); onPrintLabel(); }}
  2607. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  2608. title={t('inventory.labels.printOne')}
  2609. aria-label={t('inventory.labels.printOne')}
  2610. >
  2611. <Printer className="w-4 h-4" />
  2612. </button>
  2613. )}
  2614. <span className="text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  2615. #{spool.id}
  2616. </span>
  2617. </div>
  2618. </div>
  2619. <div>
  2620. <div className="flex justify-between text-xs text-bambu-gray mb-1">
  2621. <span>{t('inventory.remaining')}</span>
  2622. <span>{Math.round(pct)}%</span>
  2623. </div>
  2624. <div className="flex items-center gap-2">
  2625. <div className="flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden">
  2626. <div
  2627. className={`h-full rounded-full ${pct > 50 ? 'bg-bambu-green' : pct > 20 ? 'bg-yellow-500' : 'bg-red-500'}`}
  2628. style={{ width: `${Math.min(pct, 100)}%` }}
  2629. />
  2630. </div>
  2631. <span className="text-xs text-bambu-gray min-w-[40px] text-right">
  2632. {Math.round(remaining)}g
  2633. </span>
  2634. </div>
  2635. </div>
  2636. <div className="grid grid-cols-2 gap-2 text-xs">
  2637. <div>
  2638. <span className="text-bambu-gray/60">{t('inventory.labelWeight')}: </span>
  2639. <span className="text-bambu-gray">{formatWeight(spool.label_weight)}</span>
  2640. </div>
  2641. <div>
  2642. <span className="text-bambu-gray/60">{t('inventory.weightUsed')}: </span>
  2643. <span className="text-bambu-gray">
  2644. {spool.weight_used > 0 ? formatWeight(spool.weight_used) : '-'}
  2645. </span>
  2646. </div>
  2647. </div>
  2648. {spool.location_id && (
  2649. <SpoolLocationFooter
  2650. locationId={spool.location_id}
  2651. locationName={spool.storage_location ?? null}
  2652. isLast={!spool.note}
  2653. colorize={colorizeLocationSensors}
  2654. aboveColor={locationSensorAboveColor}
  2655. belowColor={locationSensorBelowColor}
  2656. optimalColor={locationSensorOptimalColor}
  2657. />
  2658. )}
  2659. {spool.note && (
  2660. <div
  2661. className="text-xs text-bambu-gray/60 pt-3 border-t border-bambu-dark-tertiary truncate"
  2662. title={spool.note}
  2663. >
  2664. {spool.note}
  2665. </div>
  2666. )}
  2667. </div>
  2668. </div>
  2669. );
  2670. }
  2671. const LOCATION_SENSOR_CATEGORY_ORDER: Record<string, number> = {
  2672. temperature: 0,
  2673. humidity: 1,
  2674. battery: 2,
  2675. };
  2676. function locationSensorIconGapClass(deviceClass: string | null): string {
  2677. if (deviceClass === 'humidity') return 'mr-[2px]';
  2678. if (deviceClass === 'battery') return 'mr-[3px]';
  2679. return '';
  2680. }
  2681. // Two decimal places, unlike the printer row's raw value: keeps
  2682. // temperature/humidity/battery cells at a consistent width in the table and
  2683. // card grid (see describeHASensorReading's doc comment).
  2684. function describeLocationSensor(
  2685. reading: LocationHASensorReading,
  2686. t: (key: string, opts?: Record<string, unknown>) => string
  2687. ): string {
  2688. return describeHASensorReading(reading, t, { decimals: 2 });
  2689. }
  2690. function locationSensorCellColor(
  2691. reading: LocationHASensorReading,
  2692. colorize: boolean,
  2693. aboveColor: LocationSensorAlertColor,
  2694. belowColor: LocationSensorAlertColor,
  2695. optimalColor: LocationSensorAlertColor
  2696. ): string {
  2697. if (!colorize) return 'text-bambu-gray';
  2698. const status = locationSensorReadingAlertStatus(reading);
  2699. return locationSensorValueColorClass(status, aboveColor, belowColor, optimalColor) || 'text-bambu-gray';
  2700. }
  2701. function SpoolLocationFooter({
  2702. locationId, locationName, isLast, colorize, aboveColor, belowColor, optimalColor,
  2703. }: {
  2704. locationId: number;
  2705. locationName: string | null;
  2706. isLast: boolean;
  2707. colorize: boolean;
  2708. aboveColor: LocationSensorAlertColor;
  2709. belowColor: LocationSensorAlertColor;
  2710. optimalColor: LocationSensorAlertColor;
  2711. }) {
  2712. const { t } = useTranslation();
  2713. const { data: settings } = useQuery({ queryKey: ['settings'], queryFn: api.getSettings });
  2714. const pollIntervalMs = (settings?.location_sensor_poll_interval || 120) * 1000;
  2715. // Same query key as the list fetch in InventoryPage's body, so this is a
  2716. // cache read (no extra request) whenever that has already run — which it
  2717. // has, since card view and this footer only render after spools/locations
  2718. // are loaded.
  2719. const { data: sensorsList } = useQuery({
  2720. queryKey: ['locationHaSensors'],
  2721. queryFn: () => api.getLocationHASensors(),
  2722. });
  2723. const hasSensor = (sensorsList ?? []).some((s) => s.location_id === locationId);
  2724. // Same query key as the table-view columns' fetch in InventoryPage's body
  2725. // (unfiltered, show_on_card=false) — this is a cache read whenever that
  2726. // has already run, and the two views never need two different requests
  2727. // for one location. Filtering to card-visible sensors happens here
  2728. // instead of on the server.
  2729. const { data: allReadings } = useQuery({
  2730. queryKey: ['locationHaSensorReadings', locationId],
  2731. queryFn: () => api.getLocationHASensorReadings(locationId, false),
  2732. refetchInterval: pollIntervalMs,
  2733. enabled: hasSensor,
  2734. });
  2735. const readings = allReadings?.filter((r) => r.show_on_card);
  2736. if (!readings?.length) return null;
  2737. const batteryReading = readings.find((r) => r.device_class === 'battery');
  2738. const otherReadings = readings
  2739. .filter((r) => r.device_class !== 'battery')
  2740. .sort(
  2741. (a, b) =>
  2742. (LOCATION_SENSOR_CATEGORY_ORDER[a.device_class ?? ''] ?? 99) -
  2743. (LOCATION_SENSOR_CATEGORY_ORDER[b.device_class ?? ''] ?? 99)
  2744. );
  2745. return (
  2746. <div
  2747. className={`flex items-center gap-2 pt-3 border-t border-bambu-dark-tertiary text-xs text-bambu-gray ${isLast ? '-mb-1' : ''}`}
  2748. >
  2749. {locationName && <span className="truncate">{locationName}</span>}
  2750. <span className="text-bambu-gray/40">|</span>
  2751. <div className="flex items-center gap-3">
  2752. {otherReadings.map((reading, index) => {
  2753. const Icon = iconForHASensor(reading);
  2754. const firstIconOffsetClass = index === 0 ? 'ml-[-3.6px]' : '';
  2755. return (
  2756. <span key={reading.id} title={reading.name} className="flex items-center gap-[3px]">
  2757. <Icon className={`w-3 h-3 ${locationSensorIconGapClass(reading.device_class)} ${firstIconOffsetClass}`} />
  2758. <span className={locationSensorCellColor(reading, colorize, aboveColor, belowColor, optimalColor)}>
  2759. {describeLocationSensor(reading, t)}
  2760. </span>
  2761. </span>
  2762. );
  2763. })}
  2764. </div>
  2765. {batteryReading &&
  2766. (() => {
  2767. const Icon = iconForHASensor(batteryReading);
  2768. return (
  2769. <span key={batteryReading.id} title={batteryReading.name} className="flex items-center gap-[3px] ml-auto">
  2770. <Icon className={`w-3 h-3 ${locationSensorIconGapClass(batteryReading.device_class)}`} />
  2771. <span className={locationSensorCellColor(batteryReading, colorize, aboveColor, belowColor, optimalColor)}>
  2772. {describeLocationSensor(batteryReading, t)}
  2773. </span>
  2774. </span>
  2775. );
  2776. })()}
  2777. </div>
  2778. );
  2779. }
  2780. /* Single spool row for table view */
  2781. function SpoolTableRow({
  2782. spool, remaining, pct, isSelected, onToggleSelected,
  2783. onEdit, onCopy, onRestore, onArchive, onDelete, onPrintLabel, onResetConsumedCounter,
  2784. visibleColumns, assignmentMap, catalogMap, locationReadingsMap, currencySymbol, dateFormat, t, onSyncWeight,
  2785. colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor,
  2786. }: {
  2787. spool: InventorySpool;
  2788. remaining: number;
  2789. pct: number;
  2790. isSelected?: boolean;
  2791. onToggleSelected?: () => void;
  2792. onEdit: () => void;
  2793. onCopy?: () => void;
  2794. onRestore: () => void;
  2795. onArchive: () => void;
  2796. onDelete: () => void;
  2797. onPrintLabel?: () => void;
  2798. onResetConsumedCounter?: () => void;
  2799. visibleColumns: string[];
  2800. assignmentMap: Record<number, LocationDisplay>;
  2801. catalogMap: Record<number, SpoolCatalogEntry>;
  2802. locationReadingsMap: Record<number, LocationHASensorReading[]>;
  2803. currencySymbol: string;
  2804. dateFormat: DateFormat;
  2805. t: TFn;
  2806. onSyncWeight?: (spool: InventorySpool) => void;
  2807. colorizeLocationSensors: boolean;
  2808. locationSensorAboveColor: LocationSensorAlertColor;
  2809. locationSensorBelowColor: LocationSensorAlertColor;
  2810. locationSensorOptimalColor: LocationSensorAlertColor;
  2811. }) {
  2812. return (
  2813. <tr
  2814. className={`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${
  2815. spool.archived_at ? 'opacity-50' : ''
  2816. } ${isSelected ? 'bg-bambu-green/10' : ''}`}
  2817. onClick={onEdit}
  2818. >
  2819. <td className="w-10 px-3 py-3" onClick={(e) => e.stopPropagation()}>
  2820. {onToggleSelected && (
  2821. <input
  2822. type="checkbox"
  2823. className="h-4 w-4 cursor-pointer"
  2824. aria-label={t('inventory.bulk.selectRow')}
  2825. checked={!!isSelected}
  2826. onChange={onToggleSelected}
  2827. />
  2828. )}
  2829. </td>
  2830. {visibleColumns.map((colId) => (
  2831. <td key={colId} className="py-3 px-4">
  2832. {columnCells[colId]?.({ spool, remaining, pct, assignmentMap, catalogMap, locationReadingsMap, currencySymbol, dateFormat, t, onSyncWeight, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor })}
  2833. </td>
  2834. ))}
  2835. <td className="py-3 px-4">
  2836. <div className="flex items-center justify-end gap-1" onClick={(e) => e.stopPropagation()}>
  2837. <button onClick={onEdit} className="p-1.5 text-bambu-gray hover:text-white rounded transition-colors" title={t('common.edit')}>
  2838. <Edit2 className="w-4 h-4" />
  2839. </button>
  2840. {onCopy && (
  2841. <button onClick={onCopy} className="p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors" title={t('inventory.copySpool')}>
  2842. <Copy className="w-4 h-4" />
  2843. </button>
  2844. )}
  2845. {onPrintLabel && (
  2846. <button onClick={onPrintLabel} className="p-1.5 text-bambu-gray hover:text-white rounded transition-colors" title={t('inventory.labels.printOne')}>
  2847. <Printer className="w-4 h-4" />
  2848. </button>
  2849. )}
  2850. {onResetConsumedCounter && spool.weight_used > 0 && (
  2851. // Eraser also shows on archived spools (#1390 follow-up):
  2852. // archived consumed weight now counts in "Total Consumed", so
  2853. // the user needs a way to zero an archived spool's tracking
  2854. // counter individually without having to un-archive it first.
  2855. <button onClick={onResetConsumedCounter} className="p-1.5 text-bambu-gray hover:text-orange-600 dark:hover:text-orange-400 rounded transition-colors" title={t('inventory.resetConsumedCounterTooltip')}>
  2856. <Eraser className="w-4 h-4" />
  2857. </button>
  2858. )}
  2859. {spool.archived_at ? (
  2860. <button onClick={onRestore} className="p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors" title={t('inventory.restore')}>
  2861. <RotateCcw className="w-4 h-4" />
  2862. </button>
  2863. ) : (
  2864. <button onClick={onArchive} className="p-1.5 text-bambu-gray hover:text-yellow-600 dark:hover:text-yellow-400 rounded transition-colors" title={t('inventory.archive')}>
  2865. <Archive className="w-4 h-4" />
  2866. </button>
  2867. )}
  2868. <button onClick={onDelete} className="p-1.5 text-bambu-gray hover:text-red-600 dark:hover:text-red-400 rounded transition-colors" title={t('common.delete')}>
  2869. <Trash2 className="w-4 h-4" />
  2870. </button>
  2871. </div>
  2872. </td>
  2873. </tr>
  2874. );
  2875. }
  2876. /* Grouped spool rows for table view */
  2877. function SpoolTableGroup({
  2878. spools, headerSpool, remaining, pct, isExpanded, onToggle,
  2879. onEdit, onCopy, onArchive, onDelete, onPrintLabel, onResetConsumedCounter,
  2880. visibleColumns, assignmentMap, catalogMap, locationReadingsMap, currencySymbol, dateFormat, t, onSyncWeight,
  2881. colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor,
  2882. selectedIds, onToggleSelected, onToggleGroupSelected,
  2883. }: {
  2884. spools: InventorySpool[];
  2885. // Aggregate of all members (summed quantities, shared identity) — rendered
  2886. // in the collapsed header row so it shows group totals (#1368).
  2887. headerSpool: InventorySpool;
  2888. remaining: number;
  2889. pct: number;
  2890. isExpanded: boolean;
  2891. onToggle: () => void;
  2892. onEdit: (spool: InventorySpool) => void;
  2893. onCopy?: (spool: InventorySpool) => void;
  2894. onArchive: (id: number) => void;
  2895. onDelete: (id: number) => void;
  2896. onPrintLabel?: (spoolId: number) => void;
  2897. onResetConsumedCounter?: (id: number) => void;
  2898. visibleColumns: string[];
  2899. assignmentMap: Record<number, LocationDisplay>;
  2900. catalogMap: Record<number, SpoolCatalogEntry>;
  2901. locationReadingsMap: Record<number, LocationHASensorReading[]>;
  2902. currencySymbol: string;
  2903. dateFormat: DateFormat;
  2904. t: TFn;
  2905. onSyncWeight?: (spool: InventorySpool) => void;
  2906. colorizeLocationSensors: boolean;
  2907. locationSensorAboveColor: LocationSensorAlertColor;
  2908. locationSensorBelowColor: LocationSensorAlertColor;
  2909. locationSensorOptimalColor: LocationSensorAlertColor;
  2910. selectedIds?: Set<number>;
  2911. onToggleSelected?: (id: number) => void;
  2912. onToggleGroupSelected?: (ids: number[], select: boolean) => void;
  2913. }) {
  2914. const allMembersSelected = !!selectedIds && spools.every((s) => selectedIds.has(s.id));
  2915. return (
  2916. <>
  2917. {/* Group header row */}
  2918. <tr
  2919. className="border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer bg-bambu-green/5"
  2920. onClick={onToggle}
  2921. >
  2922. <td className="w-10 px-3 py-3" onClick={(e) => e.stopPropagation()}>
  2923. {onToggleGroupSelected && (
  2924. <input
  2925. type="checkbox"
  2926. className="h-4 w-4 cursor-pointer"
  2927. aria-label={t('inventory.bulk.selectGroup')}
  2928. checked={allMembersSelected}
  2929. onChange={(e) => onToggleGroupSelected(spools.map((s) => s.id), e.target.checked)}
  2930. />
  2931. )}
  2932. </td>
  2933. {visibleColumns.map((colId, idx) => (
  2934. <td key={colId} className="py-3 px-4">
  2935. {idx === 0 ? (
  2936. <div className="flex items-center gap-2">
  2937. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isExpanded ? '' : '-rotate-90'}`} />
  2938. {columnCells[colId]?.({ spool: headerSpool, remaining, pct, assignmentMap, catalogMap, locationReadingsMap, currencySymbol, dateFormat, t, onSyncWeight, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor })}
  2939. </div>
  2940. ) : colId === 'id' ? (
  2941. <span className="text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full">
  2942. {t('inventory.groupedSpools', { count: spools.length })}
  2943. </span>
  2944. ) : (
  2945. columnCells[colId]?.({ spool: headerSpool, remaining, pct, assignmentMap, catalogMap, locationReadingsMap, currencySymbol, dateFormat, t, onSyncWeight, colorizeLocationSensors, locationSensorAboveColor, locationSensorBelowColor, locationSensorOptimalColor })
  2946. )}
  2947. </td>
  2948. ))}
  2949. <td className="py-3 px-4">
  2950. <span className="text-xs text-bambu-gray">
  2951. {spools.map((s) => `#${s.id}`).join(', ')}
  2952. </span>
  2953. </td>
  2954. </tr>
  2955. {/* Expanded individual rows */}
  2956. {isExpanded && spools.map((spool) => {
  2957. const r = Math.max(0, spool.label_weight - spool.weight_used);
  2958. const p = spool.label_weight > 0 ? (r / spool.label_weight) * 100 : 0;
  2959. return (
  2960. <SpoolTableRow
  2961. key={spool.id}
  2962. spool={spool}
  2963. remaining={r}
  2964. pct={p}
  2965. isSelected={selectedIds?.has(spool.id)}
  2966. onToggleSelected={onToggleSelected ? () => onToggleSelected(spool.id) : undefined}
  2967. onEdit={() => onEdit(spool)}
  2968. onCopy={onCopy ? () => onCopy(spool) : undefined}
  2969. onRestore={() => {}}
  2970. onArchive={() => onArchive(spool.id)}
  2971. onDelete={() => onDelete(spool.id)}
  2972. onPrintLabel={onPrintLabel ? () => onPrintLabel(spool.id) : undefined}
  2973. onResetConsumedCounter={onResetConsumedCounter ? () => onResetConsumedCounter(spool.id) : undefined}
  2974. visibleColumns={visibleColumns}
  2975. assignmentMap={assignmentMap}
  2976. catalogMap={catalogMap}
  2977. locationReadingsMap={locationReadingsMap}
  2978. currencySymbol={currencySymbol}
  2979. dateFormat={dateFormat}
  2980. t={t}
  2981. onSyncWeight={onSyncWeight}
  2982. colorizeLocationSensors={colorizeLocationSensors}
  2983. locationSensorAboveColor={locationSensorAboveColor}
  2984. locationSensorBelowColor={locationSensorBelowColor}
  2985. locationSensorOptimalColor={locationSensorOptimalColor}
  2986. />
  2987. );
  2988. })}
  2989. </>
  2990. );
  2991. }
  2992. /* Empty state matching SpoolBuddy's design */
  2993. function EmptyFilterState({
  2994. hasFilters,
  2995. onAddSpool,
  2996. t,
  2997. }: {
  2998. hasFilters: boolean;
  2999. onAddSpool: () => void;
  3000. t: (key: string) => string;
  3001. }) {
  3002. return (
  3003. <div className="flex flex-col items-center justify-center py-16 px-4">
  3004. <div className="relative mb-6">
  3005. <div className="absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl" />
  3006. <div className="relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg">
  3007. <div className="absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30" />
  3008. <div className="absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20" />
  3009. {hasFilters ? (
  3010. <Search className="w-10 h-10 text-bambu-gray/40" strokeWidth={1.5} />
  3011. ) : (
  3012. <div className="relative">
  3013. <div className="w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center">
  3014. <div className="w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20" />
  3015. </div>
  3016. <div className="absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md">
  3017. <span className="text-white text-lg font-bold leading-none">+</span>
  3018. </div>
  3019. </div>
  3020. )}
  3021. </div>
  3022. </div>
  3023. <h3 className="text-lg font-semibold text-white mb-2 text-center">
  3024. {hasFilters ? t('inventory.noSpoolsMatch') : t('inventory.noSpools').split('.')[0]}
  3025. </h3>
  3026. <p className="text-sm text-bambu-gray text-center max-w-sm mb-6">
  3027. {hasFilters
  3028. ? t('inventory.noSpoolsMatchDesc')
  3029. : t('inventory.noSpools')
  3030. }
  3031. </p>
  3032. {!hasFilters && (
  3033. <Button onClick={onAddSpool}>
  3034. <Package className="w-4 h-4" />
  3035. {t('inventory.addSpool')}
  3036. </Button>
  3037. )}
  3038. </div>
  3039. );
  3040. }