ArchivesPage.tsx 158 KB

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