ArchivesPage.tsx 219 KB

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