ArchivesPage.tsx 178 KB

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