ArchivesPage.tsx 210 KB

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