ArchivesPage.tsx 205 KB

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