ArchivesPage.tsx 176 KB

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