ArchivesPage.tsx 209 KB

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