ArchivesPage.tsx 209 KB

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