ArchivesPage.tsx 178 KB

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