ArchivesPage.tsx 180 KB

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