AdditionalSection.tsx 18 KB

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