ArchivesPage.tsx 162 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003
  1. import { useState, useRef, useEffect, useCallback } from 'react';
  2. import { Link, useNavigate } from 'react-router-dom';
  3. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import {
  6. Download,
  7. Trash2,
  8. Clock,
  9. Package,
  10. Coins,
  11. Layers,
  12. Search,
  13. Filter,
  14. Image,
  15. Box,
  16. Printer,
  17. Upload,
  18. ExternalLink,
  19. CheckSquare,
  20. Square,
  21. X,
  22. Globe,
  23. Pencil,
  24. LayoutGrid,
  25. List,
  26. CalendarDays,
  27. ArrowUpDown,
  28. Star,
  29. Tag,
  30. StickyNote,
  31. FolderOpen,
  32. Calendar,
  33. AlertCircle,
  34. Copy,
  35. Film,
  36. ScanSearch,
  37. QrCode,
  38. Camera,
  39. FileText,
  40. FileCode,
  41. MoreVertical,
  42. FileSpreadsheet,
  43. GitCompare,
  44. GitBranch,
  45. Loader2,
  46. FolderKanban,
  47. ChevronLeft,
  48. ChevronRight,
  49. ChevronsLeft,
  50. ChevronsRight,
  51. Settings,
  52. User,
  53. Play,
  54. ClipboardList,
  55. Zap,
  56. Cog,
  57. Archive as ArchiveIcon,
  58. History,
  59. } from 'lucide-react';
  60. import { api } from '../api/client';
  61. import { SliceModal } from '../components/SliceModal';
  62. import { openInSlicer, type SlicerType } from '../utils/slicer';
  63. import { formatDateTime, formatDateOnly, parseUTCDate, type TimeFormat, formatDuration } from '../utils/date';
  64. import { getCurrencySymbol } from '../utils/currency';
  65. import { getBedTypeInfo } from '../utils/bedType';
  66. import { useIsMobile } from '../hooks/useIsMobile';
  67. import type { Archive, ProjectListItem } from '../api/client';
  68. import { Card, CardContent } from '../components/Card';
  69. import { Button } from '../components/Button';
  70. import { PrintModal } from '../components/PrintModal';
  71. import { UploadModal } from '../components/UploadModal';
  72. import { PurgeArchivesModal } from '../components/PurgeArchivesModal';
  73. import { ConfirmModal } from '../components/ConfirmModal';
  74. import { EditArchiveModal } from '../components/EditArchiveModal';
  75. import { PrintLogModal } from '../components/PrintLogModal';
  76. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  77. import { BatchTagModal } from '../components/BatchTagModal';
  78. import { BatchProjectModal } from '../components/BatchProjectModal';
  79. import { CalendarView } from '../components/CalendarView';
  80. import { QRCodeModal } from '../components/QRCodeModal';
  81. import { PhotoGalleryModal } from '../components/PhotoGalleryModal';
  82. import { ProjectPageModal } from '../components/ProjectPageModal';
  83. import { TimelapseViewer } from '../components/TimelapseViewer';
  84. import { CompareArchivesModal } from '../components/CompareArchivesModal';
  85. import { PendingUploadsPanel } from '../components/PendingUploadsPanel';
  86. import { TagManagementModal } from '../components/TagManagementModal';
  87. import { PlatePickerModal } from '../components/PlatePickerModal';
  88. import type { PlateMetadata } from '../types/plates';
  89. import { useToast } from '../contexts/ToastContext';
  90. import { useAuth } from '../contexts/AuthContext';
  91. import { formatFileSize } from '../utils/file';
  92. type TFunction = (key: string, options?: Record<string, unknown>) => string;
  93. /**
  94. * Check if an archive represents a sliced/printable file.
  95. * Uses filename (.gcode, .gcode.3mf) as primary check, then falls back to
  96. * metadata — a .3mf with total_layers or print_time is sliced (contains gcode),
  97. * while a raw source .3mf (CAD export) has neither.
  98. */
  99. function isSlicedFile(archive: { filename?: string | null; total_layers?: number | null; print_time_seconds?: number | null }): boolean {
  100. const filename = archive.filename;
  101. if (filename) {
  102. const lower = filename.toLowerCase();
  103. if (lower.endsWith('.gcode') || lower.includes('.gcode.')) return true;
  104. }
  105. // .3mf can be either sliced or source — check for gcode metadata
  106. if (archive.total_layers || archive.print_time_seconds) return true;
  107. return false;
  108. }
  109. // formatDate imported from '../utils/date' - handles UTC conversion
  110. /**
  111. * Open an archive file in the slicer.
  112. * Fetches a short-lived download token, then builds a token-authenticated URL
  113. * that bypasses auth middleware (slicer protocol handlers can't send auth headers).
  114. */
  115. async function openInSlicerWithToken(
  116. archiveId: number,
  117. filename: string,
  118. resourceType: 'file' | 'source',
  119. slicer: SlicerType,
  120. ): Promise<void> {
  121. try {
  122. if (resourceType === 'source') {
  123. const { token } = await api.createSourceSlicerToken(archiveId);
  124. const path = api.getSourceSlicerDownloadUrl(archiveId, token, filename);
  125. openInSlicer(`${window.location.origin}${path}`, slicer);
  126. } else {
  127. const { token } = await api.createArchiveSlicerToken(archiveId);
  128. const path = api.getArchiveSlicerDownloadUrl(archiveId, token, filename);
  129. openInSlicer(`${window.location.origin}${path}`, slicer);
  130. }
  131. } catch {
  132. // Fallback to direct URL (works when auth is disabled)
  133. const path = resourceType === 'source'
  134. ? api.getSource3mfForSlicer(archiveId, filename)
  135. : api.getArchiveForSlicer(archiveId, filename);
  136. openInSlicer(`${window.location.origin}${path}`, slicer);
  137. }
  138. }
  139. function ArchiveCard({
  140. archive,
  141. printerName,
  142. isSelected,
  143. onSelect,
  144. selectionMode,
  145. projects,
  146. isHighlighted,
  147. timeFormat = 'system',
  148. preferredSlicer = 'bambu_studio',
  149. useSlicerApi = false,
  150. currency,
  151. t,
  152. onNavigateToArchive,
  153. }: {
  154. archive: Archive;
  155. printerName: string;
  156. isSelected: boolean;
  157. onSelect: (id: number) => void;
  158. selectionMode: boolean;
  159. projects: ProjectListItem[] | undefined;
  160. isHighlighted?: boolean;
  161. timeFormat?: TimeFormat;
  162. preferredSlicer?: SlicerType;
  163. useSlicerApi?: boolean;
  164. currency: string;
  165. t: TFunction;
  166. onNavigateToArchive?: (archiveId: number) => void;
  167. }) {
  168. // Debug: log when card is highlighted
  169. if (isHighlighted) {
  170. console.log('ArchiveCard isHighlighted=true for archive:', archive.id);
  171. }
  172. const queryClient = useQueryClient();
  173. const { showToast } = useToast();
  174. const { hasPermission, canModify } = useAuth();
  175. const isMobile = useIsMobile();
  176. const navigate = useNavigate();
  177. const [showReprint, setShowReprint] = useState(false);
  178. const [showSliceModal, setShowSliceModal] = useState(false);
  179. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  180. // #1343: when true, the delete also drops the row from Quick Stats. Default
  181. // off — soft delete preserves the archive's filament/time/cost contribution.
  182. const [deletePurgeStats, setDeletePurgeStats] = useState(false);
  183. const [showEdit, setShowEdit] = useState(false);
  184. const [showPrintLog, setShowPrintLog] = useState(false);
  185. const [showTimelapse, setShowTimelapse] = useState(false);
  186. const [showTimelapseSelect, setShowTimelapseSelect] = useState(false);
  187. const [availableTimelapses, setAvailableTimelapses] = useState<Array<{ name: string; path: string; size: number; mtime: string | null }>>([]);
  188. const [showQRCode, setShowQRCode] = useState(false);
  189. const [showPhotos, setShowPhotos] = useState(false);
  190. const [showProjectPage, setShowProjectPage] = useState(false);
  191. const [showSchedule, setShowSchedule] = useState(false);
  192. const [showDeleteSource3mfConfirm, setShowDeleteSource3mfConfirm] = useState(false);
  193. const [showDeleteF3dConfirm, setShowDeleteF3dConfirm] = useState(false);
  194. const [showDeleteTimelapseConfirm, setShowDeleteTimelapseConfirm] = useState(false);
  195. const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
  196. const [currentPlateIndex, setCurrentPlateIndex] = useState<number | null>(null);
  197. const [showPlateNav, setShowPlateNav] = useState(false);
  198. const [platePickerPlates, setPlatePickerPlates] = useState<PlateMetadata[] | null>(null);
  199. const source3mfInputRef = useRef<HTMLInputElement>(null);
  200. const f3dInputRef = useRef<HTMLInputElement>(null);
  201. const timelapseInputRef = useRef<HTMLInputElement>(null);
  202. // Fetch plates data for multi-plate browsing (lazy - only when hovering)
  203. const { data: platesData } = useQuery({
  204. queryKey: ['archive-plates', archive.id],
  205. queryFn: () => api.getArchivePlates(archive.id),
  206. enabled: showPlateNav, // Only fetch when user hovers to see navigation
  207. staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  208. });
  209. // Use pre-computed duplicate sequence and original archive ID from list response
  210. const duplicateSequence = archive.duplicate_sequence ?? 0;
  211. const originalArchiveId = archive.original_archive_id ?? null;
  212. const plates = platesData?.plates ?? [];
  213. const isMultiPlate = platesData?.is_multi_plate ?? false;
  214. const displayPlateIndex = currentPlateIndex ?? 0;
  215. // 3D Preview click handler. Multi-plate archives show the plate picker
  216. // first; single-plate archives navigate straight into the viewer. Source-
  217. // only archives (no sliced gcode, e.g. pure project 3MFs from BambuStudio
  218. // that carry only plate PNG/JSON metadata) get a toast — there's nothing
  219. // the gcode viewer can render for them.
  220. const openGcodeViewer = async () => {
  221. try {
  222. const resp = await api.getArchivePlates(archive.id);
  223. if (resp.has_gcode === false) {
  224. showToast(t('archives.platePicker.noGcode'), 'info');
  225. return;
  226. }
  227. if (resp.is_multi_plate && resp.plates.length > 1) {
  228. setPlatePickerPlates(resp.plates);
  229. return;
  230. }
  231. } catch {
  232. // Swallow — fall through to the no-plate navigate below so the viewer
  233. // still opens on the first plate (the backend's default).
  234. }
  235. navigate(`/gcode-viewer?archive=${archive.id}`);
  236. };
  237. const timelapseDeleteMutation = useMutation({
  238. mutationFn: () => api.deleteArchiveTimelapse(archive.id),
  239. onSuccess: () => {
  240. queryClient.invalidateQueries({ queryKey: ['archives'] });
  241. showToast(t('archives.toast.timelapseRemoved'));
  242. },
  243. onError: (error: Error) => {
  244. showToast(error.message || t('archives.toast.failedRemoveTimelapse'), 'error');
  245. },
  246. });
  247. const timelapseUploadMutation = useMutation({
  248. mutationFn: (file: File) => api.uploadArchiveTimelapse(archive.id, file),
  249. onSuccess: (data) => {
  250. queryClient.invalidateQueries({ queryKey: ['archives'] });
  251. showToast(t('archives.toast.timelapseUploaded', { filename: data.filename }));
  252. },
  253. onError: (error: Error) => {
  254. showToast(error.message || t('archives.toast.failedUploadTimelapse'), 'error');
  255. },
  256. });
  257. const source3mfUploadMutation = useMutation({
  258. mutationFn: (file: File) => api.uploadSource3mf(archive.id, file),
  259. onSuccess: (data) => {
  260. queryClient.invalidateQueries({ queryKey: ['archives'] });
  261. showToast(t('archives.toast.source3mfAttached', { filename: data.filename }));
  262. },
  263. onError: (error: Error) => {
  264. showToast(error.message || t('archives.toast.failedUploadSource3mf'), 'error');
  265. },
  266. });
  267. const source3mfDeleteMutation = useMutation({
  268. mutationFn: () => api.deleteSource3mf(archive.id),
  269. onSuccess: () => {
  270. queryClient.invalidateQueries({ queryKey: ['archives'] });
  271. showToast(t('archives.toast.source3mfRemoved'));
  272. },
  273. onError: (error: Error) => {
  274. showToast(error.message || t('archives.toast.failedRemoveSource3mf'), 'error');
  275. },
  276. });
  277. const f3dUploadMutation = useMutation({
  278. mutationFn: (file: File) => api.uploadF3d(archive.id, file),
  279. onSuccess: (data) => {
  280. queryClient.invalidateQueries({ queryKey: ['archives'] });
  281. showToast(t('archives.toast.f3dAttached', { filename: data.filename }));
  282. },
  283. onError: (error: Error) => {
  284. showToast(error.message || t('archives.toast.failedUploadF3d'), 'error');
  285. },
  286. });
  287. const f3dDeleteMutation = useMutation({
  288. mutationFn: () => api.deleteF3d(archive.id),
  289. onSuccess: () => {
  290. queryClient.invalidateQueries({ queryKey: ['archives'] });
  291. showToast(t('archives.toast.f3dRemoved'));
  292. },
  293. onError: (error: Error) => {
  294. showToast(error.message || t('archives.toast.failedRemoveF3d'), 'error');
  295. },
  296. });
  297. const timelapseScanMutation = useMutation({
  298. mutationFn: () => api.scanArchiveTimelapse(archive.id),
  299. onSuccess: (data) => {
  300. if (data.status === 'attached') {
  301. queryClient.invalidateQueries({ queryKey: ['archives'] });
  302. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  303. } else if (data.status === 'exists') {
  304. showToast(t('archives.toast.timelapseAlreadyAttached'));
  305. } else if (data.status === 'not_found' && data.available_files && data.available_files.length > 0) {
  306. // Show selection dialog
  307. setAvailableTimelapses(data.available_files);
  308. setShowTimelapseSelect(true);
  309. } else {
  310. showToast(data.message || t('archives.toast.noMatchingTimelapse'), 'warning');
  311. }
  312. },
  313. onError: (error: Error) => {
  314. showToast(error.message || t('archives.toast.failedScanTimelapse'), 'error');
  315. },
  316. });
  317. const timelapseSelectMutation = useMutation({
  318. mutationFn: (filename: string) => api.selectArchiveTimelapse(archive.id, filename),
  319. onSuccess: (data) => {
  320. queryClient.invalidateQueries({ queryKey: ['archives'] });
  321. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  322. setShowTimelapseSelect(false);
  323. setAvailableTimelapses([]);
  324. },
  325. onError: (error: Error) => {
  326. showToast(error.message || t('archives.toast.failedAttachTimelapse'), 'error');
  327. },
  328. });
  329. const deleteMutation = useMutation({
  330. mutationFn: (purgeStats: boolean) => api.deleteArchive(archive.id, purgeStats),
  331. onSuccess: () => {
  332. queryClient.invalidateQueries({ queryKey: ['archives'] });
  333. showToast(t('archives.toast.archiveDeleted'));
  334. },
  335. onError: () => {
  336. showToast(t('archives.toast.failedDeleteArchive'), 'error');
  337. },
  338. });
  339. const favoriteMutation = useMutation({
  340. mutationFn: () => api.toggleFavorite(archive.id),
  341. onSuccess: (data) => {
  342. queryClient.invalidateQueries({ queryKey: ['archives'] });
  343. showToast(data.is_favorite ? t('archives.toast.addedToFavorites') : t('archives.toast.removedFromFavorites'));
  344. },
  345. });
  346. // Query for linked folders
  347. const { data: linkedFolders } = useQuery({
  348. queryKey: ['archive-folders', archive.id],
  349. queryFn: () => api.getLibraryFoldersByArchive(archive.id),
  350. });
  351. const assignProjectMutation = useMutation({
  352. mutationFn: (projectId: number | null) => api.updateArchive(archive.id, { project_id: projectId }),
  353. onSuccess: () => {
  354. queryClient.invalidateQueries({ queryKey: ['archives'] });
  355. queryClient.invalidateQueries({ queryKey: ['projects'] });
  356. showToast(t('archives.toast.projectUpdated'));
  357. },
  358. onError: () => {
  359. showToast(t('archives.toast.failedUpdateProject'), 'error');
  360. },
  361. });
  362. const handleContextMenu = (e: React.MouseEvent) => {
  363. e.preventDefault();
  364. setContextMenu({ x: e.clientX, y: e.clientY });
  365. };
  366. const isGcodeFile = isSlicedFile(archive);
  367. const contextMenuItems: ContextMenuItem[] = [
  368. // For gcode files: show Print option
  369. // For source files: show Slice as the primary action
  370. ...(isGcodeFile ? [
  371. {
  372. label: t('archives.menu.print'),
  373. icon: <Printer className="w-4 h-4" />,
  374. onClick: () => setShowReprint(true),
  375. disabled: !archive.file_path || !canModify('archives', 'reprint', archive.created_by_id),
  376. title: !archive.file_path ? t('archives.card.noFileForReprint') : !canModify('archives', 'reprint', archive.created_by_id) ? t('archives.permission.noReprint') : undefined,
  377. },
  378. {
  379. label: t('archives.menu.schedule'),
  380. icon: <Calendar className="w-4 h-4" />,
  381. onClick: () => setShowSchedule(true),
  382. disabled: !archive.file_path || !hasPermission('queue:create'),
  383. title: !archive.file_path ? t('archives.card.noFileForReprint') : !hasPermission('queue:create') ? t('archives.permission.noAddToQueue') : undefined,
  384. },
  385. {
  386. label: t('archives.menu.openInBambuStudio'),
  387. icon: <ExternalLink className="w-4 h-4" />,
  388. onClick: () => {
  389. const filename = archive.print_name || archive.filename || 'model';
  390. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  391. },
  392. disabled: !archive.file_path,
  393. title: !archive.file_path ? t('archives.card.noFileForReprint') : undefined,
  394. },
  395. ] : [
  396. {
  397. label: t('archives.menu.slice'),
  398. icon: useSlicerApi ? <Cog className="w-4 h-4" /> : <ExternalLink className="w-4 h-4" />,
  399. onClick: () => {
  400. if (useSlicerApi) {
  401. setShowSliceModal(true);
  402. } else {
  403. const filename = archive.print_name || archive.filename || 'model';
  404. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  405. }
  406. },
  407. },
  408. ]),
  409. {
  410. label: archive.external_url ? t('archives.menu.externalLink') : t('archives.menu.viewOnMakerWorld'),
  411. icon: <Globe className="w-4 h-4" />,
  412. onClick: () => {
  413. const url = archive.external_url || archive.makerworld_url;
  414. if (url) window.open(url, '_blank');
  415. },
  416. disabled: !archive.external_url && !archive.makerworld_url,
  417. },
  418. { label: '', divider: true, onClick: () => {} },
  419. {
  420. label: t('archives.menu.preview3d'),
  421. icon: <Box className="w-4 h-4" />,
  422. onClick: () => { openGcodeViewer(); },
  423. },
  424. {
  425. label: t('archives.menu.viewTimelapse'),
  426. icon: <Film className="w-4 h-4" />,
  427. onClick: () => setShowTimelapse(true),
  428. disabled: !archive.timelapse_path,
  429. },
  430. {
  431. label: t('archives.menu.scanForTimelapse'),
  432. icon: <ScanSearch className="w-4 h-4" />,
  433. onClick: () => timelapseScanMutation.mutate(),
  434. disabled: !archive.printer_id || !!archive.timelapse_path || timelapseScanMutation.isPending || !canModify('archives', 'update', archive.created_by_id),
  435. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  436. },
  437. {
  438. label: t('archives.menu.uploadTimelapse'),
  439. icon: <Upload className="w-4 h-4" />,
  440. onClick: () => timelapseInputRef.current?.click(),
  441. disabled: !!archive.timelapse_path || !canModify('archives', 'update', archive.created_by_id),
  442. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  443. },
  444. ...(archive.timelapse_path ? [{
  445. label: t('archives.menu.removeTimelapse'),
  446. icon: <Trash2 className="w-4 h-4" />,
  447. onClick: () => setShowDeleteTimelapseConfirm(true),
  448. danger: true,
  449. disabled: !canModify('archives', 'update', archive.created_by_id),
  450. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  451. }] : []),
  452. { label: '', divider: true, onClick: () => {} },
  453. {
  454. label: archive.source_3mf_path ? t('archives.menu.downloadSource3mf') : t('archives.menu.uploadSource3mf'),
  455. icon: <FileCode className="w-4 h-4" />,
  456. onClick: () => {
  457. if (archive.source_3mf_path) {
  458. api.downloadSource3mf(archive.id).catch((err) => {
  459. console.error('Source 3MF download failed:', err);
  460. });
  461. } else {
  462. source3mfInputRef.current?.click();
  463. }
  464. },
  465. disabled: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id),
  466. title: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUploadFiles') : undefined,
  467. },
  468. ...(archive.source_3mf_path ? [{
  469. label: t('archives.menu.replaceSource3mf'),
  470. icon: <Upload className="w-4 h-4" />,
  471. onClick: () => source3mfInputRef.current?.click(),
  472. disabled: !canModify('archives', 'update', archive.created_by_id),
  473. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  474. },
  475. {
  476. label: t('archives.menu.removeSource3mf'),
  477. icon: <Trash2 className="w-4 h-4" />,
  478. onClick: () => setShowDeleteSource3mfConfirm(true),
  479. danger: true,
  480. disabled: !canModify('archives', 'update', archive.created_by_id),
  481. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  482. }] : []),
  483. {
  484. label: archive.f3d_path ? t('archives.menu.replaceF3d') : t('archives.menu.uploadF3d'),
  485. icon: <Box className="w-4 h-4" />,
  486. onClick: () => f3dInputRef.current?.click(),
  487. disabled: !canModify('archives', 'update', archive.created_by_id),
  488. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  489. },
  490. ...(archive.f3d_path ? [{
  491. label: t('archives.menu.downloadF3d'),
  492. icon: <Download className="w-4 h-4" />,
  493. onClick: () => {
  494. api.downloadF3d(archive.id).catch((err) => {
  495. console.error('F3D download failed:', err);
  496. });
  497. },
  498. },
  499. {
  500. label: t('archives.menu.removeF3d'),
  501. icon: <Trash2 className="w-4 h-4" />,
  502. onClick: () => setShowDeleteF3dConfirm(true),
  503. danger: true,
  504. disabled: !canModify('archives', 'update', archive.created_by_id),
  505. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  506. }] : []),
  507. { label: '', divider: true, onClick: () => {} },
  508. {
  509. label: t('archives.menu.download'),
  510. icon: <Download className="w-4 h-4" />,
  511. onClick: () => {
  512. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  513. console.error('Archive download failed:', err);
  514. });
  515. },
  516. disabled: !hasPermission('archives:read'),
  517. title: !hasPermission('archives:read') ? t('archives.permission.noDownload') : undefined,
  518. },
  519. {
  520. label: t('archives.menu.copyDownloadLink'),
  521. icon: <Copy className="w-4 h-4" />,
  522. onClick: () => {
  523. const url = `${window.location.origin}${api.getArchiveDownload(archive.id)}`;
  524. navigator.clipboard.writeText(url).then(() => {
  525. showToast(t('archives.toast.linkCopied'));
  526. }).catch(() => {
  527. showToast(t('archives.toast.failedCopyLink'), 'error');
  528. });
  529. },
  530. disabled: !hasPermission('archives:read'),
  531. title: !hasPermission('archives:read') ? t('archives.permission.noCopyLink') : undefined,
  532. },
  533. {
  534. label: t('archives.menu.qrCode'),
  535. icon: <QrCode className="w-4 h-4" />,
  536. onClick: () => setShowQRCode(true),
  537. },
  538. {
  539. label: archive.photos?.length ? t('archives.menu.viewPhotosCount', { count: archive.photos.length }) : t('archives.menu.viewPhotos'),
  540. icon: <Camera className="w-4 h-4" />,
  541. onClick: () => setShowPhotos(true),
  542. disabled: !archive.photos?.length,
  543. },
  544. {
  545. label: t('archives.menu.projectPage'),
  546. icon: <FileText className="w-4 h-4" />,
  547. onClick: () => setShowProjectPage(true),
  548. },
  549. { label: '', divider: true, onClick: () => {} },
  550. {
  551. label: archive.is_favorite ? t('archives.menu.removeFromFavorites') : t('archives.menu.addToFavorites'),
  552. icon: <Star className={`w-4 h-4 ${archive.is_favorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />,
  553. onClick: () => favoriteMutation.mutate(),
  554. disabled: !canModify('archives', 'update', archive.created_by_id),
  555. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  556. },
  557. {
  558. label: t('archives.menu.edit'),
  559. icon: <Pencil className="w-4 h-4" />,
  560. onClick: () => setShowEdit(true),
  561. disabled: !canModify('archives', 'update', archive.created_by_id),
  562. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  563. },
  564. {
  565. label: t('archives.menu.printLog'),
  566. icon: <History className="w-4 h-4" />,
  567. onClick: () => setShowPrintLog(true),
  568. },
  569. ...(archive.project_id && archive.project_name ? [{
  570. label: t('archives.menu.goToProject', { name: archive.project_name }),
  571. icon: <FolderKanban className="w-4 h-4 text-bambu-green" />,
  572. onClick: () => window.location.href = '/projects',
  573. }] : []),
  574. {
  575. label: t('archives.menu.addToProject'),
  576. icon: <FolderKanban className="w-4 h-4" />,
  577. onClick: () => {},
  578. disabled: !canModify('archives', 'update', archive.created_by_id),
  579. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  580. submenuSearchPlaceholder: (projects?.filter(p => p.status === 'active').length ?? 0) > 5
  581. ? t('archives.menu.searchProjects')
  582. : undefined,
  583. submenu: (() => {
  584. const items: ContextMenuItem[] = [];
  585. // Add "Remove from Project" if archive is in a project
  586. if (archive.project_id) {
  587. items.push({
  588. label: t('archives.menu.removeFromProject'),
  589. icon: <X className="w-4 h-4" />,
  590. onClick: () => assignProjectMutation.mutate(null),
  591. disabled: !canModify('archives', 'update', archive.created_by_id),
  592. });
  593. }
  594. // Add project options
  595. if (!projects) {
  596. items.push({
  597. label: t('archives.menu.loading'),
  598. icon: <Loader2 className="w-4 h-4 animate-spin" />,
  599. onClick: () => {},
  600. disabled: true,
  601. });
  602. } else {
  603. const activeProjects = projects
  604. .filter(p => p.status === 'active')
  605. .sort((a, b) => a.name.localeCompare(b.name));
  606. if (activeProjects.length === 0) {
  607. items.push({
  608. label: t('archives.menu.noProjectsAvailable'),
  609. icon: <FolderKanban className="w-4 h-4 opacity-50" />,
  610. onClick: () => {},
  611. disabled: true,
  612. });
  613. } else {
  614. activeProjects.forEach(p => {
  615. items.push({
  616. label: p.name,
  617. icon: <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: p.color || '#888' }} />,
  618. onClick: () => assignProjectMutation.mutate(p.id),
  619. disabled: archive.project_id === p.id || !canModify('archives', 'update', archive.created_by_id),
  620. });
  621. });
  622. }
  623. }
  624. return items;
  625. })(),
  626. },
  627. {
  628. label: isSelected ? t('archives.menu.deselect') : t('archives.menu.select'),
  629. icon: isSelected ? <CheckSquare className="w-4 h-4" /> : <Square className="w-4 h-4" />,
  630. onClick: () => onSelect(archive.id),
  631. },
  632. { label: '', divider: true, onClick: () => {} },
  633. {
  634. label: t('archives.menu.delete'),
  635. icon: <Trash2 className="w-4 h-4" />,
  636. onClick: () => setShowDeleteConfirm(true),
  637. danger: true,
  638. disabled: !canModify('archives', 'delete', archive.created_by_id),
  639. title: !canModify('archives', 'delete', archive.created_by_id) ? t('archives.permission.noDelete') : undefined,
  640. },
  641. ];
  642. return (
  643. <Card
  644. data-archive-id={archive.id}
  645. className={`relative flex flex-col group ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode ? 'cursor-pointer' : ''}`}
  646. style={isHighlighted ? { outline: '4px solid #facc15', outlineOffset: '2px' } : undefined}
  647. onContextMenu={handleContextMenu}
  648. onClick={selectionMode ? () => onSelect(archive.id) : undefined}
  649. >
  650. {/* Selection checkbox */}
  651. {selectionMode && (
  652. <button
  653. className="absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors"
  654. onClick={(e) => { e.stopPropagation(); onSelect(archive.id); }}
  655. >
  656. {isSelected ? (
  657. <CheckSquare className="w-5 h-5 text-bambu-green" />
  658. ) : (
  659. <Square className="w-5 h-5 text-white" />
  660. )}
  661. </button>
  662. )}
  663. {/* Thumbnail with plate navigation */}
  664. <div
  665. className="aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl"
  666. onMouseEnter={() => setShowPlateNav(true)}
  667. onMouseLeave={() => setShowPlateNav(false)}
  668. >
  669. {archive.thumbnail_path ? (
  670. <img
  671. src={
  672. currentPlateIndex !== null && plates.length > 0
  673. ? api.getArchivePlateThumbnail(archive.id, plates[displayPlateIndex]?.index ?? 0)
  674. : api.getArchiveThumbnail(archive.id)
  675. }
  676. alt={archive.print_name || archive.filename}
  677. className="w-full h-full object-cover"
  678. />
  679. ) : (
  680. <div className="w-full h-full flex items-center justify-center">
  681. <Image className="w-12 h-12 text-bambu-dark-tertiary" />
  682. </div>
  683. )}
  684. {/* Plate navigation - only show for multi-plate archives */}
  685. {isMultiPlate && plates.length > 1 && (
  686. <>
  687. {/* Left arrow */}
  688. <button
  689. className={`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${
  690. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  691. }`}
  692. onClick={(e) => {
  693. e.stopPropagation();
  694. setCurrentPlateIndex((prev) => {
  695. const current = prev ?? 0;
  696. return current > 0 ? current - 1 : plates.length - 1;
  697. });
  698. }}
  699. title={t('archives.card.previousPlate')}
  700. >
  701. <ChevronLeft className="w-4 h-4 text-white" />
  702. </button>
  703. {/* Right arrow */}
  704. <button
  705. className={`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${
  706. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  707. }`}
  708. onClick={(e) => {
  709. e.stopPropagation();
  710. setCurrentPlateIndex((prev) => {
  711. const current = prev ?? 0;
  712. return current < plates.length - 1 ? current + 1 : 0;
  713. });
  714. }}
  715. title={t('archives.card.nextPlate')}
  716. >
  717. <ChevronRight className="w-4 h-4 text-white" />
  718. </button>
  719. {/* Dots indicator */}
  720. <div
  721. className={`absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-1 px-2 py-1 rounded-full bg-black/50 transition-all ${
  722. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  723. }`}
  724. >
  725. {plates.map((plate, idx) => (
  726. <button
  727. key={plate.index}
  728. className={`w-2 h-2 rounded-full transition-colors ${
  729. idx === displayPlateIndex ? 'bg-bambu-green' : 'bg-white/50 hover:bg-white/80'
  730. }`}
  731. onClick={(e) => {
  732. e.stopPropagation();
  733. setCurrentPlateIndex(idx);
  734. }}
  735. title={plate.name || t('archives.card.plateNumber', { index: plate.index })}
  736. />
  737. ))}
  738. </div>
  739. </>
  740. )}
  741. {/* Context menu button - visible on mobile, shows on hover for desktop */}
  742. <button
  743. className={`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${
  744. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  745. } ${selectionMode ? 'left-10' : ''}`}
  746. onClick={(e) => {
  747. e.stopPropagation();
  748. const rect = e.currentTarget.getBoundingClientRect();
  749. setContextMenu({ x: rect.left, y: rect.bottom + 4 });
  750. }}
  751. title={t('archives.card.moreOptions')}
  752. >
  753. <MoreVertical className="w-5 h-5 text-white" />
  754. </button>
  755. {/* Favorite star */}
  756. <button
  757. className={`absolute top-2 right-2 p-1 rounded transition-colors ${
  758. canModify('archives', 'update', archive.created_by_id)
  759. ? 'bg-black/50 hover:bg-black/70'
  760. : 'bg-black/30 cursor-not-allowed'
  761. }`}
  762. onClick={(e) => {
  763. e.stopPropagation();
  764. if (canModify('archives', 'update', archive.created_by_id)) {
  765. favoriteMutation.mutate();
  766. }
  767. }}
  768. disabled={!canModify('archives', 'update', archive.created_by_id)}
  769. title={!canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : (archive.is_favorite ? t('archives.card.removeFromFavorites') : t('archives.card.addToFavorites'))}
  770. >
  771. <Star
  772. className={`w-5 h-5 ${archive.is_favorite ? 'text-yellow-400 fill-yellow-400' : 'text-white'} ${!canModify('archives', 'update', archive.created_by_id) ? 'opacity-50' : ''}`}
  773. />
  774. </button>
  775. {(archive.status === 'failed' || archive.status === 'aborted') && (
  776. <div className="absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white">
  777. {archive.status === 'aborted' ? t('archives.card.cancelled') : t('archives.card.failed')}
  778. </div>
  779. )}
  780. {/* Duplicate badge */}
  781. {archive.duplicate_count > 0 && duplicateSequence > 0 && originalArchiveId && (
  782. <button
  783. onClick={(e) => {
  784. e.stopPropagation();
  785. onNavigateToArchive?.(originalArchiveId);
  786. }}
  787. className="absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 hover:bg-purple-600/90 text-white flex items-center gap-1 transition-colors cursor-pointer"
  788. title={t('archives.viewOriginalPrint', { id: originalArchiveId })}
  789. >
  790. <Copy className="w-3 h-3" />
  791. #{duplicateSequence}
  792. </button>
  793. )}
  794. {archive.duplicate_count > 0 && duplicateSequence === 0 && (
  795. <span
  796. className="absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1"
  797. title={`${archive.duplicate_count} reprint${archive.duplicate_count === 1 ? '' : 's'}`}
  798. >
  799. <GitBranch className="w-3 h-3" />
  800. +{archive.duplicate_count}
  801. </span>
  802. )}
  803. {/* Source 3MF badge */}
  804. {archive.source_3mf_path && (
  805. <button
  806. className="absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  807. onClick={(e) => {
  808. e.stopPropagation();
  809. // Open source 3MF in Bambu Studio - use filename in URL for slicer compatibility
  810. const sourceName = (archive.print_name || archive.filename || 'source').replace(/\.gcode\.3mf$/i, '') + '_source';
  811. openInSlicerWithToken(archive.id, sourceName, 'source', preferredSlicer);
  812. }}
  813. title={t('archives.card.openSource3mf')}
  814. >
  815. <FileCode className="w-4 h-4 text-orange-400" />
  816. </button>
  817. )}
  818. {/* F3D badge */}
  819. {archive.f3d_path && (
  820. <button
  821. className={`absolute bottom-2 ${archive.source_3mf_path ? 'left-12' : 'left-2'} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`}
  822. onClick={(e) => {
  823. e.stopPropagation();
  824. // Download F3D file
  825. api.downloadF3d(archive.id).catch((err) => {
  826. console.error('F3D download failed:', err);
  827. });
  828. }}
  829. title={t('archives.card.downloadF3d')}
  830. >
  831. <Box className="w-4 h-4 text-cyan-400" />
  832. </button>
  833. )}
  834. {/* 3D preview badge */}
  835. <button
  836. className="absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  837. onClick={(e) => {
  838. e.stopPropagation();
  839. openGcodeViewer();
  840. }}
  841. title={t('archives.card.preview3d')}
  842. >
  843. <Layers className="w-4 h-4 text-white" />
  844. </button>
  845. {/* Timelapse badge */}
  846. {archive.timelapse_path && (
  847. <button
  848. className="absolute bottom-2 right-12 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  849. onClick={(e) => {
  850. e.stopPropagation();
  851. setShowTimelapse(true);
  852. }}
  853. title={t('archives.card.viewTimelapse')}
  854. >
  855. <Film className="w-4 h-4 text-bambu-green" />
  856. </button>
  857. )}
  858. {/* Photos badge */}
  859. {archive.photos && archive.photos.length > 0 && (
  860. <button
  861. className={`absolute bottom-2 ${archive.timelapse_path ? 'right-[5.5rem]' : 'right-12'} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`}
  862. onClick={(e) => {
  863. e.stopPropagation();
  864. setShowPhotos(true);
  865. }}
  866. title={archive.photos.length === 1 ? t('archives.card.viewPhoto') : t('archives.card.viewPhotos', { count: archive.photos.length })}
  867. >
  868. <Camera className="w-4 h-4 text-blue-400" />
  869. {archive.photos.length > 1 && (
  870. <span className="absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full text-[10px] text-white flex items-center justify-center">
  871. {archive.photos.length}
  872. </span>
  873. )}
  874. </button>
  875. )}
  876. {/* Linked folder badge */}
  877. {linkedFolders && linkedFolders.length > 0 && (
  878. <Link
  879. to={`/files?folder=${linkedFolders[0].id}`}
  880. className="absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  881. onClick={(e) => e.stopPropagation()}
  882. title={t('archives.card.openFolder', { name: linkedFolders[0].name })}
  883. style={{ left: archive.source_3mf_path ? (archive.f3d_path ? '5.5rem' : '3rem') : (archive.f3d_path ? '3rem' : '0.5rem') }}
  884. >
  885. <FolderOpen className="w-4 h-4 text-yellow-400" />
  886. </Link>
  887. )}
  888. </div>
  889. <CardContent className="p-4 flex-1 flex flex-col">
  890. {/* Archive ID */}
  891. <p className="text-[10px] text-bambu-gray/70 mb-1">#{archive.id}</p>
  892. {/* Title */}
  893. <div className="flex items-center justify-between gap-2 mb-1">
  894. <h3 className="min-w-0 font-medium text-white truncate">
  895. {archive.print_name || archive.filename}
  896. </h3>
  897. <Button
  898. variant="ghost"
  899. size="sm"
  900. className="p-1 sm:p-1.5 shrink-0"
  901. onClick={() => setShowEdit(true)}
  902. disabled={!canModify('archives', 'update', archive.created_by_id)}
  903. title={!canModify('archives', 'update', archive.created_by_id) ? t('archives.card.noPermissionEdit') : t('archives.card.edit')}
  904. >
  905. <Pencil className="w-3 h-3 sm:w-4 sm:h-4" />
  906. </Button>
  907. </div>
  908. <div className="flex items-center gap-2 mb-3 flex-wrap">
  909. <p className="text-xs text-bambu-gray">{printerName}</p>
  910. {(() => {
  911. const bed = getBedTypeInfo(archive.bed_type);
  912. return bed ? (
  913. <img src={bed.icon} alt={bed.label} title={bed.label} className="w-4 h-4 flex-shrink-0" />
  914. ) : null;
  915. })()}
  916. {/* File type badge */}
  917. <span
  918. className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${
  919. isSlicedFile(archive)
  920. ? 'bg-bambu-green/20 text-bambu-green'
  921. : 'bg-orange-500/20 text-orange-400'
  922. }`}
  923. title={
  924. isSlicedFile(archive)
  925. ? t('archives.card.slicedFile')
  926. : t('archives.card.sourceFile')
  927. }
  928. >
  929. {isSlicedFile(archive) ? t('archives.card.gcode') : t('archives.card.source')}
  930. </span>
  931. {/* File hash badge */}
  932. {archive.content_hash && (
  933. <span
  934. className="text-[10px] px-1.5 py-0.5 rounded font-mono bg-bambu-dark-tertiary/50 text-bambu-gray-light opacity-0 transition-opacity duration-150 group-hover:opacity-100"
  935. title={`SHA256: ${archive.content_hash}`}
  936. >
  937. {archive.content_hash.slice(0, 8).toUpperCase()}
  938. </span>
  939. )}
  940. {archive.project_name && (
  941. <span
  942. className="text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]"
  943. style={{
  944. backgroundColor: `${projects?.find(p => p.id === archive.project_id)?.color || '#6b7280'}20`,
  945. color: projects?.find(p => p.id === archive.project_id)?.color || '#6b7280'
  946. }}
  947. title={t('archives.card.project', { name: archive.project_name })}
  948. >
  949. {archive.project_name}
  950. </span>
  951. )}
  952. {archive.run_count > 1 && (
  953. <button
  954. className="text-[10px] px-1.5 py-0.5 rounded font-medium bg-bambu-orange/20 text-bambu-orange hover:bg-bambu-orange/30 transition-colors cursor-pointer"
  955. onClick={(e) => {
  956. e.stopPropagation();
  957. setShowPrintLog(true);
  958. }}
  959. title={t('archives.card.runsBadgeTitle', {
  960. count: archive.run_count,
  961. successful: archive.successful_run_count,
  962. failed: archive.failed_run_count,
  963. })}
  964. >
  965. {t('archives.card.runsBadge', { count: archive.run_count })}
  966. </button>
  967. )}
  968. </div>
  969. {/* Stats */}
  970. <div className="grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]">
  971. {(archive.print_time_seconds || archive.actual_time_seconds) && (
  972. <div className="flex items-center gap-1.5 text-bambu-gray" title={
  973. archive.time_accuracy
  974. ? `Estimated: ${formatDuration(archive.print_time_seconds || 0)}\nActual: ${formatDuration(archive.actual_time_seconds || 0)}\nAccuracy: ${archive.time_accuracy.toFixed(0)}%`
  975. : archive.actual_time_seconds
  976. ? `Actual: ${formatDuration(archive.actual_time_seconds)}`
  977. : `Estimated: ${formatDuration(archive.print_time_seconds || 0)}`
  978. }>
  979. <Clock className="w-3 h-3" />
  980. {formatDuration(archive.actual_time_seconds || archive.print_time_seconds || 0)}
  981. {archive.time_accuracy && (
  982. <span className={`text-[10px] px-1 rounded ${
  983. archive.time_accuracy >= 95 && archive.time_accuracy <= 105
  984. ? 'bg-bambu-green/20 text-bambu-green'
  985. : archive.time_accuracy > 105
  986. ? 'bg-blue-500/20 text-blue-400'
  987. : 'bg-orange-500/20 text-orange-400'
  988. }`}>
  989. {archive.time_accuracy > 100 ? '+' : ''}{(archive.time_accuracy - 100).toFixed(0)}%
  990. </span>
  991. )}
  992. </div>
  993. )}
  994. {archive.filament_used_grams && (
  995. <div className="flex items-center gap-1.5 text-bambu-gray">
  996. <Package className="w-3 h-3" />
  997. {archive.filament_used_grams.toFixed(1)}g
  998. </div>
  999. )}
  1000. {(archive.cost != null || archive.energy_cost != null) && (
  1001. <div className="flex items-center gap-3 text-bambu-gray">
  1002. {archive.cost != null && (
  1003. <div className="flex items-center gap-1.5">
  1004. <Coins className="w-3 h-3" />
  1005. {currency}{archive.cost.toFixed(2)}
  1006. </div>
  1007. )}
  1008. {archive.energy_cost != null && (
  1009. <div className="flex items-center gap-1.5" title={`${t('stats.energyUsed')}: ${archive.energy_kwh?.toFixed(3) || 'N/A'} kWh`}>
  1010. <Zap className="w-3 h-3" />
  1011. {currency}{archive.energy_cost.toFixed(2)}
  1012. </div>
  1013. )}
  1014. </div>
  1015. )}
  1016. {(archive.layer_height || archive.total_layers) && (
  1017. <div className="flex items-center gap-1.5 text-bambu-gray">
  1018. <Layers className="w-3 h-3" />
  1019. {archive.total_layers && <span>{archive.total_layers === 1 ? t('archives.card.layer', { count: archive.total_layers }) : t('archives.card.layers', { count: archive.total_layers })}</span>}
  1020. {archive.total_layers && archive.layer_height && <span className="text-bambu-gray/50">·</span>}
  1021. {archive.layer_height && <span>{archive.layer_height}mm</span>}
  1022. </div>
  1023. )}
  1024. {archive.object_count != null && archive.object_count > 0 && (
  1025. <div className="flex items-center gap-1.5 text-bambu-gray" title={archive.object_count === 1 ? t('archives.card.object', { count: archive.object_count }) : t('archives.card.objects', { count: archive.object_count })}>
  1026. <Box className="w-3 h-3" />
  1027. {archive.object_count === 1 ? t('archives.card.object', { count: archive.object_count }) : t('archives.card.objects', { count: archive.object_count })}
  1028. </div>
  1029. )}
  1030. {archive.sliced_for_model && (
  1031. <div className="flex items-center gap-1.5 text-bambu-gray" title={t('archives.card.slicedFor', { model: archive.sliced_for_model })}>
  1032. <Printer className="w-3 h-3" />
  1033. {archive.sliced_for_model}
  1034. </div>
  1035. )}
  1036. {archive.filament_type && (
  1037. <div className="flex items-center gap-1.5 col-span-2">
  1038. <span className="text-bambu-gray text-xs">{archive.filament_type}</span>
  1039. {archive.filament_color && (
  1040. <div className="flex items-center gap-0.5 flex-wrap">
  1041. {archive.filament_color.split(',').map((color, i) => (
  1042. <div
  1043. key={i}
  1044. className="w-3 h-3 rounded-full border border-black/20"
  1045. style={{ backgroundColor: color }}
  1046. title={color}
  1047. />
  1048. ))}
  1049. </div>
  1050. )}
  1051. </div>
  1052. )}
  1053. </div>
  1054. {/* Tags & Notes */}
  1055. {(archive.tags || archive.notes) && (
  1056. <div className="flex flex-wrap items-center gap-1.5 mb-3">
  1057. {archive.notes && (
  1058. <div
  1059. className="flex items-center gap-1 px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs"
  1060. title={archive.notes}
  1061. >
  1062. <StickyNote className="w-3 h-3" />
  1063. </div>
  1064. )}
  1065. {archive.tags?.split(',').map((tag, i) => (
  1066. <span
  1067. key={i}
  1068. className="px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs"
  1069. >
  1070. {tag.trim()}
  1071. </span>
  1072. ))}
  1073. </div>
  1074. )}
  1075. {/* Spacer to push content to bottom */}
  1076. <div className="flex-1" />
  1077. {/* Date, Size & Creator */}
  1078. <div className="flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3">
  1079. <span>{formatDateTime(archive.created_at, timeFormat)}</span>
  1080. <div className="flex items-center gap-2">
  1081. {archive.created_by_username && (
  1082. <span className="flex items-center gap-1" title={t('archives.card.uploadedBy', { name: archive.created_by_username })}>
  1083. <User className="w-3 h-3" />
  1084. {archive.created_by_username}
  1085. </span>
  1086. )}
  1087. <span>{formatFileSize(archive.file_size)}</span>
  1088. </div>
  1089. </div>
  1090. {/* Actions */}
  1091. <div className="flex gap-1 mt-3">
  1092. {isSlicedFile(archive) ? (
  1093. // Sliced file - can print directly
  1094. <>
  1095. <Button
  1096. variant="primary"
  1097. size="sm"
  1098. className="flex-1 min-w-0 overflow-hidden"
  1099. onClick={() => setShowReprint(true)}
  1100. disabled={!archive.file_path || !canModify('archives', 'reprint', archive.created_by_id)}
  1101. title={!archive.file_path ? t('archives.card.noFileForReprint') : !canModify('archives', 'reprint', archive.created_by_id) ? t('archives.card.noPermissionReprint') : undefined}
  1102. >
  1103. <Printer className="w-3 h-3 flex-shrink-0" />
  1104. <span className="hidden xl:inline truncate">{t('archives.card.reprint')}</span>
  1105. </Button>
  1106. <Button
  1107. variant="secondary"
  1108. size="sm"
  1109. className="flex-1 min-w-0 overflow-hidden"
  1110. onClick={() => setShowSchedule(true)}
  1111. disabled={!archive.file_path || !hasPermission('queue:create')}
  1112. title={!archive.file_path ? t('archives.card.noFileForReprint') : !hasPermission('queue:create') ? t('archives.permission.noAddToQueue') : t('archives.card.schedulePrint')}
  1113. >
  1114. <Calendar className="w-3 h-3 flex-shrink-0" />
  1115. <span className="hidden xl:inline truncate">{t('archives.card.schedule')}</span>
  1116. </Button>
  1117. <Button
  1118. variant="secondary"
  1119. size="sm"
  1120. className="min-w-0 p-1 sm:p-1.5"
  1121. onClick={() => {
  1122. const filename = archive.print_name || archive.filename || 'model';
  1123. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1124. }}
  1125. title={t('archives.card.openInBambuStudio')}
  1126. >
  1127. <ExternalLink className="w-3 h-3 sm:w-4 sm:h-4" />
  1128. </Button>
  1129. </>
  1130. ) : (
  1131. // Source file only - "Slice" action
  1132. <Button
  1133. variant="primary"
  1134. size="sm"
  1135. className="flex-1 min-w-0 overflow-hidden"
  1136. onClick={() => {
  1137. if (useSlicerApi) {
  1138. setShowSliceModal(true);
  1139. } else {
  1140. const filename = archive.print_name || archive.filename || 'model';
  1141. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1142. }
  1143. }}
  1144. title={useSlicerApi ? t('slice.title') : t('archives.card.openInBambuStudioToSlice')}
  1145. >
  1146. {useSlicerApi ? (
  1147. <Cog className="w-3 h-3 flex-shrink-0" />
  1148. ) : (
  1149. <ExternalLink className="w-3 h-3 flex-shrink-0" />
  1150. )}
  1151. <span className="hidden xl:inline truncate">{t('archives.card.slice')}</span>
  1152. </Button>
  1153. )}
  1154. <Button
  1155. variant="secondary"
  1156. size="sm"
  1157. className="min-w-0 p-1 sm:p-1.5"
  1158. onClick={() => {
  1159. const url = archive.external_url || archive.makerworld_url;
  1160. if (url) window.open(url, '_blank');
  1161. }}
  1162. disabled={!archive.external_url && !archive.makerworld_url}
  1163. title={
  1164. archive.external_url
  1165. ? t('archives.card.externalLink')
  1166. : archive.makerworld_url
  1167. ? t('archives.card.makerWorld', { designer: archive.designer || t('archives.card.viewProject') })
  1168. : t('archives.card.noExternalLink')
  1169. }
  1170. >
  1171. <Globe className={`w-3 h-3 sm:w-4 sm:h-4 ${!archive.external_url && !archive.makerworld_url ? 'opacity-20' : ''}`} />
  1172. </Button>
  1173. <Button
  1174. variant="secondary"
  1175. size="sm"
  1176. className="min-w-0 p-1 sm:p-1.5"
  1177. onClick={() => {
  1178. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  1179. console.error('Archive download failed:', err);
  1180. });
  1181. }}
  1182. title={t('archives.card.download')}
  1183. >
  1184. <Download className="w-3 h-3 sm:w-4 sm:h-4" />
  1185. </Button>
  1186. <Button
  1187. variant="ghost"
  1188. size="sm"
  1189. className="min-w-0 p-1 sm:p-1.5"
  1190. onClick={() => setShowDeleteConfirm(true)}
  1191. disabled={!canModify('archives', 'delete', archive.created_by_id)}
  1192. title={!canModify('archives', 'delete', archive.created_by_id) ? t('archives.card.noPermissionDelete') : t('archives.card.delete')}
  1193. >
  1194. <Trash2 className="w-3 h-3 sm:w-4 sm:h-4 text-red-400" />
  1195. </Button>
  1196. </div>
  1197. </CardContent>
  1198. {/* Edit Modal */}
  1199. {showEdit && (
  1200. <EditArchiveModal
  1201. archive={archive}
  1202. onClose={() => setShowEdit(false)}
  1203. />
  1204. )}
  1205. {/* Print Log Modal — opened from the "N prints" badge or context menu (#1378) */}
  1206. {showPrintLog && (
  1207. <PrintLogModal
  1208. archiveId={archive.id}
  1209. archiveName={archive.print_name || archive.filename}
  1210. onClose={() => setShowPrintLog(false)}
  1211. />
  1212. )}
  1213. {/* Plate picker — shown only for multi-plate archives on 3D Preview click */}
  1214. {platePickerPlates && (
  1215. <PlatePickerModal
  1216. plates={platePickerPlates}
  1217. onSelect={(plateIndex) => {
  1218. setPlatePickerPlates(null);
  1219. navigate(`/gcode-viewer?archive=${archive.id}&plate=${plateIndex}`);
  1220. }}
  1221. onClose={() => setPlatePickerPlates(null)}
  1222. />
  1223. )}
  1224. {/* Reprint Modal */}
  1225. {showReprint && (
  1226. <PrintModal
  1227. mode="reprint"
  1228. archiveId={archive.id}
  1229. archiveName={archive.print_name || archive.filename}
  1230. onClose={() => setShowReprint(false)}
  1231. />
  1232. )}
  1233. {/* Slice Modal */}
  1234. {showSliceModal && (
  1235. <SliceModal
  1236. source={{ kind: 'archive', id: archive.id, filename: archive.print_name || archive.filename || 'model' }}
  1237. onClose={() => setShowSliceModal(false)}
  1238. />
  1239. )}
  1240. {/* Delete Confirmation */}
  1241. {showDeleteConfirm && (
  1242. <ConfirmModal
  1243. title={t('archives.modal.deleteArchive')}
  1244. message={t('archives.modal.deleteConfirm', { name: archive.print_name || archive.filename })}
  1245. confirmText={t('archives.modal.deleteButton')}
  1246. variant="danger"
  1247. onConfirm={() => {
  1248. deleteMutation.mutate(deletePurgeStats);
  1249. setShowDeleteConfirm(false);
  1250. setDeletePurgeStats(false);
  1251. }}
  1252. onCancel={() => {
  1253. setShowDeleteConfirm(false);
  1254. setDeletePurgeStats(false);
  1255. }}
  1256. >
  1257. {/* #1343: opt-in checkbox — by default the archive is soft-deleted,
  1258. so its filament / time / cost contribution stays in Quick Stats. */}
  1259. <label className="flex items-start gap-2 cursor-pointer text-sm text-bambu-gray">
  1260. <input
  1261. type="checkbox"
  1262. className="mt-0.5 accent-red-500"
  1263. checked={deletePurgeStats}
  1264. onChange={(e) => setDeletePurgeStats(e.target.checked)}
  1265. />
  1266. <span>{t('archives.modal.deletePurgeStats')}</span>
  1267. </label>
  1268. </ConfirmModal>
  1269. )}
  1270. {/* Delete Source 3MF Confirmation */}
  1271. {showDeleteSource3mfConfirm && (
  1272. <ConfirmModal
  1273. title={t('archives.modal.removeSource3mf')}
  1274. message={t('archives.modal.removeSource3mfConfirm', { name: archive.print_name || archive.filename })}
  1275. confirmText={t('archives.modal.removeButton')}
  1276. variant="danger"
  1277. onConfirm={() => {
  1278. source3mfDeleteMutation.mutate();
  1279. setShowDeleteSource3mfConfirm(false);
  1280. }}
  1281. onCancel={() => setShowDeleteSource3mfConfirm(false)}
  1282. />
  1283. )}
  1284. {/* Delete F3D Confirmation */}
  1285. {showDeleteF3dConfirm && (
  1286. <ConfirmModal
  1287. title={t('archives.modal.removeF3d')}
  1288. message={t('archives.modal.removeF3dConfirm', { name: archive.print_name || archive.filename })}
  1289. confirmText={t('archives.modal.removeButton')}
  1290. variant="danger"
  1291. onConfirm={() => {
  1292. f3dDeleteMutation.mutate();
  1293. setShowDeleteF3dConfirm(false);
  1294. }}
  1295. onCancel={() => setShowDeleteF3dConfirm(false)}
  1296. />
  1297. )}
  1298. {/* Delete Timelapse Confirmation */}
  1299. {showDeleteTimelapseConfirm && (
  1300. <ConfirmModal
  1301. title={t('archives.modal.removeTimelapse')}
  1302. message={t('archives.modal.removeTimelapseConfirm', { name: archive.print_name || archive.filename })}
  1303. confirmText={t('archives.modal.removeButton')}
  1304. variant="danger"
  1305. onConfirm={() => {
  1306. timelapseDeleteMutation.mutate();
  1307. setShowDeleteTimelapseConfirm(false);
  1308. }}
  1309. onCancel={() => setShowDeleteTimelapseConfirm(false)}
  1310. />
  1311. )}
  1312. {/* Context Menu */}
  1313. {contextMenu && (
  1314. <ContextMenu
  1315. x={contextMenu.x}
  1316. y={contextMenu.y}
  1317. items={contextMenuItems}
  1318. onClose={() => setContextMenu(null)}
  1319. />
  1320. )}
  1321. {/* Timelapse Viewer Modal */}
  1322. {showTimelapse && archive.timelapse_path && (
  1323. <TimelapseViewer
  1324. src={api.getArchiveTimelapse(archive.id)}
  1325. title={t('archives.modal.timelapse', { name: archive.print_name || archive.filename })}
  1326. downloadFilename={`${archive.print_name || archive.filename}_timelapse.mp4`}
  1327. archiveId={archive.id}
  1328. onClose={() => setShowTimelapse(false)}
  1329. onEdit={() => {
  1330. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1331. setShowTimelapse(false); // Close viewer to reload fresh video
  1332. }}
  1333. />
  1334. )}
  1335. {/* Timelapse Selection Modal */}
  1336. {showTimelapseSelect && availableTimelapses.length > 0 && (
  1337. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  1338. <div className="bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col">
  1339. <div className="flex items-center justify-between p-4 border-b border-gray-700">
  1340. <div>
  1341. <h3 className="text-lg font-semibold text-white">{t('archives.modal.selectTimelapse')}</h3>
  1342. <p className="text-sm text-gray-400 mt-1">
  1343. {t('archives.modal.selectTimelapseDesc')}
  1344. </p>
  1345. </div>
  1346. <button
  1347. onClick={() => {
  1348. setShowTimelapseSelect(false);
  1349. setAvailableTimelapses([]);
  1350. }}
  1351. className="text-gray-400 hover:text-white p-1"
  1352. >
  1353. <X className="w-5 h-5" />
  1354. </button>
  1355. </div>
  1356. <div className="overflow-y-auto flex-1 p-2">
  1357. {availableTimelapses.map((file) => (
  1358. <button
  1359. key={file.name}
  1360. onClick={() => timelapseSelectMutation.mutate(file.name)}
  1361. disabled={timelapseSelectMutation.isPending}
  1362. className="w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50"
  1363. >
  1364. <Film className="w-8 h-8 text-bambu-green flex-shrink-0" />
  1365. <div className="flex-1 min-w-0">
  1366. <p className="text-white font-medium truncate">{file.name}</p>
  1367. <p className="text-sm text-gray-400">
  1368. {formatFileSize(file.size)}
  1369. {file.mtime && ` • ${formatDateTime(file.mtime, timeFormat)}`}
  1370. </p>
  1371. </div>
  1372. </button>
  1373. ))}
  1374. </div>
  1375. <div className="p-4 border-t border-gray-700">
  1376. <Button
  1377. variant="secondary"
  1378. onClick={() => {
  1379. setShowTimelapseSelect(false);
  1380. setAvailableTimelapses([]);
  1381. }}
  1382. className="w-full"
  1383. >
  1384. Cancel
  1385. </Button>
  1386. </div>
  1387. </div>
  1388. </div>
  1389. )}
  1390. {/* QR Code Modal */}
  1391. {showQRCode && (
  1392. <QRCodeModal
  1393. archiveId={archive.id}
  1394. archiveName={archive.print_name || archive.filename}
  1395. onClose={() => setShowQRCode(false)}
  1396. />
  1397. )}
  1398. {/* Photo Gallery Modal */}
  1399. {showPhotos && archive.photos && archive.photos.length > 0 && (
  1400. <PhotoGalleryModal
  1401. archiveId={archive.id}
  1402. archiveName={archive.print_name || archive.filename}
  1403. photos={archive.photos}
  1404. onClose={() => setShowPhotos(false)}
  1405. onDelete={async (filename) => {
  1406. try {
  1407. await api.deleteArchivePhoto(archive.id, filename);
  1408. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1409. showToast(t('archives.toast.photoDeleted'));
  1410. } catch {
  1411. showToast(t('archives.toast.failedDeletePhoto'), 'error');
  1412. }
  1413. }}
  1414. />
  1415. )}
  1416. {/* Project Page Modal */}
  1417. {showProjectPage && (
  1418. <ProjectPageModal
  1419. archiveId={archive.id}
  1420. archiveName={archive.print_name || archive.filename}
  1421. onClose={() => setShowProjectPage(false)}
  1422. />
  1423. )}
  1424. {showSchedule && (
  1425. <PrintModal
  1426. mode="add-to-queue"
  1427. archiveId={archive.id}
  1428. archiveName={archive.print_name || archive.filename}
  1429. onClose={() => setShowSchedule(false)}
  1430. />
  1431. )}
  1432. {/* Hidden file input for source 3MF upload */}
  1433. <input
  1434. ref={source3mfInputRef}
  1435. type="file"
  1436. accept=".3mf"
  1437. className="hidden"
  1438. onChange={(e) => {
  1439. const file = e.target.files?.[0];
  1440. if (file) {
  1441. source3mfUploadMutation.mutate(file);
  1442. }
  1443. e.target.value = '';
  1444. }}
  1445. />
  1446. {/* Hidden file input for F3D upload */}
  1447. <input
  1448. ref={f3dInputRef}
  1449. type="file"
  1450. accept=".f3d"
  1451. className="hidden"
  1452. onChange={(e) => {
  1453. const file = e.target.files?.[0];
  1454. if (file) {
  1455. f3dUploadMutation.mutate(file);
  1456. }
  1457. e.target.value = '';
  1458. }}
  1459. />
  1460. {/* Hidden file input for timelapse upload */}
  1461. <input
  1462. ref={timelapseInputRef}
  1463. type="file"
  1464. accept=".mp4,.avi,.mkv"
  1465. className="hidden"
  1466. onChange={(e) => {
  1467. const file = e.target.files?.[0];
  1468. if (file) {
  1469. timelapseUploadMutation.mutate(file);
  1470. }
  1471. e.target.value = '';
  1472. }}
  1473. />
  1474. </Card>
  1475. );
  1476. }
  1477. function ArchiveListRow({
  1478. archive,
  1479. printerName,
  1480. isSelected,
  1481. onSelect,
  1482. selectionMode,
  1483. projects,
  1484. isHighlighted,
  1485. preferredSlicer = 'bambu_studio',
  1486. useSlicerApi = false,
  1487. t,
  1488. onNavigateToArchive,
  1489. }: {
  1490. archive: Archive;
  1491. printerName: string;
  1492. isSelected: boolean;
  1493. onSelect: (id: number) => void;
  1494. selectionMode: boolean;
  1495. projects: ProjectListItem[] | undefined;
  1496. isHighlighted?: boolean;
  1497. preferredSlicer?: SlicerType;
  1498. useSlicerApi?: boolean;
  1499. t: TFunction;
  1500. onNavigateToArchive?: (archiveId: number) => void;
  1501. }) {
  1502. const queryClient = useQueryClient();
  1503. const { showToast } = useToast();
  1504. const { hasPermission, canModify } = useAuth();
  1505. const [showEdit, setShowEdit] = useState(false);
  1506. const [showPrintLog, setShowPrintLog] = useState(false);
  1507. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1508. // #1343: opt-in "Also remove from statistics" checkbox state. Default off
  1509. // — soft delete keeps the archive's contribution to Quick Stats.
  1510. const [deletePurgeStats, setDeletePurgeStats] = useState(false);
  1511. const navigate = useNavigate();
  1512. const [showReprint, setShowReprint] = useState(false);
  1513. const [showSliceModal, setShowSliceModal] = useState(false);
  1514. const [showSchedule, setShowSchedule] = useState(false);
  1515. const [showTimelapse, setShowTimelapse] = useState(false);
  1516. const [showTimelapseSelect, setShowTimelapseSelect] = useState(false);
  1517. const [availableTimelapses, setAvailableTimelapses] = useState<Array<{ name: string; path: string; size: number; mtime: string | null }>>([]);
  1518. const [showQRCode, setShowQRCode] = useState(false);
  1519. const [showPhotos, setShowPhotos] = useState(false);
  1520. const [showProjectPage, setShowProjectPage] = useState(false);
  1521. const [showDeleteSource3mfConfirm, setShowDeleteSource3mfConfirm] = useState(false);
  1522. const [showDeleteF3dConfirm, setShowDeleteF3dConfirm] = useState(false);
  1523. const [showDeleteTimelapseConfirm, setShowDeleteTimelapseConfirm] = useState(false);
  1524. const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
  1525. const source3mfInputRef = useRef<HTMLInputElement>(null);
  1526. const f3dInputRef = useRef<HTMLInputElement>(null);
  1527. const timelapseInputRef = useRef<HTMLInputElement>(null);
  1528. const [platePickerPlates, setPlatePickerPlates] = useState<PlateMetadata[] | null>(null);
  1529. // Use pre-computed duplicate sequence and original archive ID from list response
  1530. const duplicateSequence = archive.duplicate_sequence ?? 0;
  1531. const originalArchiveId = archive.original_archive_id ?? null;
  1532. // 3D Preview click handler. Multi-plate archives show the plate picker
  1533. // first; single-plate archives navigate straight into the viewer.
  1534. const openGcodeViewer = async () => {
  1535. try {
  1536. const resp = await api.getArchivePlates(archive.id);
  1537. if (resp.is_multi_plate && resp.plates.length > 1) {
  1538. setPlatePickerPlates(resp.plates);
  1539. return;
  1540. }
  1541. } catch {
  1542. // Swallow — fall through to navigate on the first-plate default.
  1543. }
  1544. navigate(`/gcode-viewer?archive=${archive.id}`);
  1545. };
  1546. const timelapseDeleteMutation = useMutation({
  1547. mutationFn: () => api.deleteArchiveTimelapse(archive.id),
  1548. onSuccess: () => {
  1549. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1550. showToast(t('archives.toast.timelapseRemoved'));
  1551. },
  1552. onError: (error: Error) => {
  1553. showToast(error.message || t('archives.toast.failedRemoveTimelapse'), 'error');
  1554. },
  1555. });
  1556. const timelapseUploadMutation = useMutation({
  1557. mutationFn: (file: File) => api.uploadArchiveTimelapse(archive.id, file),
  1558. onSuccess: (data) => {
  1559. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1560. showToast(t('archives.toast.timelapseUploaded', { filename: data.filename }));
  1561. },
  1562. onError: (error: Error) => {
  1563. showToast(error.message || t('archives.toast.failedUploadTimelapse'), 'error');
  1564. },
  1565. });
  1566. const source3mfUploadMutation = useMutation({
  1567. mutationFn: (file: File) => api.uploadSource3mf(archive.id, file),
  1568. onSuccess: (data) => {
  1569. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1570. showToast(t('archives.toast.source3mfAttached', { filename: data.filename }));
  1571. },
  1572. onError: (error: Error) => {
  1573. showToast(error.message || t('archives.toast.failedUploadSource3mf'), 'error');
  1574. },
  1575. });
  1576. const source3mfDeleteMutation = useMutation({
  1577. mutationFn: () => api.deleteSource3mf(archive.id),
  1578. onSuccess: () => {
  1579. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1580. showToast(t('archives.toast.source3mfRemoved'));
  1581. },
  1582. onError: (error: Error) => {
  1583. showToast(error.message || t('archives.toast.failedRemoveSource3mf'), 'error');
  1584. },
  1585. });
  1586. const f3dUploadMutation = useMutation({
  1587. mutationFn: (file: File) => api.uploadF3d(archive.id, file),
  1588. onSuccess: (data) => {
  1589. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1590. showToast(t('archives.toast.f3dAttached', { filename: data.filename }));
  1591. },
  1592. onError: (error: Error) => {
  1593. showToast(error.message || t('archives.toast.failedUploadF3d'), 'error');
  1594. },
  1595. });
  1596. const f3dDeleteMutation = useMutation({
  1597. mutationFn: () => api.deleteF3d(archive.id),
  1598. onSuccess: () => {
  1599. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1600. showToast(t('archives.toast.f3dRemoved'));
  1601. },
  1602. onError: (error: Error) => {
  1603. showToast(error.message || t('archives.toast.failedRemoveF3d'), 'error');
  1604. },
  1605. });
  1606. const timelapseScanMutation = useMutation({
  1607. mutationFn: () => api.scanArchiveTimelapse(archive.id),
  1608. onSuccess: (data) => {
  1609. if (data.status === 'attached') {
  1610. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1611. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  1612. } else if (data.status === 'exists') {
  1613. showToast(t('archives.toast.timelapseAlreadyAttached'));
  1614. } else if (data.status === 'not_found' && data.available_files && data.available_files.length > 0) {
  1615. setAvailableTimelapses(data.available_files);
  1616. setShowTimelapseSelect(true);
  1617. } else {
  1618. showToast(data.message || t('archives.toast.noMatchingTimelapse'), 'warning');
  1619. }
  1620. },
  1621. onError: (error: Error) => {
  1622. showToast(error.message || t('archives.toast.failedScanTimelapse'), 'error');
  1623. },
  1624. });
  1625. const timelapseSelectMutation = useMutation({
  1626. mutationFn: (filename: string) => api.selectArchiveTimelapse(archive.id, filename),
  1627. onSuccess: (data) => {
  1628. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1629. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  1630. setShowTimelapseSelect(false);
  1631. setAvailableTimelapses([]);
  1632. },
  1633. onError: (error: Error) => {
  1634. showToast(error.message || t('archives.toast.failedAttachTimelapse'), 'error');
  1635. },
  1636. });
  1637. const deleteMutation = useMutation({
  1638. mutationFn: (purgeStats: boolean) => api.deleteArchive(archive.id, purgeStats),
  1639. onSuccess: () => {
  1640. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1641. showToast(t('archives.toast.archiveDeleted'));
  1642. },
  1643. onError: () => {
  1644. showToast(t('archives.toast.failedDeleteArchive'), 'error');
  1645. },
  1646. });
  1647. const favoriteMutation = useMutation({
  1648. mutationFn: () => api.toggleFavorite(archive.id),
  1649. onSuccess: (data) => {
  1650. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1651. showToast(data.is_favorite ? t('archives.toast.addedToFavorites') : t('archives.toast.removedFromFavorites'));
  1652. },
  1653. });
  1654. // Query for linked folders
  1655. const { data: linkedFolders } = useQuery({
  1656. queryKey: ['archive-folders', archive.id],
  1657. queryFn: () => api.getLibraryFoldersByArchive(archive.id),
  1658. });
  1659. const assignProjectMutation = useMutation({
  1660. mutationFn: (projectId: number | null) => api.updateArchive(archive.id, { project_id: projectId }),
  1661. onSuccess: () => {
  1662. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1663. queryClient.invalidateQueries({ queryKey: ['projects'] });
  1664. showToast(t('archives.toast.projectUpdated'));
  1665. },
  1666. onError: () => {
  1667. showToast(t('archives.toast.failedUpdateProject'), 'error');
  1668. },
  1669. });
  1670. const handleContextMenu = (e: React.MouseEvent) => {
  1671. e.preventDefault();
  1672. setContextMenu({ x: e.clientX, y: e.clientY });
  1673. };
  1674. const isGcodeFile = isSlicedFile(archive);
  1675. const contextMenuItems: ContextMenuItem[] = [
  1676. ...(isGcodeFile ? [
  1677. {
  1678. label: t('archives.menu.print'),
  1679. icon: <Printer className="w-4 h-4" />,
  1680. onClick: () => setShowReprint(true),
  1681. disabled: !archive.file_path || !canModify('archives', 'reprint', archive.created_by_id),
  1682. title: !archive.file_path ? t('archives.card.noFileForReprint') : !canModify('archives', 'reprint', archive.created_by_id) ? t('archives.permission.noReprint') : undefined,
  1683. },
  1684. {
  1685. label: t('archives.menu.schedule'),
  1686. icon: <Calendar className="w-4 h-4" />,
  1687. onClick: () => setShowSchedule(true),
  1688. disabled: !archive.file_path || !hasPermission('queue:create'),
  1689. title: !archive.file_path ? t('archives.card.noFileForReprint') : !hasPermission('queue:create') ? t('archives.permission.noAddToQueue') : undefined,
  1690. },
  1691. {
  1692. label: t('archives.menu.openInBambuStudio'),
  1693. icon: <ExternalLink className="w-4 h-4" />,
  1694. onClick: () => {
  1695. const filename = archive.print_name || archive.filename || 'model';
  1696. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1697. },
  1698. disabled: !archive.file_path,
  1699. title: !archive.file_path ? t('archives.card.noFileForReprint') : undefined,
  1700. },
  1701. ] : [
  1702. {
  1703. label: t('archives.menu.slice'),
  1704. icon: useSlicerApi ? <Cog className="w-4 h-4" /> : <ExternalLink className="w-4 h-4" />,
  1705. onClick: () => {
  1706. if (useSlicerApi) {
  1707. setShowSliceModal(true);
  1708. } else {
  1709. const filename = archive.print_name || archive.filename || 'model';
  1710. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1711. }
  1712. },
  1713. },
  1714. ]),
  1715. {
  1716. label: archive.external_url ? t('archives.menu.externalLink') : t('archives.menu.viewOnMakerWorld'),
  1717. icon: <Globe className="w-4 h-4" />,
  1718. onClick: () => {
  1719. const url = archive.external_url || archive.makerworld_url;
  1720. if (url) window.open(url, '_blank');
  1721. },
  1722. disabled: !archive.external_url && !archive.makerworld_url,
  1723. },
  1724. { label: '', divider: true, onClick: () => {} },
  1725. {
  1726. label: t('archives.menu.preview3d'),
  1727. icon: <Box className="w-4 h-4" />,
  1728. onClick: () => { openGcodeViewer(); },
  1729. },
  1730. {
  1731. label: t('archives.menu.viewTimelapse'),
  1732. icon: <Film className="w-4 h-4" />,
  1733. onClick: () => setShowTimelapse(true),
  1734. disabled: !archive.timelapse_path,
  1735. },
  1736. {
  1737. label: t('archives.menu.scanForTimelapse'),
  1738. icon: <ScanSearch className="w-4 h-4" />,
  1739. onClick: () => timelapseScanMutation.mutate(),
  1740. disabled: !archive.printer_id || !!archive.timelapse_path || timelapseScanMutation.isPending || !canModify('archives', 'update', archive.created_by_id),
  1741. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1742. },
  1743. {
  1744. label: t('archives.menu.uploadTimelapse'),
  1745. icon: <Upload className="w-4 h-4" />,
  1746. onClick: () => timelapseInputRef.current?.click(),
  1747. disabled: !!archive.timelapse_path || !canModify('archives', 'update', archive.created_by_id),
  1748. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1749. },
  1750. ...(archive.timelapse_path ? [{
  1751. label: t('archives.menu.removeTimelapse'),
  1752. icon: <Trash2 className="w-4 h-4" />,
  1753. onClick: () => setShowDeleteTimelapseConfirm(true),
  1754. danger: true,
  1755. disabled: !canModify('archives', 'update', archive.created_by_id),
  1756. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1757. }] : []),
  1758. { label: '', divider: true, onClick: () => {} },
  1759. {
  1760. label: archive.source_3mf_path ? t('archives.menu.downloadSource3mf') : t('archives.menu.uploadSource3mf'),
  1761. icon: <FileCode className="w-4 h-4" />,
  1762. onClick: () => {
  1763. if (archive.source_3mf_path) {
  1764. api.downloadSource3mf(archive.id).catch((err) => {
  1765. console.error('Source 3MF download failed:', err);
  1766. });
  1767. } else {
  1768. source3mfInputRef.current?.click();
  1769. }
  1770. },
  1771. disabled: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id),
  1772. title: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUploadFiles') : undefined,
  1773. },
  1774. ...(archive.source_3mf_path ? [{
  1775. label: t('archives.menu.replaceSource3mf'),
  1776. icon: <Upload className="w-4 h-4" />,
  1777. onClick: () => source3mfInputRef.current?.click(),
  1778. disabled: !canModify('archives', 'update', archive.created_by_id),
  1779. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1780. },
  1781. {
  1782. label: t('archives.menu.removeSource3mf'),
  1783. icon: <Trash2 className="w-4 h-4" />,
  1784. onClick: () => setShowDeleteSource3mfConfirm(true),
  1785. danger: true,
  1786. disabled: !canModify('archives', 'update', archive.created_by_id),
  1787. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1788. }] : []),
  1789. {
  1790. label: archive.f3d_path ? t('archives.menu.replaceF3d') : t('archives.menu.uploadF3d'),
  1791. icon: <Box className="w-4 h-4" />,
  1792. onClick: () => f3dInputRef.current?.click(),
  1793. disabled: !canModify('archives', 'update', archive.created_by_id),
  1794. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1795. },
  1796. ...(archive.f3d_path ? [{
  1797. label: t('archives.menu.downloadF3d'),
  1798. icon: <Download className="w-4 h-4" />,
  1799. onClick: () => {
  1800. api.downloadF3d(archive.id).catch((err) => {
  1801. console.error('F3D download failed:', err);
  1802. });
  1803. },
  1804. },
  1805. {
  1806. label: t('archives.menu.removeF3d'),
  1807. icon: <Trash2 className="w-4 h-4" />,
  1808. onClick: () => setShowDeleteF3dConfirm(true),
  1809. danger: true,
  1810. disabled: !canModify('archives', 'update', archive.created_by_id),
  1811. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1812. }] : []),
  1813. { label: '', divider: true, onClick: () => {} },
  1814. {
  1815. label: t('archives.menu.download'),
  1816. icon: <Download className="w-4 h-4" />,
  1817. onClick: () => {
  1818. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  1819. console.error('Archive download failed:', err);
  1820. });
  1821. },
  1822. disabled: !hasPermission('archives:read'),
  1823. title: !hasPermission('archives:read') ? t('archives.permission.noDownload') : undefined,
  1824. },
  1825. {
  1826. label: t('archives.menu.copyDownloadLink'),
  1827. icon: <Copy className="w-4 h-4" />,
  1828. onClick: () => {
  1829. const url = `${window.location.origin}${api.getArchiveDownload(archive.id)}`;
  1830. navigator.clipboard.writeText(url).then(() => {
  1831. showToast(t('archives.toast.linkCopied'));
  1832. }).catch(() => {
  1833. showToast(t('archives.toast.failedCopyLink'), 'error');
  1834. });
  1835. },
  1836. disabled: !hasPermission('archives:read'),
  1837. title: !hasPermission('archives:read') ? t('archives.permission.noCopyLink') : undefined,
  1838. },
  1839. {
  1840. label: t('archives.menu.qrCode'),
  1841. icon: <QrCode className="w-4 h-4" />,
  1842. onClick: () => setShowQRCode(true),
  1843. },
  1844. {
  1845. label: archive.photos?.length ? t('archives.menu.viewPhotosCount', { count: archive.photos.length }) : t('archives.menu.viewPhotos'),
  1846. icon: <Camera className="w-4 h-4" />,
  1847. onClick: () => setShowPhotos(true),
  1848. disabled: !archive.photos?.length,
  1849. },
  1850. {
  1851. label: t('archives.menu.projectPage'),
  1852. icon: <FileText className="w-4 h-4" />,
  1853. onClick: () => setShowProjectPage(true),
  1854. },
  1855. { label: '', divider: true, onClick: () => {} },
  1856. {
  1857. label: archive.is_favorite ? t('archives.menu.removeFromFavorites') : t('archives.menu.addToFavorites'),
  1858. icon: <Star className={`w-4 h-4 ${archive.is_favorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />,
  1859. onClick: () => favoriteMutation.mutate(),
  1860. disabled: !canModify('archives', 'update', archive.created_by_id),
  1861. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1862. },
  1863. {
  1864. label: t('archives.menu.edit'),
  1865. icon: <Pencil className="w-4 h-4" />,
  1866. onClick: () => setShowEdit(true),
  1867. disabled: !canModify('archives', 'update', archive.created_by_id),
  1868. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1869. },
  1870. {
  1871. label: t('archives.menu.printLog'),
  1872. icon: <History className="w-4 h-4" />,
  1873. onClick: () => setShowPrintLog(true),
  1874. },
  1875. ...(archive.project_id && archive.project_name ? [{
  1876. label: t('archives.menu.goToProject', { name: archive.project_name }),
  1877. icon: <FolderKanban className="w-4 h-4 text-bambu-green" />,
  1878. onClick: () => window.location.href = '/projects',
  1879. }] : []),
  1880. {
  1881. label: t('archives.menu.addToProject'),
  1882. icon: <FolderKanban className="w-4 h-4" />,
  1883. onClick: () => {},
  1884. submenuSearchPlaceholder: (projects?.filter(p => p.status === 'active').length ?? 0) > 5
  1885. ? t('archives.menu.searchProjects')
  1886. : undefined,
  1887. submenu: (() => {
  1888. const items: ContextMenuItem[] = [];
  1889. if (archive.project_id) {
  1890. items.push({
  1891. label: t('archives.menu.removeFromProject'),
  1892. icon: <X className="w-4 h-4" />,
  1893. onClick: () => assignProjectMutation.mutate(null),
  1894. });
  1895. }
  1896. if (!projects) {
  1897. items.push({
  1898. label: t('archives.menu.loading'),
  1899. icon: <Loader2 className="w-4 h-4 animate-spin" />,
  1900. onClick: () => {},
  1901. disabled: true,
  1902. });
  1903. } else {
  1904. const activeProjects = projects
  1905. .filter(p => p.status === 'active')
  1906. .sort((a, b) => a.name.localeCompare(b.name));
  1907. if (activeProjects.length === 0) {
  1908. items.push({
  1909. label: t('archives.menu.noProjectsAvailable'),
  1910. icon: <FolderKanban className="w-4 h-4 opacity-50" />,
  1911. onClick: () => {},
  1912. disabled: true,
  1913. });
  1914. } else {
  1915. activeProjects.forEach(p => {
  1916. items.push({
  1917. label: p.name,
  1918. icon: <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: p.color || '#888' }} />,
  1919. onClick: () => assignProjectMutation.mutate(p.id),
  1920. disabled: archive.project_id === p.id,
  1921. });
  1922. });
  1923. }
  1924. }
  1925. return items;
  1926. })(),
  1927. },
  1928. {
  1929. label: isSelected ? t('archives.menu.deselect') : t('archives.menu.select'),
  1930. icon: isSelected ? <CheckSquare className="w-4 h-4" /> : <Square className="w-4 h-4" />,
  1931. onClick: () => onSelect(archive.id),
  1932. },
  1933. { label: '', divider: true, onClick: () => {} },
  1934. {
  1935. label: t('archives.menu.delete'),
  1936. icon: <Trash2 className="w-4 h-4" />,
  1937. onClick: () => setShowDeleteConfirm(true),
  1938. danger: true,
  1939. disabled: !canModify('archives', 'delete', archive.created_by_id),
  1940. title: !canModify('archives', 'delete', archive.created_by_id) ? t('archives.permission.noDelete') : undefined,
  1941. },
  1942. ];
  1943. return (
  1944. <>
  1945. <div
  1946. data-archive-id={archive.id}
  1947. className={`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${
  1948. isSelected ? 'bg-bambu-green/10' : ''
  1949. }`}
  1950. style={isHighlighted ? { outline: '4px solid #facc15', outlineOffset: '-4px' } : undefined}
  1951. onContextMenu={handleContextMenu}
  1952. >
  1953. <div className="col-span-1 flex items-center gap-2">
  1954. {selectionMode && (
  1955. <button onClick={() => onSelect(archive.id)}>
  1956. {isSelected ? (
  1957. <CheckSquare className="w-4 h-4 text-bambu-green" />
  1958. ) : (
  1959. <Square className="w-4 h-4 text-bambu-gray" />
  1960. )}
  1961. </button>
  1962. )}
  1963. {archive.thumbnail_path ? (
  1964. <img
  1965. src={api.getArchiveThumbnail(archive.id)}
  1966. alt=""
  1967. className="w-10 h-10 object-cover rounded"
  1968. />
  1969. ) : (
  1970. <div className="w-10 h-10 bg-bambu-dark rounded flex items-center justify-center">
  1971. <Image className="w-5 h-5 text-bambu-dark-tertiary" />
  1972. </div>
  1973. )}
  1974. </div>
  1975. <div className="col-span-4">
  1976. <div className="flex items-center gap-2">
  1977. <p className="text-white text-sm truncate">{archive.print_name || archive.filename}</p>
  1978. {(archive.status === 'failed' || archive.status === 'aborted') && (
  1979. <span className="px-1.5 py-0.5 rounded text-[10px] leading-tight bg-status-error/80 text-white flex-shrink-0">
  1980. {archive.status === 'aborted' ? t('archives.card.cancelled') : t('archives.card.failed')}
  1981. </span>
  1982. )}
  1983. {archive.duplicate_count > 0 && duplicateSequence > 0 && originalArchiveId && (
  1984. <button
  1985. onClick={(e) => {
  1986. e.stopPropagation();
  1987. onNavigateToArchive?.(originalArchiveId);
  1988. }}
  1989. className="px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 hover:bg-purple-600/90 text-white flex-shrink-0 transition-colors flex items-center gap-1"
  1990. title={t('archives.viewOriginalPrint', { id: originalArchiveId })}
  1991. >
  1992. <Copy className="w-3 h-3" />
  1993. #{duplicateSequence}
  1994. </button>
  1995. )}
  1996. {archive.duplicate_count > 0 && duplicateSequence === 0 && (
  1997. <span
  1998. className="px-1.5 py-0.5 rounded text-[10px] leading-tight bg-purple-500/80 text-white flex-shrink-0 flex items-center gap-1"
  1999. title={`${archive.duplicate_count} reprint${archive.duplicate_count === 1 ? '' : 's'}`}
  2000. >
  2001. <GitBranch className="w-3 h-3" />
  2002. +{archive.duplicate_count}
  2003. </span>
  2004. )}
  2005. {archive.timelapse_path && (
  2006. <span title={t('archives.list.hasTimelapse')}>
  2007. <Film className="w-3.5 h-3.5 text-bambu-green flex-shrink-0" />
  2008. </span>
  2009. )}
  2010. {linkedFolders && linkedFolders.length > 0 && (
  2011. <Link
  2012. to={`/files?folder=${linkedFolders[0].id}`}
  2013. className="flex-shrink-0"
  2014. title={t('archives.card.openFolder', { name: linkedFolders[0].name })}
  2015. onClick={(e) => e.stopPropagation()}
  2016. >
  2017. <FolderOpen className="w-3.5 h-3.5 text-yellow-400" />
  2018. </Link>
  2019. )}
  2020. </div>
  2021. {(archive.filament_type || archive.sliced_for_model) && (
  2022. <div className="flex items-center gap-1.5 mt-0.5">
  2023. {archive.sliced_for_model && (
  2024. <span className="text-xs text-bambu-gray flex items-center gap-1" title={t('archives.card.slicedFor', { model: archive.sliced_for_model })}>
  2025. <Printer className="w-2.5 h-2.5" />
  2026. {archive.sliced_for_model}
  2027. </span>
  2028. )}
  2029. {(() => {
  2030. const bed = getBedTypeInfo(archive.bed_type);
  2031. return bed ? (
  2032. <img src={bed.icon} alt={bed.label} title={bed.label} className="w-3.5 h-3.5 flex-shrink-0" />
  2033. ) : null;
  2034. })()}
  2035. {archive.sliced_for_model && archive.filament_type && (
  2036. <span className="text-bambu-gray/50">·</span>
  2037. )}
  2038. {archive.filament_type && (
  2039. <span className="text-xs text-bambu-gray">{archive.filament_type}</span>
  2040. )}
  2041. {archive.filament_color && (
  2042. <div className="flex items-center gap-0.5 flex-wrap">
  2043. {archive.filament_color.split(',').map((color, i) => (
  2044. <div
  2045. key={i}
  2046. className="w-2.5 h-2.5 rounded-full border border-black/20"
  2047. style={{ backgroundColor: color }}
  2048. title={color}
  2049. />
  2050. ))}
  2051. </div>
  2052. )}
  2053. </div>
  2054. )}
  2055. </div>
  2056. <div className="col-span-2 text-sm text-bambu-gray truncate">
  2057. {printerName}
  2058. </div>
  2059. <div className="col-span-2 text-sm text-bambu-gray">
  2060. <div>{formatDateOnly(archive.created_at)}</div>
  2061. {archive.created_by_username && (
  2062. <div className="flex items-center gap-1 text-xs opacity-75" title={t('archives.card.uploadedBy', { name: archive.created_by_username })}>
  2063. <User className="w-3 h-3" />
  2064. {archive.created_by_username}
  2065. </div>
  2066. )}
  2067. </div>
  2068. <div className="col-span-1 text-sm text-bambu-gray">
  2069. {formatFileSize(archive.file_size)}
  2070. </div>
  2071. <div className="col-span-2 flex justify-end gap-1">
  2072. {isSlicedFile(archive) && (
  2073. <Button
  2074. variant="ghost"
  2075. size="sm"
  2076. onClick={() => setShowReprint(true)}
  2077. disabled={!canModify('archives', 'reprint', archive.created_by_id)}
  2078. title={!canModify('archives', 'reprint', archive.created_by_id) ? t('archives.card.noPermissionReprint') : t('archives.card.reprint')}
  2079. className="text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10"
  2080. >
  2081. <Play className="w-4 h-4" />
  2082. </Button>
  2083. )}
  2084. <Button
  2085. variant="ghost"
  2086. size="sm"
  2087. onClick={() => {
  2088. const filename = archive.print_name || archive.filename || 'model';
  2089. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  2090. }}
  2091. title={t('archives.card.openInBambuStudio')}
  2092. >
  2093. <ExternalLink className="w-4 h-4" />
  2094. </Button>
  2095. {(archive.external_url || archive.makerworld_url) && (
  2096. <Button
  2097. variant="ghost"
  2098. size="sm"
  2099. onClick={() => window.open((archive.external_url || archive.makerworld_url)!, '_blank')}
  2100. title={archive.external_url ? t('archives.card.externalLink') : 'MakerWorld'}
  2101. >
  2102. <Globe className="w-4 h-4" />
  2103. </Button>
  2104. )}
  2105. <Button
  2106. variant="ghost"
  2107. size="sm"
  2108. onClick={() => {
  2109. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  2110. console.error('Archive download failed:', err);
  2111. });
  2112. }}
  2113. title={t('archives.card.download')}
  2114. >
  2115. <Download className="w-4 h-4" />
  2116. </Button>
  2117. <Button
  2118. variant="ghost"
  2119. size="sm"
  2120. onClick={() => setShowEdit(true)}
  2121. disabled={!canModify('archives', 'update', archive.created_by_id)}
  2122. title={!canModify('archives', 'update', archive.created_by_id) ? t('archives.card.noPermissionEdit') : t('archives.card.edit')}
  2123. >
  2124. <Pencil className="w-4 h-4" />
  2125. </Button>
  2126. <Button
  2127. variant="ghost"
  2128. size="sm"
  2129. onClick={() => setShowDeleteConfirm(true)}
  2130. disabled={!canModify('archives', 'delete', archive.created_by_id)}
  2131. title={!canModify('archives', 'delete', archive.created_by_id) ? t('archives.card.noPermissionDelete') : t('archives.card.delete')}
  2132. >
  2133. <Trash2 className="w-4 h-4 text-red-400" />
  2134. </Button>
  2135. <Button
  2136. variant="ghost"
  2137. size="sm"
  2138. onClick={(e) => {
  2139. const rect = e.currentTarget.getBoundingClientRect();
  2140. setContextMenu({ x: rect.left, y: rect.bottom + 4 });
  2141. }}
  2142. title={t('archives.card.moreOptions')}
  2143. >
  2144. <MoreVertical className="w-4 h-4" />
  2145. </Button>
  2146. </div>
  2147. </div>
  2148. {/* Edit Modal */}
  2149. {showEdit && (
  2150. <EditArchiveModal
  2151. archive={archive}
  2152. onClose={() => setShowEdit(false)}
  2153. />
  2154. )}
  2155. {/* Print Log Modal — opened from the "N prints" badge or context menu (#1378) */}
  2156. {showPrintLog && (
  2157. <PrintLogModal
  2158. archiveId={archive.id}
  2159. archiveName={archive.print_name || archive.filename}
  2160. onClose={() => setShowPrintLog(false)}
  2161. />
  2162. )}
  2163. {/* Plate picker — shown only for multi-plate archives on 3D Preview click */}
  2164. {platePickerPlates && (
  2165. <PlatePickerModal
  2166. plates={platePickerPlates}
  2167. onSelect={(plateIndex) => {
  2168. setPlatePickerPlates(null);
  2169. navigate(`/gcode-viewer?archive=${archive.id}&plate=${plateIndex}`);
  2170. }}
  2171. onClose={() => setPlatePickerPlates(null)}
  2172. />
  2173. )}
  2174. {/* Reprint Modal */}
  2175. {showReprint && (
  2176. <PrintModal
  2177. mode="reprint"
  2178. archiveId={archive.id}
  2179. archiveName={archive.print_name || archive.filename}
  2180. onClose={() => setShowReprint(false)}
  2181. />
  2182. )}
  2183. {/* Slice Modal */}
  2184. {showSliceModal && (
  2185. <SliceModal
  2186. source={{ kind: 'archive', id: archive.id, filename: archive.print_name || archive.filename || 'model' }}
  2187. onClose={() => setShowSliceModal(false)}
  2188. />
  2189. )}
  2190. {/* Delete Confirmation */}
  2191. {showDeleteConfirm && (
  2192. <ConfirmModal
  2193. title={t('archives.modal.deleteArchive')}
  2194. message={t('archives.modal.deleteConfirm', { name: archive.print_name || archive.filename })}
  2195. confirmText={t('archives.modal.deleteButton')}
  2196. variant="danger"
  2197. onConfirm={() => {
  2198. deleteMutation.mutate(deletePurgeStats);
  2199. setShowDeleteConfirm(false);
  2200. setDeletePurgeStats(false);
  2201. }}
  2202. onCancel={() => {
  2203. setShowDeleteConfirm(false);
  2204. setDeletePurgeStats(false);
  2205. }}
  2206. >
  2207. {/* #1343: opt-in checkbox — by default the archive is soft-deleted,
  2208. so its filament / time / cost contribution stays in Quick Stats. */}
  2209. <label className="flex items-start gap-2 cursor-pointer text-sm text-bambu-gray">
  2210. <input
  2211. type="checkbox"
  2212. className="mt-0.5 accent-red-500"
  2213. checked={deletePurgeStats}
  2214. onChange={(e) => setDeletePurgeStats(e.target.checked)}
  2215. />
  2216. <span>{t('archives.modal.deletePurgeStats')}</span>
  2217. </label>
  2218. </ConfirmModal>
  2219. )}
  2220. {/* Delete Source 3MF Confirmation */}
  2221. {showDeleteSource3mfConfirm && (
  2222. <ConfirmModal
  2223. title={t('archives.modal.removeSource3mf')}
  2224. message={t('archives.modal.removeSource3mfConfirm', { name: archive.print_name || archive.filename })}
  2225. confirmText={t('archives.modal.removeButton')}
  2226. variant="danger"
  2227. onConfirm={() => {
  2228. source3mfDeleteMutation.mutate();
  2229. setShowDeleteSource3mfConfirm(false);
  2230. }}
  2231. onCancel={() => setShowDeleteSource3mfConfirm(false)}
  2232. />
  2233. )}
  2234. {/* Delete F3D Confirmation */}
  2235. {showDeleteF3dConfirm && (
  2236. <ConfirmModal
  2237. title={t('archives.modal.removeF3d')}
  2238. message={t('archives.modal.removeF3dConfirm', { name: archive.print_name || archive.filename })}
  2239. confirmText={t('archives.modal.removeButton')}
  2240. variant="danger"
  2241. onConfirm={() => {
  2242. f3dDeleteMutation.mutate();
  2243. setShowDeleteF3dConfirm(false);
  2244. }}
  2245. onCancel={() => setShowDeleteF3dConfirm(false)}
  2246. />
  2247. )}
  2248. {/* Delete Timelapse Confirmation */}
  2249. {showDeleteTimelapseConfirm && (
  2250. <ConfirmModal
  2251. title={t('archives.modal.removeTimelapse')}
  2252. message={t('archives.modal.removeTimelapseConfirm', { name: archive.print_name || archive.filename })}
  2253. confirmText={t('archives.modal.removeButton')}
  2254. variant="danger"
  2255. onConfirm={() => {
  2256. timelapseDeleteMutation.mutate();
  2257. setShowDeleteTimelapseConfirm(false);
  2258. }}
  2259. onCancel={() => setShowDeleteTimelapseConfirm(false)}
  2260. />
  2261. )}
  2262. {/* Context Menu */}
  2263. {contextMenu && (
  2264. <ContextMenu
  2265. x={contextMenu.x}
  2266. y={contextMenu.y}
  2267. items={contextMenuItems}
  2268. onClose={() => setContextMenu(null)}
  2269. />
  2270. )}
  2271. {/* Timelapse Viewer Modal */}
  2272. {showTimelapse && archive.timelapse_path && (
  2273. <TimelapseViewer
  2274. src={api.getArchiveTimelapse(archive.id)}
  2275. title={t('archives.modal.timelapse', { name: archive.print_name || archive.filename })}
  2276. downloadFilename={`${archive.print_name || archive.filename}_timelapse.mp4`}
  2277. archiveId={archive.id}
  2278. onClose={() => setShowTimelapse(false)}
  2279. onEdit={() => {
  2280. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2281. setShowTimelapse(false);
  2282. }}
  2283. />
  2284. )}
  2285. {/* Timelapse Selection Modal */}
  2286. {showTimelapseSelect && availableTimelapses.length > 0 && (
  2287. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  2288. <div className="bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col">
  2289. <div className="flex items-center justify-between p-4 border-b border-gray-700">
  2290. <div>
  2291. <h3 className="text-lg font-semibold text-white">{t('archives.modal.selectTimelapse')}</h3>
  2292. <p className="text-sm text-gray-400 mt-1">
  2293. {t('archives.modal.selectTimelapseDesc')}
  2294. </p>
  2295. </div>
  2296. <button
  2297. onClick={() => {
  2298. setShowTimelapseSelect(false);
  2299. setAvailableTimelapses([]);
  2300. }}
  2301. className="text-gray-400 hover:text-white p-1"
  2302. >
  2303. <X className="w-5 h-5" />
  2304. </button>
  2305. </div>
  2306. <div className="overflow-y-auto flex-1 p-2">
  2307. {availableTimelapses.map((file) => (
  2308. <button
  2309. key={file.name}
  2310. onClick={() => timelapseSelectMutation.mutate(file.name)}
  2311. disabled={timelapseSelectMutation.isPending}
  2312. className="w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1"
  2313. >
  2314. <div className="font-medium text-white">{file.name}</div>
  2315. <div className="text-sm text-gray-400 flex gap-3">
  2316. <span>{formatFileSize(file.size)}</span>
  2317. {file.mtime && (
  2318. <span>{formatDateOnly(file.mtime)}</span>
  2319. )}
  2320. </div>
  2321. </button>
  2322. ))}
  2323. </div>
  2324. </div>
  2325. </div>
  2326. )}
  2327. {/* QR Code Modal */}
  2328. {showQRCode && (
  2329. <QRCodeModal
  2330. archiveId={archive.id}
  2331. archiveName={archive.print_name || archive.filename}
  2332. onClose={() => setShowQRCode(false)}
  2333. />
  2334. )}
  2335. {/* Photo Gallery Modal */}
  2336. {showPhotos && archive.photos && (
  2337. <PhotoGalleryModal
  2338. archiveId={archive.id}
  2339. archiveName={archive.print_name || archive.filename}
  2340. photos={archive.photos}
  2341. onClose={() => setShowPhotos(false)}
  2342. onDelete={async (filename) => {
  2343. try {
  2344. await api.deleteArchivePhoto(archive.id, filename);
  2345. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2346. showToast(t('archives.toast.photoDeleted'));
  2347. } catch {
  2348. showToast(t('archives.toast.failedDeletePhoto'), 'error');
  2349. }
  2350. }}
  2351. />
  2352. )}
  2353. {/* Project Page Modal */}
  2354. {showProjectPage && (
  2355. <ProjectPageModal
  2356. archiveId={archive.id}
  2357. archiveName={archive.print_name || archive.filename}
  2358. onClose={() => setShowProjectPage(false)}
  2359. />
  2360. )}
  2361. {/* Schedule Modal */}
  2362. {showSchedule && (
  2363. <PrintModal
  2364. mode="add-to-queue"
  2365. archiveId={archive.id}
  2366. archiveName={archive.print_name || archive.filename}
  2367. onClose={() => setShowSchedule(false)}
  2368. />
  2369. )}
  2370. {/* Hidden file input for source 3MF upload */}
  2371. <input
  2372. ref={source3mfInputRef}
  2373. type="file"
  2374. accept=".3mf"
  2375. className="hidden"
  2376. onChange={(e) => {
  2377. const file = e.target.files?.[0];
  2378. if (file) {
  2379. source3mfUploadMutation.mutate(file);
  2380. }
  2381. e.target.value = '';
  2382. }}
  2383. />
  2384. {/* Hidden file input for F3D upload */}
  2385. <input
  2386. ref={f3dInputRef}
  2387. type="file"
  2388. accept=".f3d"
  2389. className="hidden"
  2390. onChange={(e) => {
  2391. const file = e.target.files?.[0];
  2392. if (file) {
  2393. f3dUploadMutation.mutate(file);
  2394. }
  2395. e.target.value = '';
  2396. }}
  2397. />
  2398. {/* Hidden file input for timelapse upload */}
  2399. <input
  2400. ref={timelapseInputRef}
  2401. type="file"
  2402. accept=".mp4,.avi,.mkv"
  2403. className="hidden"
  2404. onChange={(e) => {
  2405. const file = e.target.files?.[0];
  2406. if (file) {
  2407. timelapseUploadMutation.mutate(file);
  2408. }
  2409. e.target.value = '';
  2410. }}
  2411. />
  2412. </>
  2413. );
  2414. }
  2415. type SortOption = 'date-desc' | 'date-asc' | 'name-asc' | 'name-desc' | 'size-desc' | 'size-asc';
  2416. type ViewMode = 'grid' | 'list' | 'calendar' | 'log';
  2417. type Collection = 'all' | 'recent' | 'this-week' | 'this-month' | 'favorites' | 'not-printed' | 'printed' | 'failed' | 'duplicates';
  2418. // status values that indicate a print attempt has finished (regardless of outcome).
  2419. // `archived` is the only status that means "uploaded but never sent to a printer."
  2420. const PRINTED_STATUSES = ['completed', 'failed', 'aborted', 'cancelled', 'stopped'] as const;
  2421. const collections: { id: Collection; label: string; icon: React.ReactNode }[] = [
  2422. { id: 'all', label: 'All Archives', icon: <FolderOpen className="w-4 h-4" /> },
  2423. { id: 'recent', label: 'Last 24 Hours', icon: <Clock className="w-4 h-4" /> },
  2424. { id: 'this-week', label: 'This Week', icon: <Calendar className="w-4 h-4" /> },
  2425. { id: 'this-month', label: 'This Month', icon: <Calendar className="w-4 h-4" /> },
  2426. { id: 'favorites', label: 'Favorites', icon: <Star className="w-4 h-4" /> },
  2427. { id: 'not-printed', label: 'Not Printed', icon: <Upload className="w-4 h-4" /> },
  2428. { id: 'printed', label: 'Printed', icon: <Printer className="w-4 h-4" /> },
  2429. { id: 'failed', label: 'Failed Prints', icon: <AlertCircle className="w-4 h-4" /> },
  2430. { id: 'duplicates', label: 'Duplicates', icon: <Copy className="w-4 h-4" /> },
  2431. ];
  2432. export function ArchivesPage() {
  2433. const { t } = useTranslation();
  2434. const queryClient = useQueryClient();
  2435. const { showToast } = useToast();
  2436. const { hasPermission, hasAnyPermission } = useAuth();
  2437. const searchInputRef = useRef<HTMLInputElement>(null);
  2438. const [search, setSearch] = useState('');
  2439. const [filterPrinter, setFilterPrinter] = useState<number | null>(() => {
  2440. const saved = localStorage.getItem('archiveFilterPrinter');
  2441. return saved ? Number(saved) : null;
  2442. });
  2443. const [filterMaterial, setFilterMaterial] = useState<string | null>(() =>
  2444. localStorage.getItem('archiveFilterMaterial')
  2445. );
  2446. const [filterColors, setFilterColors] = useState<Set<string>>(() => {
  2447. const saved = localStorage.getItem('archiveFilterColors');
  2448. return saved ? new Set(JSON.parse(saved)) : new Set();
  2449. });
  2450. const [colorFilterMode, setColorFilterMode] = useState<'or' | 'and'>(() =>
  2451. (localStorage.getItem('archiveColorFilterMode') as 'or' | 'and') || 'or'
  2452. );
  2453. const [filterFavorites, setFilterFavorites] = useState(() =>
  2454. localStorage.getItem('archiveFilterFavorites') === 'true'
  2455. );
  2456. const [hideFailed, setHideFailed] = useState(() =>
  2457. localStorage.getItem('archiveHideFailed') === 'true'
  2458. );
  2459. const [hideDuplicates, setHideDuplicates] = useState(() =>
  2460. localStorage.getItem('archiveHideDuplicates') === 'true'
  2461. );
  2462. const [filterTag, setFilterTag] = useState<string | null>(() =>
  2463. localStorage.getItem('archiveFilterTag')
  2464. );
  2465. const [filterFileType, setFilterFileType] = useState<'all' | 'gcode' | 'source'>(() =>
  2466. (localStorage.getItem('archiveFilterFileType') as 'all' | 'gcode' | 'source') || 'all'
  2467. );
  2468. const [showUpload, setShowUpload] = useState(false);
  2469. const [uploadFiles, setUploadFiles] = useState<File[]>([]);
  2470. const [isDraggingOver, setIsDraggingOver] = useState(false);
  2471. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  2472. const [isSelectionMode, setIsSelectionMode] = useState(false);
  2473. const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false);
  2474. const [showBatchTag, setShowBatchTag] = useState(false);
  2475. const [showBatchProject, setShowBatchProject] = useState(false);
  2476. const [viewMode, setViewMode] = useState<ViewMode>(() =>
  2477. (localStorage.getItem('archiveViewMode') as ViewMode) || 'grid'
  2478. );
  2479. const [sortBy, setSortBy] = useState<SortOption>(() =>
  2480. (localStorage.getItem('archiveSortBy') as SortOption) || 'date-desc'
  2481. );
  2482. const [collection, setCollection] = useState<Collection>(() =>
  2483. (localStorage.getItem('archiveCollection') as Collection) || 'all'
  2484. );
  2485. // Pagination state
  2486. const [pageIndex, setPageIndex] = useState(0);
  2487. const [pageSize, setPageSize] = useState<number>(() => {
  2488. try {
  2489. const stored = localStorage.getItem('archivePageSize');
  2490. return stored ? Number(stored) : 50;
  2491. } catch { return 50; }
  2492. });
  2493. const [showExportMenu, setShowExportMenu] = useState(false);
  2494. const [isExporting, setIsExporting] = useState(false);
  2495. const [showCompareModal, setShowCompareModal] = useState(false);
  2496. const [showTagManagement, setShowTagManagement] = useState(false);
  2497. const [showPurgeModal, setShowPurgeModal] = useState(false);
  2498. const [highlightedArchiveId, setHighlightedArchiveId] = useState<number | null>(null);
  2499. const [pendingNavigationArchiveId, setPendingNavigationArchiveId] = useState<number | null>(null);
  2500. // Log view state
  2501. const [logFilterUser, setLogFilterUser] = useState<string | null>(() =>
  2502. localStorage.getItem('logFilterUser') || null
  2503. );
  2504. const [logFilterStatus, setLogFilterStatus] = useState<string | null>(() =>
  2505. localStorage.getItem('logFilterStatus')
  2506. );
  2507. const [logFilterDateFrom, setLogFilterDateFrom] = useState(() =>
  2508. localStorage.getItem('logFilterDateFrom') || ''
  2509. );
  2510. const [logFilterDateTo, setLogFilterDateTo] = useState(() =>
  2511. localStorage.getItem('logFilterDateTo') || ''
  2512. );
  2513. const [logOffset, setLogOffset] = useState(() => {
  2514. const saved = localStorage.getItem('logOffset');
  2515. return saved ? Number(saved) : 0;
  2516. });
  2517. const [showClearLogConfirm, setShowClearLogConfirm] = useState(false);
  2518. const [logPageSize, setLogPageSize] = useState(() => {
  2519. const saved = localStorage.getItem('logPageSize');
  2520. return saved ? Number(saved) : 25;
  2521. });
  2522. const handleNavigateToArchive = useCallback((archiveId: number) => {
  2523. setPendingNavigationArchiveId(archiveId);
  2524. setHighlightedArchiveId(archiveId);
  2525. }, []);
  2526. // Clear highlight after 5 seconds and scroll to highlighted element
  2527. useEffect(() => {
  2528. if (highlightedArchiveId) {
  2529. // Scroll to highlighted element after a short delay (to let the view render)
  2530. const scrollTimer = setTimeout(() => {
  2531. const element = document.querySelector(`[data-archive-id="${highlightedArchiveId}"]`);
  2532. if (element) {
  2533. element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  2534. } else if (pendingNavigationArchiveId === highlightedArchiveId) {
  2535. showToast(t('archives.originalPrintNotVisible'), 'warning');
  2536. }
  2537. if (pendingNavigationArchiveId === highlightedArchiveId) {
  2538. setPendingNavigationArchiveId(null);
  2539. }
  2540. }, 100);
  2541. // Clear highlight after 5 seconds
  2542. const clearTimer = setTimeout(() => setHighlightedArchiveId(null), 5000);
  2543. return () => {
  2544. clearTimeout(scrollTimer);
  2545. clearTimeout(clearTimer);
  2546. };
  2547. }
  2548. }, [highlightedArchiveId, pendingNavigationArchiveId, showToast, t]);
  2549. const { data: archives, isLoading } = useQuery({
  2550. queryKey: ['archives', filterPrinter],
  2551. queryFn: () => api.getArchives(filterPrinter || undefined),
  2552. });
  2553. const { data: printers } = useQuery({
  2554. queryKey: ['printers'],
  2555. queryFn: api.getPrinters,
  2556. });
  2557. const { data: projects } = useQuery({
  2558. queryKey: ['projects'],
  2559. queryFn: () => api.getProjects(),
  2560. });
  2561. const { data: settings } = useQuery({
  2562. queryKey: ['settings'],
  2563. queryFn: api.getSettings,
  2564. });
  2565. const { data: users } = useQuery({
  2566. queryKey: ['users'],
  2567. queryFn: api.getUsers,
  2568. enabled: viewMode === 'log',
  2569. });
  2570. const { data: printLogData, isLoading: isLogLoading } = useQuery({
  2571. queryKey: ['print-log', filterPrinter, logFilterUser, logFilterStatus, logFilterDateFrom, logFilterDateTo, search, logOffset, logPageSize],
  2572. queryFn: () => api.getPrintLog({
  2573. search: search || undefined,
  2574. printerId: filterPrinter || undefined,
  2575. username: logFilterUser || undefined,
  2576. status: logFilterStatus || undefined,
  2577. dateFrom: logFilterDateFrom || undefined,
  2578. dateTo: logFilterDateTo || undefined,
  2579. limit: logPageSize,
  2580. offset: logOffset,
  2581. }),
  2582. enabled: viewMode === 'log',
  2583. });
  2584. const timeFormat: TimeFormat = settings?.time_format || 'system';
  2585. const preferredSlicer: SlicerType = settings?.preferred_slicer || 'bambu_studio';
  2586. const useSlicerApi = settings?.use_slicer_api ?? false;
  2587. const currency = getCurrencySymbol(settings?.currency || 'USD');
  2588. const bulkDeleteMutation = useMutation({
  2589. mutationFn: async (ids: number[]) => {
  2590. await Promise.all(ids.map((id) => api.deleteArchive(id)));
  2591. return ids.length;
  2592. },
  2593. onSuccess: (count) => {
  2594. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2595. setSelectedIds(new Set());
  2596. showToast(`${count} archive${count !== 1 ? 's' : ''} deleted`);
  2597. },
  2598. onError: () => {
  2599. showToast(t('archives.toast.failedDeleteArchives'), 'error');
  2600. },
  2601. });
  2602. const clearLogMutation = useMutation({
  2603. mutationFn: () => api.clearPrintLog(),
  2604. onSuccess: (data) => {
  2605. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  2606. setLogOffset(0);
  2607. showToast(t('archives.log.cleared', { count: data.deleted }));
  2608. },
  2609. onError: () => {
  2610. showToast(t('archives.log.clearFailed'), 'error');
  2611. },
  2612. });
  2613. // Persist all filters to localStorage
  2614. useEffect(() => {
  2615. if (filterPrinter !== null) {
  2616. localStorage.setItem('archiveFilterPrinter', filterPrinter.toString());
  2617. } else {
  2618. localStorage.removeItem('archiveFilterPrinter');
  2619. }
  2620. }, [filterPrinter]);
  2621. useEffect(() => {
  2622. if (filterMaterial) {
  2623. localStorage.setItem('archiveFilterMaterial', filterMaterial);
  2624. } else {
  2625. localStorage.removeItem('archiveFilterMaterial');
  2626. }
  2627. }, [filterMaterial]);
  2628. useEffect(() => {
  2629. localStorage.setItem('archiveFilterColors', JSON.stringify([...filterColors]));
  2630. }, [filterColors]);
  2631. useEffect(() => {
  2632. localStorage.setItem('archiveColorFilterMode', colorFilterMode);
  2633. }, [colorFilterMode]);
  2634. useEffect(() => {
  2635. localStorage.setItem('archiveFilterFavorites', filterFavorites.toString());
  2636. }, [filterFavorites]);
  2637. useEffect(() => {
  2638. localStorage.setItem('archiveHideFailed', hideFailed.toString());
  2639. }, [hideFailed]);
  2640. useEffect(() => {
  2641. localStorage.setItem('archiveHideDuplicates', hideDuplicates.toString());
  2642. }, [hideDuplicates]);
  2643. useEffect(() => {
  2644. if (filterTag) {
  2645. localStorage.setItem('archiveFilterTag', filterTag);
  2646. } else {
  2647. localStorage.removeItem('archiveFilterTag');
  2648. }
  2649. }, [filterTag]);
  2650. useEffect(() => {
  2651. localStorage.setItem('archiveFilterFileType', filterFileType);
  2652. }, [filterFileType]);
  2653. // Reset page when filters/search/sort/collection change
  2654. useEffect(() => {
  2655. setPageIndex(0);
  2656. }, [search, filterPrinter, filterMaterial, filterColors, colorFilterMode, filterFavorites, hideFailed, hideDuplicates, filterTag, filterFileType, sortBy, collection]);
  2657. useEffect(() => {
  2658. try { localStorage.setItem('archivePageSize', String(pageSize)); } catch { /* ignore */ }
  2659. }, [pageSize]);
  2660. useEffect(() => {
  2661. localStorage.setItem('archiveViewMode', viewMode);
  2662. }, [viewMode]);
  2663. useEffect(() => {
  2664. localStorage.setItem('archiveSortBy', sortBy);
  2665. }, [sortBy]);
  2666. useEffect(() => {
  2667. localStorage.setItem('archiveCollection', collection);
  2668. }, [collection]);
  2669. // Persist log view filters
  2670. useEffect(() => {
  2671. if (logFilterUser) {
  2672. localStorage.setItem('logFilterUser', logFilterUser);
  2673. } else {
  2674. localStorage.removeItem('logFilterUser');
  2675. }
  2676. }, [logFilterUser]);
  2677. useEffect(() => {
  2678. if (logFilterStatus) {
  2679. localStorage.setItem('logFilterStatus', logFilterStatus);
  2680. } else {
  2681. localStorage.removeItem('logFilterStatus');
  2682. }
  2683. }, [logFilterStatus]);
  2684. useEffect(() => {
  2685. if (logFilterDateFrom) {
  2686. localStorage.setItem('logFilterDateFrom', logFilterDateFrom);
  2687. } else {
  2688. localStorage.removeItem('logFilterDateFrom');
  2689. }
  2690. }, [logFilterDateFrom]);
  2691. useEffect(() => {
  2692. if (logFilterDateTo) {
  2693. localStorage.setItem('logFilterDateTo', logFilterDateTo);
  2694. } else {
  2695. localStorage.removeItem('logFilterDateTo');
  2696. }
  2697. }, [logFilterDateTo]);
  2698. useEffect(() => {
  2699. localStorage.setItem('logOffset', logOffset.toString());
  2700. }, [logOffset]);
  2701. useEffect(() => {
  2702. localStorage.setItem('logPageSize', logPageSize.toString());
  2703. }, [logPageSize]);
  2704. const printerMap = new Map(printers?.map((p) => [p.id, p.name]) || []);
  2705. // Extract unique materials and colors from archives
  2706. const uniqueMaterials = [...new Set(
  2707. archives?.flatMap(a => a.filament_type?.split(', ') || []).filter(Boolean) || []
  2708. )].sort();
  2709. const uniqueColors = [...new Set(
  2710. archives?.flatMap(a => a.filament_color?.split(',') || []).filter(Boolean) || []
  2711. )];
  2712. const uniqueTags = [...new Set(
  2713. archives?.flatMap(a => a.tags?.split(',').map(t => t.trim()) || []).filter(Boolean) || []
  2714. )].sort();
  2715. const filteredArchives = archives
  2716. ?.filter((a) => {
  2717. // Collection filter
  2718. const now = new Date();
  2719. const archiveDate = parseUTCDate(a.created_at) || new Date(0);
  2720. let matchesCollection = true;
  2721. switch (collection) {
  2722. case 'recent':
  2723. matchesCollection = (now.getTime() - archiveDate.getTime()) < 24 * 60 * 60 * 1000;
  2724. break;
  2725. case 'this-week':
  2726. matchesCollection = (now.getTime() - archiveDate.getTime()) < 7 * 24 * 60 * 60 * 1000;
  2727. break;
  2728. case 'this-month':
  2729. matchesCollection = archiveDate.getMonth() === now.getMonth() && archiveDate.getFullYear() === now.getFullYear();
  2730. break;
  2731. case 'favorites':
  2732. matchesCollection = a.is_favorite === true;
  2733. break;
  2734. case 'not-printed':
  2735. matchesCollection = a.status === 'archived';
  2736. break;
  2737. case 'printed':
  2738. matchesCollection = (PRINTED_STATUSES as readonly string[]).includes(a.status);
  2739. break;
  2740. case 'failed':
  2741. matchesCollection = a.status === 'failed' || a.status === 'aborted';
  2742. break;
  2743. case 'duplicates':
  2744. matchesCollection = a.duplicate_count > 0;
  2745. break;
  2746. }
  2747. // Search filter
  2748. const matchesSearch = (a.print_name || a.filename).toLowerCase().includes(search.toLowerCase());
  2749. // Material filter
  2750. const matchesMaterial = !filterMaterial ||
  2751. (a.filament_type?.split(', ').includes(filterMaterial));
  2752. // Color filter (AND: must have all selected colors, OR: must have any selected color)
  2753. const archiveColors = a.filament_color?.split(',') || [];
  2754. const matchesColor = filterColors.size === 0 ||
  2755. (colorFilterMode === 'or'
  2756. ? archiveColors.some(c => filterColors.has(c))
  2757. : [...filterColors].every(c => archiveColors.includes(c)));
  2758. // Favorites filter (only apply if not using favorites collection)
  2759. const matchesFavorites = collection === 'favorites' || !filterFavorites || a.is_favorite;
  2760. // Hide failed filter (don't apply when viewing failed collection)
  2761. const matchesHideFailed = collection === 'failed' || !hideFailed || (a.status !== 'failed' && a.status !== 'aborted');
  2762. // Hide duplicates filter (don't apply when viewing duplicates collection)
  2763. const matchesHideDuplicates =
  2764. collection === 'duplicates' || !hideDuplicates || a.duplicate_count === 0 || a.duplicate_sequence === 0;
  2765. // Tag filter
  2766. const archiveTags = a.tags?.split(',').map(t => t.trim()) || [];
  2767. const matchesTag = !filterTag || archiveTags.includes(filterTag);
  2768. // File type filter (gcode = sliced, source = project file only)
  2769. const isGcodeFile = isSlicedFile(a);
  2770. const matchesFileType = filterFileType === 'all' ||
  2771. (filterFileType === 'gcode' && isGcodeFile) ||
  2772. (filterFileType === 'source' && !isGcodeFile);
  2773. return matchesCollection && matchesSearch && matchesMaterial && matchesColor && matchesFavorites && matchesHideFailed && matchesHideDuplicates && matchesTag && matchesFileType;
  2774. })
  2775. .sort((a, b) => {
  2776. switch (sortBy) {
  2777. case 'date-desc':
  2778. return (parseUTCDate(b.created_at)?.getTime() || 0) - (parseUTCDate(a.created_at)?.getTime() || 0);
  2779. case 'date-asc':
  2780. return (parseUTCDate(a.created_at)?.getTime() || 0) - (parseUTCDate(b.created_at)?.getTime() || 0);
  2781. case 'name-asc':
  2782. return (a.print_name || a.filename).localeCompare(b.print_name || b.filename);
  2783. case 'name-desc':
  2784. return (b.print_name || b.filename).localeCompare(a.print_name || a.filename);
  2785. case 'size-desc':
  2786. return b.file_size - a.file_size;
  2787. case 'size-asc':
  2788. return a.file_size - b.file_size;
  2789. default:
  2790. return 0;
  2791. }
  2792. });
  2793. // Pagination
  2794. const totalFiltered = filteredArchives?.length || 0;
  2795. const showAll = pageSize === -1;
  2796. const effectivePageSize = showAll ? totalFiltered || 1 : pageSize;
  2797. const totalPages = Math.max(1, Math.ceil(totalFiltered / effectivePageSize));
  2798. const paginatedArchives = showAll
  2799. ? filteredArchives
  2800. : filteredArchives?.slice(pageIndex * effectivePageSize, (pageIndex + 1) * effectivePageSize);
  2801. // Jump to the page containing the highlighted archive
  2802. useEffect(() => {
  2803. if (highlightedArchiveId && filteredArchives && !showAll) {
  2804. const idx = filteredArchives.findIndex(a => a.id === highlightedArchiveId);
  2805. if (idx >= 0) {
  2806. const targetPage = Math.floor(idx / effectivePageSize);
  2807. if (targetPage !== pageIndex) setPageIndex(targetPage);
  2808. }
  2809. }
  2810. // eslint-disable-next-line react-hooks/exhaustive-deps
  2811. }, [highlightedArchiveId]);
  2812. const selectionMode = isSelectionMode || selectedIds.size > 0;
  2813. const toggleSelect = (id: number) => {
  2814. setSelectedIds((prev) => {
  2815. const next = new Set(prev);
  2816. if (next.has(id)) {
  2817. next.delete(id);
  2818. } else {
  2819. next.add(id);
  2820. }
  2821. return next;
  2822. });
  2823. };
  2824. const selectAll = () => {
  2825. if (filteredArchives) {
  2826. setSelectedIds(new Set(filteredArchives.map((a) => a.id)));
  2827. }
  2828. };
  2829. const clearSelection = () => {
  2830. setSelectedIds(new Set());
  2831. setIsSelectionMode(false);
  2832. };
  2833. const toggleColor = (color: string) => {
  2834. setFilterColors((prev) => {
  2835. const next = new Set(prev);
  2836. if (next.has(color)) {
  2837. next.delete(color);
  2838. } else {
  2839. next.add(color);
  2840. }
  2841. return next;
  2842. });
  2843. };
  2844. const clearColorFilter = () => {
  2845. setFilterColors(new Set());
  2846. };
  2847. const clearTopFilters = () => {
  2848. setSearch('');
  2849. setFilterPrinter(null);
  2850. setFilterMaterial(null);
  2851. setFilterFavorites(false);
  2852. setHideFailed(false);
  2853. setHideDuplicates(false);
  2854. setFilterTag(null);
  2855. setFilterFileType('all');
  2856. };
  2857. const hasTopFilters = search || filterPrinter || filterMaterial || filterFavorites || hideFailed || hideDuplicates || filterTag || filterFileType !== 'all';
  2858. // Drag & drop handlers for page-wide upload
  2859. const handleDragOver = useCallback((e: React.DragEvent) => {
  2860. e.preventDefault();
  2861. if (e.dataTransfer.types.includes('Files')) {
  2862. setIsDraggingOver(true);
  2863. }
  2864. }, []);
  2865. const handleDragLeave = useCallback((e: React.DragEvent) => {
  2866. e.preventDefault();
  2867. // Only hide if leaving the page (not entering a child)
  2868. if (e.currentTarget === e.target) {
  2869. setIsDraggingOver(false);
  2870. }
  2871. }, []);
  2872. const handleDrop = useCallback((e: React.DragEvent) => {
  2873. e.preventDefault();
  2874. setIsDraggingOver(false);
  2875. const droppedFiles = Array.from(e.dataTransfer.files).filter(f => f.name.endsWith('.3mf'));
  2876. if (droppedFiles.length > 0) {
  2877. setUploadFiles(droppedFiles);
  2878. setShowUpload(true);
  2879. } else if (e.dataTransfer.files.length > 0) {
  2880. showToast(t('archives.page.only3mfSupported'), 'warning');
  2881. }
  2882. }, [showToast, t]);
  2883. // Keyboard shortcuts
  2884. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  2885. const target = e.target as HTMLElement;
  2886. // Ignore if typing in an input/textarea
  2887. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  2888. if (e.key === 'Escape') {
  2889. target.blur();
  2890. }
  2891. return;
  2892. }
  2893. switch (e.key) {
  2894. case '/':
  2895. e.preventDefault();
  2896. searchInputRef.current?.focus();
  2897. break;
  2898. case 'u':
  2899. case 'U':
  2900. if (!e.metaKey && !e.ctrlKey) {
  2901. e.preventDefault();
  2902. setShowUpload(true);
  2903. }
  2904. break;
  2905. case 'Escape':
  2906. if (selectionMode) {
  2907. clearSelection();
  2908. }
  2909. break;
  2910. }
  2911. }, [selectionMode]);
  2912. useEffect(() => {
  2913. document.addEventListener('keydown', handleKeyDown);
  2914. return () => document.removeEventListener('keydown', handleKeyDown);
  2915. }, [handleKeyDown]);
  2916. return (
  2917. <div
  2918. className="p-4 md:p-8 relative"
  2919. onDragOver={handleDragOver}
  2920. onDragLeave={handleDragLeave}
  2921. onDrop={handleDrop}
  2922. >
  2923. {/* Drag & Drop Overlay */}
  2924. {isDraggingOver && (
  2925. <div className="fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none">
  2926. <div className="border-4 border-dashed border-bambu-green rounded-xl p-12 text-center">
  2927. <Upload className="w-16 h-16 mx-auto mb-4 text-bambu-green" />
  2928. <p className="text-2xl font-semibold text-white mb-2">Drop .3mf files here</p>
  2929. <p className="text-bambu-gray">{t('archives.releaseToUpload')}</p>
  2930. </div>
  2931. </div>
  2932. )}
  2933. {/* Selection Toolbar */}
  2934. {selectionMode && (
  2935. <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-4">
  2936. <Button variant="secondary" size="sm" onClick={clearSelection}>
  2937. <X className="w-4 h-4" />
  2938. Close
  2939. </Button>
  2940. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  2941. <span className="text-white font-medium">
  2942. {selectedIds.size} selected
  2943. </span>
  2944. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  2945. <Button variant="secondary" size="sm" onClick={selectAll}>
  2946. Select All
  2947. </Button>
  2948. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  2949. <Button
  2950. variant="secondary"
  2951. size="sm"
  2952. onClick={() => setShowBatchTag(true)}
  2953. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  2954. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  2955. >
  2956. <Tag className="w-4 h-4" />
  2957. Tags
  2958. </Button>
  2959. <Button
  2960. variant="secondary"
  2961. size="sm"
  2962. onClick={() => setShowBatchProject(true)}
  2963. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  2964. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  2965. >
  2966. <FolderKanban className="w-4 h-4" />
  2967. Project
  2968. </Button>
  2969. <Button
  2970. variant="secondary"
  2971. size="sm"
  2972. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  2973. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  2974. onClick={() => {
  2975. const ids = Array.from(selectedIds);
  2976. Promise.all(ids.map(id => api.toggleFavorite(id)))
  2977. .then(() => {
  2978. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2979. showToast(`Toggled favorites for ${ids.length} archive${ids.length !== 1 ? 's' : ''}`);
  2980. })
  2981. .catch(() => {
  2982. showToast(t('archives.toast.failedUpdateFavorites'), 'error');
  2983. });
  2984. }}
  2985. >
  2986. <Star className="w-4 h-4" />
  2987. Favorite
  2988. </Button>
  2989. <Button
  2990. size="sm"
  2991. className="bg-red-500 hover:bg-red-600"
  2992. onClick={() => setShowBulkDeleteConfirm(true)}
  2993. disabled={!hasAnyPermission('archives:delete_own', 'archives:delete_all')}
  2994. title={!hasAnyPermission('archives:delete_own', 'archives:delete_all') ? t('archives.permission.noDelete') : undefined}
  2995. >
  2996. <Trash2 className="w-4 h-4" />
  2997. Delete
  2998. </Button>
  2999. </div>
  3000. )}
  3001. <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
  3002. <div>
  3003. <div className="flex items-start gap-3">
  3004. <div>
  3005. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  3006. <ArchiveIcon className="w-7 h-7 text-bambu-green" />
  3007. Archives
  3008. </h1>
  3009. <p className="text-bambu-gray mt-1">
  3010. {filteredArchives?.length || 0} of {archives?.length || 0} prints
  3011. </p>
  3012. </div>
  3013. <select
  3014. className="mt-0.5 px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray-light text-sm focus:border-bambu-green focus:outline-none"
  3015. value={collection}
  3016. onChange={(e) => setCollection(e.target.value as Collection)}
  3017. >
  3018. {collections.map((c) => (
  3019. <option key={c.id} value={c.id}>
  3020. {c.label}
  3021. </option>
  3022. ))}
  3023. </select>
  3024. </div>
  3025. </div>
  3026. <div className="flex items-center gap-2 sm:gap-3 flex-wrap">
  3027. {/* Export dropdown */}
  3028. <div className="relative">
  3029. <Button
  3030. variant="secondary"
  3031. onClick={() => setShowExportMenu(!showExportMenu)}
  3032. disabled={isExporting}
  3033. >
  3034. {isExporting ? (
  3035. <Loader2 className="w-4 h-4 animate-spin" />
  3036. ) : (
  3037. <FileSpreadsheet className="w-4 h-4" />
  3038. )}
  3039. Export
  3040. </Button>
  3041. {showExportMenu && (
  3042. <div className="absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20">
  3043. <button
  3044. className="w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg"
  3045. onClick={async () => {
  3046. setShowExportMenu(false);
  3047. setIsExporting(true);
  3048. try {
  3049. const { blob, filename } = await api.exportArchives({
  3050. format: 'csv',
  3051. printerId: filterPrinter || undefined,
  3052. status: collection === 'failed' ? 'failed' : undefined,
  3053. search: search || undefined,
  3054. });
  3055. const url = URL.createObjectURL(blob);
  3056. const a = document.createElement('a');
  3057. a.href = url;
  3058. a.download = filename;
  3059. a.click();
  3060. URL.revokeObjectURL(url);
  3061. showToast(t('archives.toast.exportDownloaded'));
  3062. } catch {
  3063. showToast(t('archives.toast.exportFailed'), 'error');
  3064. } finally {
  3065. setIsExporting(false);
  3066. }
  3067. }}
  3068. >
  3069. <FileText className="w-4 h-4" />
  3070. Export as CSV
  3071. </button>
  3072. <button
  3073. className="w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg"
  3074. onClick={async () => {
  3075. setShowExportMenu(false);
  3076. setIsExporting(true);
  3077. try {
  3078. const { blob, filename } = await api.exportArchives({
  3079. format: 'xlsx',
  3080. printerId: filterPrinter || undefined,
  3081. status: collection === 'failed' ? 'failed' : undefined,
  3082. search: search || undefined,
  3083. });
  3084. const url = URL.createObjectURL(blob);
  3085. const a = document.createElement('a');
  3086. a.href = url;
  3087. a.download = filename;
  3088. a.click();
  3089. URL.revokeObjectURL(url);
  3090. showToast(t('archives.toast.exportDownloaded'));
  3091. } catch {
  3092. showToast(t('archives.toast.exportFailed'), 'error');
  3093. } finally {
  3094. setIsExporting(false);
  3095. }
  3096. }}
  3097. >
  3098. <FileSpreadsheet className="w-4 h-4" />
  3099. Export as Excel
  3100. </button>
  3101. </div>
  3102. )}
  3103. </div>
  3104. {/* Compare button (only when 2-5 items selected) */}
  3105. {selectedIds.size >= 2 && selectedIds.size <= 5 && (
  3106. <Button
  3107. variant="secondary"
  3108. onClick={() => setShowCompareModal(true)}
  3109. >
  3110. <GitCompare className="w-4 h-4" />
  3111. Compare ({selectedIds.size})
  3112. </Button>
  3113. )}
  3114. {!selectionMode && (
  3115. <Button variant="secondary" onClick={() => setIsSelectionMode(true)}>
  3116. <CheckSquare className="w-4 h-4" />
  3117. Select
  3118. </Button>
  3119. )}
  3120. <Button
  3121. onClick={() => setShowUpload(true)}
  3122. disabled={!hasPermission('archives:create')}
  3123. title={!hasPermission('archives:create') ? t('archives.permission.noCreate') : undefined}
  3124. >
  3125. <Upload className="w-4 h-4" />
  3126. Upload 3MF
  3127. </Button>
  3128. {hasPermission('archives:purge') && (
  3129. <Button
  3130. variant="secondary"
  3131. onClick={() => setShowPurgeModal(true)}
  3132. title={t('archivePurge.headerTooltip')}
  3133. >
  3134. <Trash2 className="w-4 h-4 mr-2" />
  3135. {t('archivePurge.headerButton')}
  3136. </Button>
  3137. )}
  3138. </div>
  3139. </div>
  3140. {/* View mode toggle — always visible */}
  3141. <div className="flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4">
  3142. <button
  3143. className={`p-2 ${viewMode === 'grid' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3144. onClick={() => setViewMode('grid')}
  3145. title={t('archives.gridView')}
  3146. >
  3147. <LayoutGrid className="w-4 h-4" />
  3148. </button>
  3149. <button
  3150. className={`p-2 ${viewMode === 'list' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3151. onClick={() => setViewMode('list')}
  3152. title={t('archives.listView')}
  3153. >
  3154. <List className="w-4 h-4" />
  3155. </button>
  3156. <button
  3157. className={`p-2 ${viewMode === 'calendar' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3158. onClick={() => setViewMode('calendar')}
  3159. title={t('archives.calendarView')}
  3160. >
  3161. <CalendarDays className="w-4 h-4" />
  3162. </button>
  3163. <button
  3164. className={`p-2 ${viewMode === 'log' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3165. onClick={() => setViewMode('log')}
  3166. title={t('archives.logView')}
  3167. >
  3168. <ClipboardList className="w-4 h-4" />
  3169. </button>
  3170. </div>
  3171. {/* Filters (hidden in log view which has its own filters) */}
  3172. {viewMode !== 'log' && <Card className="mb-6">
  3173. <CardContent className="py-4">
  3174. <div className="flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap">
  3175. {/* Search - full width on mobile */}
  3176. <div className="w-full md:flex-1 relative md:min-w-[200px]">
  3177. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  3178. <input
  3179. ref={searchInputRef}
  3180. type="text"
  3181. placeholder={t('archives.searchPlaceholder')}
  3182. className="w-full pl-10 pr-4 py-3 md:py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3183. value={search}
  3184. onChange={(e) => setSearch(e.target.value)}
  3185. />
  3186. </div>
  3187. {/* Filters - horizontal scroll on mobile */}
  3188. <div className="flex gap-2 md:gap-4 overflow-x-auto pb-1 md:pb-0 -mx-4 px-4 md:mx-0 md:px-0 md:flex-wrap scrollbar-hide">
  3189. <div className="flex items-center gap-2 flex-shrink-0">
  3190. <Filter className="w-4 h-4 text-bambu-gray hidden md:block" />
  3191. <select
  3192. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3193. value={filterPrinter || ''}
  3194. onChange={(e) =>
  3195. setFilterPrinter(e.target.value ? Number(e.target.value) : null)
  3196. }
  3197. >
  3198. <option value="">All Printers</option>
  3199. {printers?.map((p) => (
  3200. <option key={p.id} value={p.id}>
  3201. {p.name}
  3202. </option>
  3203. ))}
  3204. </select>
  3205. </div>
  3206. <div className="flex items-center gap-2 flex-shrink-0">
  3207. <Package className="w-4 h-4 text-bambu-gray hidden md:block" />
  3208. <select
  3209. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3210. value={filterMaterial || ''}
  3211. onChange={(e) =>
  3212. setFilterMaterial(e.target.value || null)
  3213. }
  3214. >
  3215. <option value="">All Materials</option>
  3216. {uniqueMaterials.map((m) => (
  3217. <option key={m} value={m}>
  3218. {m}
  3219. </option>
  3220. ))}
  3221. </select>
  3222. </div>
  3223. <div className="flex items-center gap-2 flex-shrink-0">
  3224. <FileCode className="w-4 h-4 text-bambu-gray hidden md:block" />
  3225. <select
  3226. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3227. value={filterFileType}
  3228. onChange={(e) => setFilterFileType(e.target.value as 'all' | 'gcode' | 'source')}
  3229. >
  3230. <option value="all">All Files</option>
  3231. <option value="gcode">Sliced (GCODE)</option>
  3232. <option value="source">Source Only</option>
  3233. </select>
  3234. </div>
  3235. <button
  3236. onClick={() => setFilterFavorites(!filterFavorites)}
  3237. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3238. filterFavorites
  3239. ? 'bg-yellow-500/20 border-yellow-500 text-yellow-400'
  3240. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3241. }`}
  3242. title={filterFavorites ? t('archives.showAll') : t('archives.showFavoritesOnly')}
  3243. >
  3244. <Star className={`w-4 h-4 ${filterFavorites ? 'fill-yellow-400' : ''}`} />
  3245. <span className="text-sm hidden md:inline">Favorites</span>
  3246. </button>
  3247. <button
  3248. onClick={() => setHideFailed(!hideFailed)}
  3249. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3250. hideFailed
  3251. ? 'bg-red-500/20 border-red-500 text-red-400'
  3252. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3253. }`}
  3254. title={hideFailed ? t('archives.showFailedPrints') : t('archives.hideFailedPrints')}
  3255. >
  3256. <AlertCircle className={`w-4 h-4 ${hideFailed ? '' : ''}`} />
  3257. <span className="text-sm hidden md:inline">Hide Failed</span>
  3258. </button>
  3259. <button
  3260. onClick={() => setHideDuplicates(!hideDuplicates)}
  3261. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3262. hideDuplicates
  3263. ? 'bg-purple-500/20 border-purple-500 text-purple-400'
  3264. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3265. }`}
  3266. title={t('archives.hideDuplicates')}
  3267. >
  3268. <Copy className="w-4 h-4" />
  3269. <span className="text-sm hidden md:inline">{t('archives.hideDuplicates')}</span>
  3270. </button>
  3271. {uniqueTags.length > 0 && (
  3272. <div className="flex items-center gap-2 flex-shrink-0">
  3273. <Tag className="w-4 h-4 text-bambu-gray hidden md:block" />
  3274. <select
  3275. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3276. value={filterTag || ''}
  3277. onChange={(e) => setFilterTag(e.target.value || null)}
  3278. >
  3279. <option value="">All Tags</option>
  3280. {uniqueTags.map((t) => (
  3281. <option key={t} value={t}>
  3282. {t}
  3283. </option>
  3284. ))}
  3285. </select>
  3286. <button
  3287. onClick={() => setShowTagManagement(true)}
  3288. className="p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors"
  3289. title={t('archives.manageTags')}
  3290. >
  3291. <Settings className="w-4 h-4" />
  3292. </button>
  3293. </div>
  3294. )}
  3295. <div className="flex items-center gap-2 flex-shrink-0">
  3296. <ArrowUpDown className="w-4 h-4 text-bambu-gray hidden md:block" />
  3297. <select
  3298. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3299. value={sortBy}
  3300. onChange={(e) => setSortBy(e.target.value as SortOption)}
  3301. >
  3302. <option value="date-desc">{t('archives.sortNewest')}</option>
  3303. <option value="date-asc">{t('archives.sortOldest')}</option>
  3304. <option value="name-asc">{t('archives.sortName')} A-Z</option>
  3305. <option value="name-desc">{t('archives.sortName')} Z-A</option>
  3306. <option value="size-desc">{t('archives.sortLargest')}</option>
  3307. <option value="size-asc">{t('archives.sortSmallest')}</option>
  3308. </select>
  3309. </div>
  3310. </div>
  3311. {hasTopFilters && (
  3312. <Button
  3313. variant="ghost"
  3314. size="sm"
  3315. onClick={clearTopFilters}
  3316. className="text-bambu-gray hover:text-white"
  3317. >
  3318. <X className="w-4 h-4" />
  3319. Reset
  3320. </Button>
  3321. )}
  3322. </div>
  3323. {/* Color Filter */}
  3324. {uniqueColors.length > 0 && (
  3325. <div className="flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary">
  3326. <span className="text-xs text-bambu-gray">Colors:</span>
  3327. {filterColors.size > 1 && (
  3328. <button
  3329. onClick={() => setColorFilterMode(m => m === 'or' ? 'and' : 'or')}
  3330. className={`px-2 py-0.5 text-xs rounded transition-colors ${
  3331. colorFilterMode === 'and'
  3332. ? 'bg-bambu-green text-white'
  3333. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3334. }`}
  3335. title={colorFilterMode === 'or' ? 'Match ANY selected color' : 'Match ALL selected colors'}
  3336. >
  3337. {colorFilterMode.toUpperCase()}
  3338. </button>
  3339. )}
  3340. <div className="flex items-center gap-1.5 flex-wrap">
  3341. {uniqueColors.map((color) => (
  3342. <button
  3343. key={color}
  3344. onClick={() => toggleColor(color)}
  3345. className={`w-6 h-6 rounded-full border-2 transition-all ${
  3346. filterColors.has(color)
  3347. ? 'border-bambu-green scale-110'
  3348. : 'border-white/20 hover:border-white/40'
  3349. }`}
  3350. style={{ backgroundColor: color }}
  3351. title={color}
  3352. />
  3353. ))}
  3354. </div>
  3355. {filterColors.size > 0 && (
  3356. <button
  3357. onClick={clearColorFilter}
  3358. className="text-xs text-bambu-gray hover:text-white flex items-center gap-1"
  3359. >
  3360. <X className="w-3 h-3" />
  3361. Clear
  3362. </button>
  3363. )}
  3364. </div>
  3365. )}
  3366. </CardContent>
  3367. </Card>}
  3368. {/* Pending Uploads Panel (visible when in queue mode with pending files) */}
  3369. <PendingUploadsPanel />
  3370. {/* Archives */}
  3371. {isLoading ? (
  3372. <div className="text-center py-12 text-bambu-gray">{t('archives.loadingArchives')}</div>
  3373. ) : filteredArchives?.length === 0 ? (
  3374. <Card>
  3375. <CardContent className="text-center py-12">
  3376. <p className="text-bambu-gray">
  3377. {search ? t('archives.noArchivesSearch') : t('archives.noArchivesYet')}
  3378. </p>
  3379. <p className="text-sm text-bambu-gray mt-2">
  3380. Archives are created automatically when prints complete
  3381. </p>
  3382. </CardContent>
  3383. </Card>
  3384. ) : viewMode === 'calendar' ? (
  3385. <Card className="p-6">
  3386. <CalendarView
  3387. archives={filteredArchives || []}
  3388. onArchiveClick={(archive) => {
  3389. // Switch to grid view and highlight the archive
  3390. setSearch(''); // Clear search to show all archives
  3391. setViewMode('grid');
  3392. setHighlightedArchiveId(archive.id);
  3393. }}
  3394. highlightedArchiveId={highlightedArchiveId}
  3395. />
  3396. </Card>
  3397. ) : viewMode === 'grid' ? (
  3398. <>
  3399. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
  3400. {paginatedArchives?.map((archive) => (
  3401. <ArchiveCard
  3402. key={archive.id}
  3403. archive={archive}
  3404. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model || 'No Printer')}
  3405. isSelected={selectedIds.has(archive.id)}
  3406. onSelect={toggleSelect}
  3407. selectionMode={selectionMode}
  3408. projects={projects}
  3409. isHighlighted={archive.id === highlightedArchiveId}
  3410. timeFormat={timeFormat}
  3411. preferredSlicer={preferredSlicer}
  3412. useSlicerApi={useSlicerApi}
  3413. currency={currency}
  3414. t={t}
  3415. onNavigateToArchive={handleNavigateToArchive}
  3416. />
  3417. ))}
  3418. </div>
  3419. <ArchivePaginationBar
  3420. pageIndex={pageIndex}
  3421. pageSize={pageSize}
  3422. totalRows={totalFiltered}
  3423. totalPages={totalPages}
  3424. onPageChange={setPageIndex}
  3425. onPageSizeChange={(size) => { setPageSize(size); setPageIndex(0); }}
  3426. t={t}
  3427. />
  3428. </>
  3429. ) : viewMode === 'list' ? (
  3430. <>
  3431. <Card>
  3432. <div className="divide-y divide-bambu-dark-tertiary">
  3433. {/* List Header */}
  3434. <div className="grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium">
  3435. <div className="col-span-1"></div>
  3436. <div className="col-span-4">Name</div>
  3437. <div className="col-span-2">Printer</div>
  3438. <div className="col-span-2">Date</div>
  3439. <div className="col-span-1">Size</div>
  3440. <div className="col-span-2 text-right">Actions</div>
  3441. </div>
  3442. {/* List Items */}
  3443. {paginatedArchives?.map((archive) => (
  3444. <ArchiveListRow
  3445. key={archive.id}
  3446. archive={archive}
  3447. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model || 'No Printer')}
  3448. isSelected={selectedIds.has(archive.id)}
  3449. onSelect={toggleSelect}
  3450. selectionMode={selectionMode}
  3451. projects={projects}
  3452. isHighlighted={archive.id === highlightedArchiveId}
  3453. preferredSlicer={preferredSlicer}
  3454. useSlicerApi={useSlicerApi}
  3455. t={t}
  3456. onNavigateToArchive={handleNavigateToArchive}
  3457. />
  3458. ))}
  3459. </div>
  3460. </Card>
  3461. <ArchivePaginationBar
  3462. pageIndex={pageIndex}
  3463. pageSize={pageSize}
  3464. totalRows={totalFiltered}
  3465. totalPages={totalPages}
  3466. onPageChange={setPageIndex}
  3467. onPageSizeChange={(size) => { setPageSize(size); setPageIndex(0); }}
  3468. t={t}
  3469. />
  3470. </>
  3471. ) : viewMode === 'log' ? (
  3472. <div className="space-y-4">
  3473. {/* Log filters */}
  3474. <Card>
  3475. <CardContent className="py-3">
  3476. <div className="flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap">
  3477. {/* Search */}
  3478. <div className="flex-1 relative md:min-w-[200px]">
  3479. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  3480. <input
  3481. type="text"
  3482. placeholder={t('archives.searchPlaceholder')}
  3483. className="w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  3484. value={search}
  3485. onChange={(e) => { setSearch(e.target.value); setLogOffset(0); }}
  3486. />
  3487. </div>
  3488. {/* Printer filter */}
  3489. <select
  3490. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  3491. value={filterPrinter || ''}
  3492. onChange={(e) => { setFilterPrinter(e.target.value ? Number(e.target.value) : null); setLogOffset(0); }}
  3493. >
  3494. <option value="">{t('archives.log.allPrinters')}</option>
  3495. {printers?.map((p) => (
  3496. <option key={p.id} value={p.id}>{p.name}</option>
  3497. ))}
  3498. </select>
  3499. {/* User filter */}
  3500. <select
  3501. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  3502. value={logFilterUser || ''}
  3503. onChange={(e) => { setLogFilterUser(e.target.value || null); setLogOffset(0); }}
  3504. >
  3505. <option value="">{t('archives.log.allUsers')}</option>
  3506. {users?.map((u) => (
  3507. <option key={u.id} value={u.username}>{u.username}</option>
  3508. ))}
  3509. </select>
  3510. {/* Status filter */}
  3511. <select
  3512. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  3513. value={logFilterStatus || ''}
  3514. onChange={(e) => { setLogFilterStatus(e.target.value || null); setLogOffset(0); }}
  3515. >
  3516. <option value="">{t('archives.log.allStatuses')}</option>
  3517. <option value="completed">{t('archives.status.completed')}</option>
  3518. <option value="failed">{t('archives.status.failed')}</option>
  3519. <option value="stopped">{t('archives.status.stopped')}</option>
  3520. <option value="cancelled">{t('archives.log.cancelled')}</option>
  3521. <option value="skipped">{t('archives.log.skipped')}</option>
  3522. </select>
  3523. {/* Date range */}
  3524. <div className="flex items-center gap-2">
  3525. <label className="text-sm text-bambu-gray">{t('archives.log.dateFrom')}</label>
  3526. <input
  3527. type="date"
  3528. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  3529. value={logFilterDateFrom}
  3530. onChange={(e) => { setLogFilterDateFrom(e.target.value); setLogOffset(0); }}
  3531. />
  3532. </div>
  3533. <div className="flex items-center gap-2">
  3534. <label className="text-sm text-bambu-gray">{t('archives.log.dateTo')}</label>
  3535. <input
  3536. type="date"
  3537. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm"
  3538. value={logFilterDateTo}
  3539. onChange={(e) => { setLogFilterDateTo(e.target.value); setLogOffset(0); }}
  3540. />
  3541. </div>
  3542. {/* Clear log button */}
  3543. <div className="ml-auto">
  3544. <Button
  3545. variant="danger"
  3546. size="sm"
  3547. onClick={() => setShowClearLogConfirm(true)}
  3548. disabled={!hasPermission('archives:delete_all') || clearLogMutation.isPending}
  3549. >
  3550. <Trash2 className="w-4 h-4" />
  3551. {t('archives.log.clearLog')}
  3552. </Button>
  3553. </div>
  3554. </div>
  3555. </CardContent>
  3556. </Card>
  3557. {/* Log table */}
  3558. <Card>
  3559. {isLogLoading ? (
  3560. <div className="flex items-center justify-center py-12">
  3561. <Loader2 className="w-6 h-6 animate-spin text-bambu-green" />
  3562. </div>
  3563. ) : !printLogData?.items.length ? (
  3564. <div className="text-center py-12 text-bambu-gray">
  3565. {t('archives.log.noEntries')}
  3566. </div>
  3567. ) : (
  3568. <>
  3569. <div className="overflow-x-auto">
  3570. <table className="w-full text-sm">
  3571. <thead>
  3572. <tr className="border-b border-bambu-dark-tertiary text-bambu-gray text-left">
  3573. <th className="px-4 py-3 font-medium">{t('archives.log.date')}</th>
  3574. <th className="px-4 py-3 font-medium">{t('archives.log.printName')}</th>
  3575. <th className="px-4 py-3 font-medium">{t('archives.log.printer')}</th>
  3576. <th className="px-4 py-3 font-medium">{t('archives.log.user')}</th>
  3577. <th className="px-4 py-3 font-medium">{t('archives.log.status')}</th>
  3578. <th className="px-4 py-3 font-medium">{t('archives.log.duration')}</th>
  3579. <th className="px-4 py-3 font-medium">{t('archives.log.filament')}</th>
  3580. </tr>
  3581. </thead>
  3582. <tbody className="divide-y divide-bambu-dark-tertiary">
  3583. {printLogData.items.map((entry) => (
  3584. <tr key={entry.id} className="hover:bg-bambu-dark-secondary/50">
  3585. <td className="px-4 py-3 text-white whitespace-nowrap">
  3586. {formatDateTime(entry.started_at || entry.created_at, timeFormat)}
  3587. </td>
  3588. <td className="px-4 py-3">
  3589. <div className="flex items-center gap-2">
  3590. {entry.thumbnail_path && (
  3591. <img
  3592. src={api.getPrintLogThumbnail(entry.id)}
  3593. alt=""
  3594. className="w-8 h-8 rounded object-cover flex-shrink-0"
  3595. onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
  3596. />
  3597. )}
  3598. <span className="text-white truncate max-w-[200px]">
  3599. {entry.print_name || '—'}
  3600. </span>
  3601. </div>
  3602. </td>
  3603. <td className="px-4 py-3 text-bambu-gray-light">{entry.printer_name || '—'}</td>
  3604. <td className="px-4 py-3 text-bambu-gray-light">{entry.created_by_username || '—'}</td>
  3605. <td className="px-4 py-3">
  3606. <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
  3607. entry.status === 'completed' ? 'bg-green-500/20 text-green-400' :
  3608. entry.status === 'failed' ? 'bg-red-500/20 text-red-400' :
  3609. entry.status === 'stopped' ? 'bg-yellow-500/20 text-yellow-400' :
  3610. entry.status === 'cancelled' ? 'bg-orange-500/20 text-orange-400' :
  3611. entry.status === 'skipped' ? 'bg-blue-500/20 text-blue-400' :
  3612. 'bg-gray-500/20 text-gray-400'
  3613. }`}>
  3614. {entry.status}
  3615. </span>
  3616. </td>
  3617. <td className="px-4 py-3 text-bambu-gray-light whitespace-nowrap">
  3618. {entry.duration_seconds ? formatDuration(entry.duration_seconds) : '—'}
  3619. </td>
  3620. <td className="px-4 py-3">
  3621. <div className="flex items-center gap-1.5">
  3622. {entry.filament_color && (
  3623. <span
  3624. className="w-3 h-3 rounded-full border border-black/20 flex-shrink-0"
  3625. style={{ backgroundColor: entry.filament_color.startsWith('#') ? entry.filament_color : undefined }}
  3626. />
  3627. )}
  3628. <span className="text-bambu-gray-light text-xs">
  3629. {entry.filament_type || '—'}
  3630. </span>
  3631. </div>
  3632. </td>
  3633. </tr>
  3634. ))}
  3635. </tbody>
  3636. </table>
  3637. </div>
  3638. {/* Pagination */}
  3639. <div className="flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2">
  3640. <div className="flex items-center gap-3">
  3641. <span className="text-sm text-bambu-gray">
  3642. {t('archives.log.showing', { count: Math.min(logOffset + logPageSize, printLogData.total), total: printLogData.total })}
  3643. </span>
  3644. <div className="flex items-center gap-1.5">
  3645. <label className="text-xs text-bambu-gray">{t('archives.log.rowsPerPage')}</label>
  3646. <select
  3647. className="px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none"
  3648. value={logPageSize}
  3649. onChange={(e) => { setLogPageSize(Number(e.target.value)); setLogOffset(0); }}
  3650. >
  3651. <option value={10}>10</option>
  3652. <option value={25}>25</option>
  3653. <option value={50}>50</option>
  3654. <option value={100}>100</option>
  3655. </select>
  3656. </div>
  3657. </div>
  3658. <div className="flex items-center gap-2">
  3659. <span className="text-sm text-bambu-gray">
  3660. {t('archives.log.page')} {Math.floor(logOffset / logPageSize) + 1} / {Math.max(1, Math.ceil(printLogData.total / logPageSize))}
  3661. </span>
  3662. <Button variant="secondary" size="sm" onClick={() => setLogOffset(Math.max(0, logOffset - logPageSize))} disabled={logOffset === 0}>
  3663. <ChevronLeft className="w-4 h-4" />
  3664. </Button>
  3665. <Button variant="secondary" size="sm" onClick={() => setLogOffset(logOffset + logPageSize)} disabled={logOffset + logPageSize >= printLogData.total}>
  3666. <ChevronRight className="w-4 h-4" />
  3667. </Button>
  3668. </div>
  3669. </div>
  3670. </>
  3671. )}
  3672. </Card>
  3673. </div>
  3674. ) : null}
  3675. {/* Upload Modal */}
  3676. {showUpload && (
  3677. <UploadModal
  3678. onClose={() => {
  3679. setShowUpload(false);
  3680. setUploadFiles([]);
  3681. }}
  3682. initialFiles={uploadFiles}
  3683. />
  3684. )}
  3685. {/* Archive bulk-purge modal (#1008 follow-up) */}
  3686. {showPurgeModal && (
  3687. <PurgeArchivesModal onClose={() => setShowPurgeModal(false)} />
  3688. )}
  3689. {/* Bulk Delete Confirmation */}
  3690. {showBulkDeleteConfirm && (
  3691. <ConfirmModal
  3692. title={t('archives.modal.deleteArchives')}
  3693. message={t('archives.modal.deleteArchivesConfirm', { count: selectedIds.size })}
  3694. confirmText={t('archives.modal.deleteCount', { count: selectedIds.size })}
  3695. variant="danger"
  3696. onConfirm={() => {
  3697. bulkDeleteMutation.mutate(Array.from(selectedIds));
  3698. setShowBulkDeleteConfirm(false);
  3699. }}
  3700. onCancel={() => setShowBulkDeleteConfirm(false)}
  3701. />
  3702. )}
  3703. {/* Batch Tag Modal */}
  3704. {showBatchTag && (
  3705. <BatchTagModal
  3706. selectedIds={Array.from(selectedIds)}
  3707. existingTags={uniqueTags}
  3708. onClose={() => setShowBatchTag(false)}
  3709. />
  3710. )}
  3711. {/* Batch Project Modal */}
  3712. {showBatchProject && (
  3713. <BatchProjectModal
  3714. selectedIds={Array.from(selectedIds)}
  3715. onClose={() => setShowBatchProject(false)}
  3716. />
  3717. )}
  3718. {/* Compare Archives Modal */}
  3719. {showCompareModal && selectedIds.size >= 2 && selectedIds.size <= 5 && (
  3720. <CompareArchivesModal
  3721. archiveIds={Array.from(selectedIds)}
  3722. onClose={() => {
  3723. setShowCompareModal(false);
  3724. setSelectedIds(new Set());
  3725. setIsSelectionMode(false);
  3726. }}
  3727. />
  3728. )}
  3729. {/* Tag Management Modal */}
  3730. {showTagManagement && (
  3731. <TagManagementModal onClose={() => setShowTagManagement(false)} />
  3732. )}
  3733. {/* Clear Log Confirmation */}
  3734. {showClearLogConfirm && (
  3735. <ConfirmModal
  3736. title={t('archives.log.clearLogTitle')}
  3737. message={t('archives.log.clearLogConfirm')}
  3738. confirmText={t('archives.log.clearLogButton')}
  3739. variant="danger"
  3740. onConfirm={() => {
  3741. clearLogMutation.mutate();
  3742. setShowClearLogConfirm(false);
  3743. }}
  3744. onCancel={() => setShowClearLogConfirm(false)}
  3745. />
  3746. )}
  3747. </div>
  3748. );
  3749. }
  3750. /* Pagination bar for archives grid/list views */
  3751. function ArchivePaginationBar({
  3752. pageIndex, pageSize, totalRows, totalPages, onPageChange, onPageSizeChange, t,
  3753. }: {
  3754. pageIndex: number;
  3755. pageSize: number;
  3756. totalRows: number;
  3757. totalPages: number;
  3758. onPageChange: (page: number) => void;
  3759. onPageSizeChange: (size: number) => void;
  3760. t: (key: string) => string;
  3761. }) {
  3762. const isShowAll = pageSize === -1;
  3763. if (totalPages <= 1 && !isShowAll) return null;
  3764. const effectiveSize = isShowAll ? totalRows || 1 : pageSize;
  3765. return (
  3766. <div className="flex items-center justify-between pt-2 text-sm">
  3767. <span className="text-bambu-gray">
  3768. {isShowAll
  3769. ? `${totalRows} ${t('archives.prints')}`
  3770. : <>{t('archives.pagination.showing')} {pageIndex * effectiveSize + 1} {t('archives.pagination.to')}{' '}
  3771. {Math.min((pageIndex + 1) * effectiveSize, totalRows)}{' '}
  3772. {t('archives.pagination.of')} {totalRows} {t('archives.prints')}</>
  3773. }
  3774. </span>
  3775. <div className="flex items-center gap-2">
  3776. <span className="text-bambu-gray">{t('archives.pagination.show')}</span>
  3777. <select
  3778. value={pageSize}
  3779. onChange={(e) => onPageSizeChange(Number(e.target.value))}
  3780. 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"
  3781. >
  3782. {[25, 50, 100, 200].map((n) => (
  3783. <option key={n} value={n}>{n}</option>
  3784. ))}
  3785. <option value={-1}>{t('archives.pagination.all')}</option>
  3786. </select>
  3787. {!isShowAll && (
  3788. <>
  3789. <button
  3790. onClick={() => onPageChange(0)}
  3791. disabled={pageIndex === 0}
  3792. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  3793. >
  3794. <ChevronsLeft className="w-4 h-4" />
  3795. </button>
  3796. <button
  3797. onClick={() => onPageChange(Math.max(0, pageIndex - 1))}
  3798. disabled={pageIndex === 0}
  3799. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  3800. >
  3801. <ChevronLeft className="w-4 h-4" />
  3802. </button>
  3803. <span className="text-bambu-gray px-2 whitespace-nowrap">
  3804. {t('archives.pagination.page')} {pageIndex + 1} {t('archives.pagination.of')} {totalPages}
  3805. </span>
  3806. <button
  3807. onClick={() => onPageChange(Math.min(totalPages - 1, pageIndex + 1))}
  3808. disabled={pageIndex >= totalPages - 1}
  3809. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  3810. >
  3811. <ChevronRight className="w-4 h-4" />
  3812. </button>
  3813. <button
  3814. onClick={() => onPageChange(totalPages - 1)}
  3815. disabled={pageIndex >= totalPages - 1}
  3816. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  3817. >
  3818. <ChevronsRight className="w-4 h-4" />
  3819. </button>
  3820. </>
  3821. )}
  3822. </div>
  3823. </div>
  3824. );
  3825. }