ArchivesPage.tsx 219 KB

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