InventoryPage.tsx 135 KB

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