ArchivesPage.tsx 198 KB

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