ArchivesPage.tsx 174 KB

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