AdditionalSection.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. import { useState, useRef, useEffect, useMemo } from 'react';
  2. import { Scale } from 'lucide-react';
  3. import { useTranslation } from 'react-i18next';
  4. import { useToast } from '../../contexts/ToastContext';
  5. import { toDateTimeLocalValue } from '../../utils/date';
  6. import type { AdditionalSectionProps } from './types';
  7. function SpoolWeightPicker({
  8. catalog,
  9. value,
  10. onChange,
  11. catalogId,
  12. onCatalogIdChange,
  13. }: {
  14. catalog: { id: number; name: string; weight: number }[];
  15. value: number;
  16. onChange: (weight: number) => void;
  17. catalogId: number | null;
  18. onCatalogIdChange: (id: number | null) => void;
  19. }) {
  20. const { t } = useTranslation();
  21. const [isOpen, setIsOpen] = useState(false);
  22. const [search, setSearch] = useState('');
  23. const dropdownRef = useRef<HTMLDivElement>(null);
  24. const inputRef = useRef<HTMLInputElement>(null);
  25. useEffect(() => {
  26. const handleClick = (e: MouseEvent) => {
  27. if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
  28. setIsOpen(false);
  29. }
  30. };
  31. document.addEventListener('mousedown', handleClick);
  32. return () => document.removeEventListener('mousedown', handleClick);
  33. }, []);
  34. // When value changes, auto-select if there's only one matching entry or keep selection if it still matches
  35. useEffect(() => {
  36. // If no catalog loaded yet, skip matching logic
  37. if (catalog.length === 0) {
  38. return;
  39. }
  40. const matches = catalog.filter(e => e.weight === value);
  41. // If currently selected entry still matches the weight, keep it selected
  42. if (catalogId) {
  43. const selected = catalog.find(e => e.id === catalogId);
  44. if (selected && selected.weight === value) {
  45. return; // Keep current selection
  46. }
  47. }
  48. // If exactly one match, auto-select it
  49. if (matches.length === 1) {
  50. onCatalogIdChange(matches[0].id);
  51. } else if (matches.length === 0) {
  52. // No matches, clear selection to prevent stale catalog ID
  53. if (catalogId !== null) {
  54. onCatalogIdChange(null);
  55. }
  56. }
  57. // If multiple matches, don't auto-select - let user choose
  58. }, [value, catalog, catalogId, onCatalogIdChange]);
  59. const filtered = useMemo(() => {
  60. if (!search) return catalog;
  61. const s = search.toLowerCase();
  62. return catalog.filter(e =>
  63. e.name.toLowerCase().includes(s) ||
  64. e.weight.toString().includes(s),
  65. );
  66. }, [catalog, search]);
  67. // Find all entries matching the current weight
  68. const matchingEntries = useMemo(() => {
  69. return catalog.filter(e => e.weight === value);
  70. }, [catalog, value]);
  71. // Display value: show catalog name if selected by ID, otherwise show first match
  72. const displayValue = useMemo(() => {
  73. if (isOpen) return search;
  74. // If a catalog ID is explicitly selected, use that
  75. if (catalogId) {
  76. const entry = catalog.find(e => e.id === catalogId);
  77. if (entry) return entry.name;
  78. }
  79. // Otherwise, show the first matching entry as a suggestion
  80. if (matchingEntries.length > 0) {
  81. return matchingEntries[0].name;
  82. }
  83. // Leave empty if there are no matches
  84. return '';
  85. }, [isOpen, search, catalogId, catalog, matchingEntries]);
  86. return (
  87. <div>
  88. <label className="block text-sm font-medium text-bambu-gray mb-1">
  89. <span className="flex items-center gap-2">
  90. <Scale className="w-3.5 h-3.5 text-bambu-gray" />
  91. {t('inventory.coreWeight')}
  92. </span>
  93. </label>
  94. <div className="flex gap-2 items-center">
  95. <div className="flex-1 min-w-0 relative" ref={dropdownRef}>
  96. <input
  97. ref={inputRef}
  98. type="text"
  99. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  100. placeholder={t('inventory.searchSpoolWeight')}
  101. value={displayValue}
  102. onFocus={() => {
  103. setIsOpen(true);
  104. setSearch('');
  105. }}
  106. onChange={(e) => {
  107. setSearch(e.target.value);
  108. setIsOpen(true);
  109. }}
  110. />
  111. {isOpen && (
  112. <div className="absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto">
  113. {filtered.length === 0 ? (
  114. <div className="px-3 py-2 text-sm text-bambu-gray">{t('inventory.noResults')}</div>
  115. ) : (
  116. filtered.map(entry => (
  117. <button
  118. key={entry.id}
  119. type="button"
  120. className={`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${
  121. (catalogId ? entry.id === catalogId : entry.weight === value)
  122. ? 'bg-bambu-green/10 text-bambu-green'
  123. : 'text-white'
  124. }`}
  125. onClick={() => {
  126. onCatalogIdChange(entry.id);
  127. onChange(entry.weight);
  128. setIsOpen(false);
  129. setSearch('');
  130. }}
  131. >
  132. <span className="truncate">{entry.name}</span>
  133. <span className="font-mono text-xs text-bambu-gray ml-2 shrink-0">{entry.weight}g</span>
  134. </button>
  135. ))
  136. )}
  137. </div>
  138. )}
  139. </div>
  140. <div className="flex items-center gap-1 shrink-0">
  141. <input
  142. type="number"
  143. className="w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green"
  144. value={value}
  145. min={0}
  146. max={2000}
  147. onChange={(e) => {
  148. const val = parseInt(e.target.value);
  149. if (!isNaN(val) && val >= 0) onChange(val);
  150. }}
  151. />
  152. <span className="text-bambu-gray text-sm">g</span>
  153. </div>
  154. </div>
  155. </div>
  156. );
  157. }
  158. export function AdditionalSection({
  159. formData,
  160. updateField,
  161. spoolCatalog,
  162. currencySymbol,
  163. availableCategories,
  164. availableMaterialNumbers,
  165. availableLocations = [],
  166. onCreateLocation,
  167. globalLowStockThreshold,
  168. spoolmanMode = false,
  169. showLastDried = false,
  170. }: AdditionalSectionProps) {
  171. const { t } = useTranslation();
  172. const { showToast } = useToast();
  173. const [measuredInput, setMeasuredInput] = useState('');
  174. const [isMeasuredFocused, setIsMeasuredFocused] = useState(false);
  175. const [remainingInput, setRemainingInput] = useState('');
  176. const [isRemainingFocused, setIsRemainingFocused] = useState(false);
  177. const [newLocationName, setNewLocationName] = useState('');
  178. const [creatingLocation, setCreatingLocation] = useState(false);
  179. const remainingWeight = Math.max(0, formData.label_weight - formData.weight_used);
  180. const measuredDefault = formData.core_weight + remainingWeight;
  181. useEffect(() => {
  182. if (!isMeasuredFocused) {
  183. setMeasuredInput(String(measuredDefault));
  184. }
  185. }, [isMeasuredFocused, measuredDefault]);
  186. useEffect(() => {
  187. if (!isRemainingFocused) {
  188. setRemainingInput(String(remainingWeight));
  189. }
  190. }, [isRemainingFocused, remainingWeight]);
  191. return (
  192. // Two columns from sm up. These are all short single-value fields, and at
  193. // the form's width one per row left most of each row empty and pushed the
  194. // rest below the fold. The two that stay full width earn it: the spool
  195. // catalogue picker carries a long product name beside its own number
  196. // input, and the note is a textarea.
  197. <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-4">
  198. {/* Empty Spool Weight. Shown in Spoolman mode too: Spoolman keeps a
  199. per-spool spool_weight that overrides the filament type's, and it is
  200. the tare every weigh-in subtracts (#2908). */}
  201. <div className="sm:col-span-2">
  202. <SpoolWeightPicker
  203. catalog={spoolCatalog}
  204. value={formData.core_weight}
  205. onChange={(weight) => updateField('core_weight', weight)}
  206. catalogId={formData.core_weight_catalog_id}
  207. onCatalogIdChange={(id) => updateField('core_weight_catalog_id', id)}
  208. />
  209. </div>
  210. {/* Current Weight (remaining filament) */}
  211. <div>
  212. <label className="block text-sm font-medium text-bambu-gray mb-1">{t('inventory.currentWeight')}</label>
  213. <div className="flex items-center gap-2">
  214. <div className="relative flex-1">
  215. <input
  216. type="number"
  217. value={remainingInput}
  218. min={0}
  219. max={formData.label_weight}
  220. onFocus={() => setIsRemainingFocused(true)}
  221. onChange={(e) => {
  222. setRemainingInput(e.target.value);
  223. }}
  224. onBlur={() => {
  225. setIsRemainingFocused(false);
  226. const raw = remainingInput.trim();
  227. const remaining = Number(raw);
  228. if (!raw || !Number.isFinite(remaining) || remaining < 0 || remaining > formData.label_weight) {
  229. setRemainingInput(String(remainingWeight));
  230. return;
  231. }
  232. const rounded = Math.round(remaining);
  233. updateField('weight_used', Math.max(0, formData.label_weight - rounded));
  234. setRemainingInput(String(rounded));
  235. }}
  236. className="w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  237. />
  238. <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray">g</span>
  239. </div>
  240. <span className="text-xs text-bambu-gray shrink-0">/ {formData.label_weight}g</span>
  241. </div>
  242. </div>
  243. {/* Measured Weight (empty spool + remaining filament) */}
  244. <div>
  245. <label className="block text-sm font-medium text-bambu-gray mb-1">{t('inventory.measuredWeight')}</label>
  246. <div className="flex items-center gap-2">
  247. <div className="relative flex-1">
  248. <input
  249. type="number"
  250. value={measuredInput}
  251. min={0}
  252. onFocus={() => setIsMeasuredFocused(true)}
  253. onChange={(e) => {
  254. setMeasuredInput(e.target.value);
  255. }}
  256. onBlur={() => {
  257. setIsMeasuredFocused(false);
  258. const raw = measuredInput.trim();
  259. const measured = Number(raw);
  260. const minAllowed = formData.core_weight;
  261. const maxAllowed = formData.core_weight + formData.label_weight;
  262. if (!raw || !Number.isFinite(measured) || measured < minAllowed || measured > maxAllowed) {
  263. showToast(t('inventory.measuredWeightError', { min: minAllowed, max: maxAllowed }), 'error');
  264. setMeasuredInput(String(measuredDefault));
  265. return;
  266. }
  267. const rounded = Math.round(measured);
  268. const remaining = Math.max(0, Math.min(formData.label_weight, rounded - formData.core_weight));
  269. updateField('weight_used', Math.max(0, formData.label_weight - remaining));
  270. setMeasuredInput(String(rounded));
  271. }}
  272. className="w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  273. />
  274. <span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray">g</span>
  275. </div>
  276. <span className="text-xs text-bambu-gray shrink-0">/ {formData.core_weight + formData.label_weight}g</span>
  277. </div>
  278. </div>
  279. {/* Cost per kg */}
  280. <div>
  281. <label className="block text-sm font-medium text-bambu-gray mb-1">{t('inventory.costPerKg', 'Cost per kg')}</label>
  282. <div className="flex items-center gap-2">
  283. <div className="relative flex-1">
  284. <span className="absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none">{currencySymbol}</span>
  285. <input
  286. type="number"
  287. value={formData.cost_per_kg ?? ''}
  288. min={0}
  289. step={0.01}
  290. placeholder="0.00"
  291. onChange={(e) => {
  292. const value = e.target.value === '' ? null : parseFloat(e.target.value);
  293. updateField('cost_per_kg', value);
  294. }}
  295. style={{ paddingLeft: `${Math.max(2, currencySymbol.length * 0.6 + 1)}rem` }}
  296. className="w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  297. />
  298. </div>
  299. </div>
  300. </div>
  301. {/* Material number (#2870). Hidden in Spoolman mode: there the number
  302. is Spoolman's filament-level article_number, maintained in Spoolman
  303. itself and surfaced read-only in the list. */}
  304. {!spoolmanMode && (
  305. <div>
  306. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="spool-material-number">
  307. {t('inventory.materialNumber')}
  308. </label>
  309. <input
  310. id="spool-material-number"
  311. type="text"
  312. list="spool-material-number-options"
  313. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  314. placeholder={t('inventory.materialNumberPlaceholder')}
  315. value={formData.material_number}
  316. maxLength={64}
  317. onChange={(e) => updateField('material_number', e.target.value)}
  318. />
  319. {availableMaterialNumbers.length > 0 && (
  320. <datalist id="spool-material-number-options">
  321. {availableMaterialNumbers.map((n) => <option key={n} value={n} />)}
  322. </datalist>
  323. )}
  324. <p className="text-xs text-bambu-gray mt-1">{t('inventory.materialNumberHelp')}</p>
  325. </div>
  326. )}
  327. {/* Category (#729) */}
  328. <div>
  329. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="spool-category">
  330. {t('inventory.category')}
  331. </label>
  332. <input
  333. id="spool-category"
  334. type="text"
  335. list="spool-category-options"
  336. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  337. placeholder={t('inventory.categoryPlaceholder')}
  338. value={formData.category}
  339. maxLength={50}
  340. onChange={(e) => updateField('category', e.target.value)}
  341. />
  342. {availableCategories.length > 0 && (
  343. <datalist id="spool-category-options">
  344. {availableCategories.map((c) => <option key={c} value={c} />)}
  345. </datalist>
  346. )}
  347. </div>
  348. {/* Per-spool low-stock threshold override (#729) */}
  349. <div>
  350. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="spool-low-stock-threshold">
  351. {t('inventory.lowStockThresholdOverride')}
  352. </label>
  353. <div className="flex items-center gap-2">
  354. <div className="relative flex-1">
  355. <input
  356. id="spool-low-stock-threshold"
  357. type="number"
  358. className="w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  359. placeholder={String(globalLowStockThreshold)}
  360. value={formData.low_stock_threshold_pct ?? ''}
  361. min={1}
  362. max={99}
  363. step={1}
  364. onChange={(e) => {
  365. const raw = e.target.value;
  366. if (raw === '') {
  367. updateField('low_stock_threshold_pct', null);
  368. return;
  369. }
  370. const n = Number(raw);
  371. if (Number.isFinite(n)) {
  372. updateField('low_stock_threshold_pct', Math.min(99, Math.max(1, Math.round(n))));
  373. }
  374. }}
  375. />
  376. <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none">%</span>
  377. </div>
  378. </div>
  379. <p className="text-xs text-bambu-gray mt-1">
  380. {t('inventory.lowStockThresholdOverrideHelp', { global: globalLowStockThreshold })}
  381. </p>
  382. </div>
  383. {/* Storage Location */}
  384. <div>
  385. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="spool-storage-location">
  386. {t('inventory.storageLocation')}
  387. </label>
  388. <select
  389. id="spool-storage-location"
  390. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  391. value={formData.location_id ?? ''}
  392. onChange={(e) => {
  393. const raw = e.target.value;
  394. if (!raw) {
  395. updateField('location_id', null);
  396. return;
  397. }
  398. const id = Number(raw);
  399. updateField('location_id', id);
  400. }}
  401. >
  402. <option value="">{t('inventory.storageLocationNone')}</option>
  403. {availableLocations.map((loc) => (
  404. <option key={loc.id} value={loc.id}>{loc.name}</option>
  405. ))}
  406. </select>
  407. {onCreateLocation && (
  408. <div className="mt-2 flex gap-2">
  409. <input
  410. type="text"
  411. maxLength={255}
  412. className="flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  413. placeholder={t('locations.createPlaceholder')}
  414. value={newLocationName}
  415. onChange={(e) => setNewLocationName(e.target.value)}
  416. />
  417. <button
  418. type="button"
  419. className="px-3 py-2 text-sm rounded-lg bg-bambu-dark-tertiary text-white hover:bg-bambu-gray-dark disabled:opacity-50"
  420. disabled={!newLocationName.trim() || creatingLocation}
  421. onClick={async () => {
  422. const trimmed = newLocationName.trim();
  423. if (!trimmed || !onCreateLocation) return;
  424. setCreatingLocation(true);
  425. try {
  426. const created = await onCreateLocation(trimmed);
  427. if (created) {
  428. updateField('location_id', created.id);
  429. setNewLocationName('');
  430. }
  431. } finally {
  432. setCreatingLocation(false);
  433. }
  434. }}
  435. >
  436. {t('locations.addShort')}
  437. </button>
  438. </div>
  439. )}
  440. </div>
  441. {/* Last dried (#2863). Stamped by AMS drying runs; set here for a
  442. spool dried in an external dryer. */}
  443. {showLastDried && (
  444. <div>
  445. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="spool-last-dried">
  446. {t('inventory.lastDried')}
  447. </label>
  448. <div className="flex gap-2">
  449. <input
  450. id="spool-last-dried"
  451. type="datetime-local"
  452. className="flex-1 min-w-0 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  453. value={formData.last_dried_at}
  454. onChange={(e) => updateField('last_dried_at', e.target.value)}
  455. />
  456. <button
  457. type="button"
  458. className="px-3 py-2 text-sm rounded-lg bg-bambu-dark-tertiary text-white hover:bg-bambu-gray-dark"
  459. onClick={() => updateField('last_dried_at', toDateTimeLocalValue(new Date()))}
  460. >
  461. {t('inventory.lastDriedNow')}
  462. </button>
  463. </div>
  464. <p className="text-xs text-bambu-gray mt-1">{t('inventory.lastDriedHelp')}</p>
  465. </div>
  466. )}
  467. {/* Note */}
  468. <div className="sm:col-span-2">
  469. <label className="block text-sm font-medium text-bambu-gray mb-1">{t('inventory.note')}</label>
  470. <textarea
  471. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]"
  472. placeholder={t('inventory.notePlaceholder')}
  473. value={formData.note}
  474. onChange={(e) => updateField('note', e.target.value)}
  475. />
  476. </div>
  477. </div>
  478. );
  479. }