InventorySpoolInfoCard.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { useState } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { Check, AlertTriangle, RefreshCw, Unlink } from 'lucide-react';
  5. import type { InventorySpool } from '../../api/client';
  6. import { spoolbuddyApi, api } from '../../api/client';
  7. import { SpoolIcon } from './SpoolIcon';
  8. const DEFAULT_CORE_WEIGHT_KEY = 'spoolbuddy-default-core-weight';
  9. function getDefaultCoreWeight(): number {
  10. try {
  11. const stored = localStorage.getItem(DEFAULT_CORE_WEIGHT_KEY);
  12. if (stored) {
  13. const weight = parseInt(stored, 10);
  14. if (weight >= 0 && weight <= 500) return weight;
  15. }
  16. } catch {
  17. // Ignore errors
  18. }
  19. return 250;
  20. }
  21. interface InventorySpoolInfoCardProps {
  22. spool: InventorySpool;
  23. liveScaleWeight: number | null;
  24. persistedGrossWeight?: number | null;
  25. onClose?: () => void;
  26. onSyncWeight?: () => void;
  27. onAssignToAms?: () => void;
  28. isAssigned?: boolean;
  29. onUnassignFromAms?: () => void;
  30. className?: string;
  31. }
  32. export function InventorySpoolInfoCard({
  33. spool,
  34. liveScaleWeight,
  35. persistedGrossWeight,
  36. onClose,
  37. onSyncWeight,
  38. onAssignToAms,
  39. isAssigned,
  40. onUnassignFromAms,
  41. className,
  42. }: InventorySpoolInfoCardProps) {
  43. const { t } = useTranslation();
  44. const [syncing, setSyncing] = useState(false);
  45. const [synced, setSynced] = useState(false);
  46. const [syncedGrossWeight, setSyncedGrossWeight] = useState<number | null>(null);
  47. // Fetch k_profiles if not already present in the spool object
  48. const { data: fetchedKProfiles } = useQuery({
  49. queryKey: ['spool-k-profiles', spool.id],
  50. queryFn: () => api.getSpoolKProfiles(spool.id),
  51. // Inventory list payloads may omit k_profiles, so lazily fetch when missing.
  52. enabled: !spool.k_profiles || spool.k_profiles.length === 0,
  53. staleTime: 5 * 60 * 1000,
  54. });
  55. // Use fetched k_profiles if available, otherwise use the ones from the spool object
  56. const kProfiles = (spool.k_profiles && spool.k_profiles.length > 0) ? spool.k_profiles : fetchedKProfiles;
  57. const colorHex = spool.rgba ? `#${spool.rgba.slice(0, 6)}` : '#808080';
  58. const coreWeight = (spool.core_weight && spool.core_weight > 0)
  59. ? spool.core_weight
  60. : getDefaultCoreWeight();
  61. const grossWeightFromScale = liveScaleWeight !== null
  62. ? Math.round(Math.max(0, liveScaleWeight))
  63. : null;
  64. // Inventory scenario: prefer the most recently synced value in this modal session.
  65. const displayedGrossWeight = syncedGrossWeight ?? (
  66. persistedGrossWeight !== undefined
  67. ? (persistedGrossWeight !== null ? Math.round(Math.max(0, persistedGrossWeight)) : null)
  68. : grossWeightFromScale
  69. );
  70. const inventoryRemaining = Math.round(Math.max(0,
  71. (spool.label_weight || 0) - (spool.weight_used || 0)
  72. ));
  73. // Use live scale for remaining/fill only when scale has a meaningful reading.
  74. const minDynamicScaleReading = 10;
  75. const useDynamicRemaining = grossWeightFromScale !== null
  76. && grossWeightFromScale >= minDynamicScaleReading;
  77. const remaining = useDynamicRemaining
  78. ? Math.round(Math.max(0, grossWeightFromScale - coreWeight))
  79. : inventoryRemaining;
  80. const labelWeight = Math.round(spool.label_weight || 1000);
  81. const fillPercent = labelWeight > 0 ? Math.min(100, Math.round((remaining / labelWeight) * 100)) : null;
  82. const fillColor = fillPercent !== null
  83. ? (fillPercent > 50 ? '#22c55e' : fillPercent > 20 ? '#eab308' : '#ef4444')
  84. : '#808080';
  85. const netWeight = Math.max(0,
  86. (spool.label_weight || 0) - (spool.weight_used || 0)
  87. );
  88. const calculatedWeight = netWeight + coreWeight;
  89. const difference = grossWeightFromScale !== null ? grossWeightFromScale - calculatedWeight : null;
  90. const isMatch = difference !== null ? Math.abs(difference) <= 50 : null;
  91. // Inventory fallback so gross is always populated across spools.
  92. const inventoryDerivedGrossWeight = Math.round(calculatedWeight);
  93. const resolvedGrossWeight = displayedGrossWeight ?? inventoryDerivedGrossWeight;
  94. const nozzleTempRange = (spool.nozzle_temp_min != null && spool.nozzle_temp_max != null)
  95. ? `${spool.nozzle_temp_min}-${spool.nozzle_temp_max}\u00B0C`
  96. : null;
  97. const slicerPreset = spool.slicer_filament_name || spool.slicer_filament || null;
  98. const note = spool.note?.trim() || null;
  99. const kFactorSummary = (kProfiles && kProfiles.length > 0)
  100. ? Array.from(new Set(kProfiles.map(kp => kp.k_value.toFixed(3)))).join(', ')
  101. : null;
  102. const handleSyncWeight = async () => {
  103. if (liveScaleWeight === null) return;
  104. const roundedLiveWeight = Math.round(Math.max(0, liveScaleWeight));
  105. setSyncing(true);
  106. try {
  107. await spoolbuddyApi.updateSpoolWeight(spool.id, roundedLiveWeight);
  108. setSyncedGrossWeight(roundedLiveWeight);
  109. setSynced(true);
  110. onSyncWeight?.();
  111. setTimeout(() => setSynced(false), 3000);
  112. } catch (e) {
  113. console.error('Failed to sync weight:', e);
  114. } finally {
  115. setSyncing(false);
  116. }
  117. };
  118. return (
  119. <div className={`flex flex-col items-center space-y-4 max-w-md ${className ?? ''}`}>
  120. <div className="flex items-start gap-5">
  121. <div className="relative shrink-0">
  122. <SpoolIcon color={colorHex} isEmpty={false} size={100} />
  123. {fillPercent !== null && (
  124. <div
  125. className="absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg"
  126. style={{ backgroundColor: fillColor }}
  127. >
  128. {fillPercent}%
  129. </div>
  130. )}
  131. </div>
  132. <div className="flex-1 min-w-0 pt-1">
  133. <h3 className="text-lg font-semibold text-zinc-100">
  134. {spool.color_name || 'Unknown color'}
  135. </h3>
  136. <p className="text-sm text-zinc-400">
  137. {spool.brand} &bull; {spool.material}
  138. {spool.subtype && ` ${spool.subtype}`}
  139. </p>
  140. <div className="mt-3">
  141. <div className="flex items-baseline gap-2">
  142. <span className="text-3xl font-bold font-mono text-zinc-100">{remaining}g</span>
  143. <span className="text-sm text-zinc-500">/ {labelWeight}g</span>
  144. </div>
  145. <p className="text-xs text-zinc-500 mt-0.5">{t('spoolbuddy.spool.remaining', 'Remaining')}</p>
  146. <div className="mt-2 max-w-xs">
  147. <div className="h-2 bg-zinc-700 rounded-full overflow-hidden">
  148. <div
  149. className="h-full rounded-full transition-all duration-500"
  150. style={{ width: `${fillPercent ?? 0}%`, backgroundColor: fillColor }}
  151. />
  152. </div>
  153. </div>
  154. </div>
  155. </div>
  156. </div>
  157. <div className="grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full">
  158. <div className="flex justify-between">
  159. <span className="text-zinc-500">{t('spoolbuddy.dashboard.grossWeight', 'Gross weight')}</span>
  160. <span className="font-mono text-zinc-300">{resolvedGrossWeight}g</span>
  161. </div>
  162. <div className="flex justify-between">
  163. <span className="text-zinc-500">{t('spoolbuddy.spool.coreWeight', 'Core')}</span>
  164. <span className="font-mono text-zinc-300">{coreWeight}g</span>
  165. </div>
  166. <div className="flex justify-between">
  167. <span className="text-zinc-500">{t('spoolbuddy.dashboard.spoolSize', 'Spool size')}</span>
  168. <span className="font-mono text-zinc-300">{labelWeight}g</span>
  169. </div>
  170. <div className="flex justify-between items-center">
  171. <span className="text-zinc-500">{t('spoolbuddy.spool.scaleWeight', 'Scale')}</span>
  172. {grossWeightFromScale !== null ? (
  173. <span className={`flex items-center gap-1 font-mono ${isMatch ? 'text-green-500' : 'text-yellow-500'}`}>
  174. {grossWeightFromScale}g
  175. {isMatch ? (
  176. <Check className="w-3.5 h-3.5" />
  177. ) : (
  178. <>
  179. <AlertTriangle className="w-3.5 h-3.5" />
  180. <button
  181. onClick={handleSyncWeight}
  182. className="p-1 hover:bg-green-500/20 rounded transition-colors text-green-500"
  183. title={t('spoolbuddy.dashboard.syncWeight', 'Sync Weight')}
  184. >
  185. <RefreshCw className="w-4 h-4" />
  186. </button>
  187. </>
  188. )}
  189. </span>
  190. ) : (
  191. <span className="text-zinc-500">{'\u2014'}</span>
  192. )}
  193. </div>
  194. <div className="flex justify-between items-center">
  195. <span className="text-zinc-500">{t('spoolbuddy.dashboard.tagId', 'Tag')}</span>
  196. <span className="font-mono text-xs text-zinc-400 truncate max-w-[120px]" title={spool.tag_uid || ''}>
  197. {spool.tag_uid ? spool.tag_uid.slice(-8) : '\u2014'}
  198. </span>
  199. </div>
  200. {nozzleTempRange && (
  201. <div className="flex justify-between items-center">
  202. <span className="text-zinc-500">{t('spoolbuddy.inventory.nozzleTemp', 'Nozzle')}</span>
  203. <span className="font-mono text-zinc-300">{nozzleTempRange}</span>
  204. </div>
  205. )}
  206. {spool.cost_per_kg != null && spool.cost_per_kg > 0 && (
  207. <div className="flex justify-between items-center">
  208. <span className="text-zinc-500">{t('spoolbuddy.inventory.costPerKg', 'Cost/kg')}</span>
  209. <span className="font-mono text-zinc-300">{spool.cost_per_kg.toFixed(2)}/kg</span>
  210. </div>
  211. )}
  212. {kFactorSummary && (
  213. <div className="flex justify-between items-center">
  214. <span className="text-zinc-500">{t('spoolbuddy.inventory.kProfiles', 'K-Profile')}</span>
  215. <span className="font-mono text-zinc-300 truncate max-w-[220px] text-right" title={kFactorSummary}>{kFactorSummary}</span>
  216. </div>
  217. )}
  218. {slicerPreset && (
  219. <div className="min-w-0">
  220. <p className="text-xs text-zinc-500 mb-1">{t('spoolbuddy.inventory.slicerFilament', 'Slicer Filament')}</p>
  221. <p className="text-sm text-zinc-300 whitespace-pre-wrap break-words">{slicerPreset}</p>
  222. </div>
  223. )}
  224. {note && (
  225. <div className="col-span-2">
  226. <p className="text-xs text-zinc-500 mb-1">{t('spoolbuddy.inventory.note', 'Note')}</p>
  227. <p className="text-sm leading-5 text-zinc-300 whitespace-pre-wrap break-words max-h-[3.75rem] overflow-y-auto pr-1">{note}</p>
  228. </div>
  229. )}
  230. </div>
  231. <div className="flex gap-2 justify-center">
  232. {onAssignToAms && (
  233. <button
  234. onClick={isAssigned ? undefined : onAssignToAms}
  235. disabled={!!isAssigned}
  236. className="px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px] disabled:opacity-50 disabled:cursor-not-allowed"
  237. >
  238. {t('spoolbuddy.modal.assignToAms', 'Assign to AMS')}
  239. </button>
  240. )}
  241. {onUnassignFromAms && (
  242. <button
  243. onClick={onUnassignFromAms}
  244. className="px-5 py-2.5 rounded-lg text-sm font-medium bg-red-600/20 text-red-400 hover:bg-red-600/30 transition-colors min-h-[44px]"
  245. >
  246. <Unlink className="w-4 h-4 inline mr-1" />
  247. {t('inventory.unassignSpool')}
  248. </button>
  249. )}
  250. <button
  251. onClick={handleSyncWeight}
  252. disabled={liveScaleWeight === null || syncing}
  253. className={`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${
  254. synced
  255. ? 'bg-green-600/20 text-green-400'
  256. : onAssignToAms
  257. ? 'bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed'
  258. : 'bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed'
  259. }`}
  260. >
  261. {syncing ? '...' : synced ? t('spoolbuddy.dashboard.weightSynced', 'Synced!') : t('spoolbuddy.dashboard.syncWeight', 'Sync Weight')}
  262. </button>
  263. {onClose && (
  264. <button
  265. onClick={onClose}
  266. className="px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]"
  267. >
  268. {t('spoolbuddy.dashboard.close', 'Close')}
  269. </button>
  270. )}
  271. </div>
  272. </div>
  273. );
  274. }