ArchivesPage.tsx 197 KB

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