ArchivesPage.tsx 160 KB

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