ArchivesPage.tsx 206 KB

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