ArchivesPage.tsx 178 KB

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