ArchivesPage.tsx 207 KB

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