ArchivesPage.tsx 222 KB

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