client.ts 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808
  1. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  2. const API_BASE = '/api/v1';
  3. // Auth token storage
  4. let authToken: string | null = localStorage.getItem('auth_token');
  5. export function setAuthToken(token: string | null) {
  6. authToken = token;
  7. if (token) {
  8. localStorage.setItem('auth_token', token);
  9. } else {
  10. localStorage.removeItem('auth_token');
  11. }
  12. }
  13. export function getAuthToken(): string | null {
  14. return authToken;
  15. }
  16. function parseContentDispositionFilename(header: string | null): string | null {
  17. if (!header) return null;
  18. // RFC 5987: filename*=utf-8''percent-encoded-name
  19. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  20. if (rfc5987Match) {
  21. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  22. }
  23. // Standard: filename="name" or filename=name
  24. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  25. return standardMatch?.[1] || null;
  26. }
  27. async function request<T>(
  28. endpoint: string,
  29. options: RequestInit = {}
  30. ): Promise<T> {
  31. const headers: Record<string, string> = {
  32. 'Content-Type': 'application/json',
  33. ...options.headers as Record<string, string>,
  34. };
  35. // Add auth token if available
  36. if (authToken) {
  37. headers['Authorization'] = `Bearer ${authToken}`;
  38. }
  39. const response = await fetch(`${API_BASE}${endpoint}`, {
  40. ...options,
  41. cache: 'no-store', // Prevent browser caching of API responses
  42. headers,
  43. });
  44. if (!response.ok) {
  45. const error = await response.json().catch(() => ({}));
  46. const detail = error.detail;
  47. const message = typeof detail === 'string'
  48. ? detail
  49. : (detail ? JSON.stringify(detail) : `HTTP ${response.status}`);
  50. // Handle 401 Unauthorized - only clear token if it's actually invalid
  51. // Don't clear on "Authentication required" which might be a timing issue
  52. if (response.status === 401) {
  53. const invalidTokenMessages = [
  54. 'Could not validate credentials',
  55. 'Token has expired',
  56. 'User not found or inactive',
  57. 'Invalid API key',
  58. 'API key has expired',
  59. ];
  60. if (invalidTokenMessages.some(m => message.includes(m))) {
  61. setAuthToken(null);
  62. }
  63. }
  64. throw new Error(message);
  65. }
  66. // Handle empty responses (204 No Content, etc.)
  67. const contentLength = response.headers.get('content-length');
  68. if (response.status === 204 || contentLength === '0') {
  69. return undefined as T;
  70. }
  71. return await response.json();
  72. }
  73. // Printer types
  74. export interface Printer {
  75. id: number;
  76. name: string;
  77. serial_number: string;
  78. ip_address: string;
  79. access_code: string;
  80. model: string | null;
  81. location: string | null; // Group/location name
  82. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  83. is_active: boolean;
  84. auto_archive: boolean;
  85. external_camera_url: string | null;
  86. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  87. external_camera_enabled: boolean;
  88. plate_detection_enabled: boolean; // Check plate before print
  89. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  90. created_at: string;
  91. updated_at: string;
  92. }
  93. export interface HMSError {
  94. code: string;
  95. attr: number; // Attribute value for constructing wiki URL
  96. module: number;
  97. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  98. }
  99. export interface AMSTray {
  100. id: number;
  101. tray_color: string | null;
  102. tray_type: string | null;
  103. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  104. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  105. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  106. remain: number;
  107. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  108. cali_idx: number | null; // Calibration index for K-profile lookup
  109. tag_uid: string | null; // RFID tag UID (any tag)
  110. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  111. nozzle_temp_min: number | null; // Min nozzle temperature
  112. nozzle_temp_max: number | null; // Max nozzle temperature
  113. }
  114. export interface AMSUnit {
  115. id: number;
  116. humidity: number | null;
  117. temp: number | null;
  118. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  119. tray: AMSTray[];
  120. }
  121. export interface NozzleInfo {
  122. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  123. nozzle_diameter: string; // e.g., "0.4"
  124. }
  125. export interface NozzleRackSlot {
  126. id: number;
  127. nozzle_type: string;
  128. nozzle_diameter: string;
  129. wear: number | null;
  130. stat: number | null; // Nozzle status (e.g. mounted/docked)
  131. max_temp: number;
  132. serial_number: string;
  133. filament_color: string; // RGBA hex ("00000000" = no filament)
  134. filament_id: string;
  135. filament_type: string; // Material type (e.g. "PLA", "PETG")
  136. }
  137. export interface PrintOptions {
  138. // Core AI detectors
  139. spaghetti_detector: boolean;
  140. print_halt: boolean;
  141. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  142. first_layer_inspector: boolean;
  143. printing_monitor: boolean;
  144. buildplate_marker_detector: boolean;
  145. allow_skip_parts: boolean;
  146. // Additional AI detectors (decoded from cfg bitmask)
  147. nozzle_clumping_detector: boolean;
  148. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  149. pileup_detector: boolean;
  150. pileup_sensitivity: string; // "low", "medium", "high"
  151. airprint_detector: boolean;
  152. airprint_sensitivity: string; // "low", "medium", "high"
  153. auto_recovery_step_loss: boolean;
  154. filament_tangle_detect: boolean;
  155. }
  156. export interface PrinterStatus {
  157. id: number;
  158. name: string;
  159. connected: boolean;
  160. state: string | null;
  161. current_print: string | null;
  162. subtask_name: string | null;
  163. gcode_file: string | null;
  164. progress: number | null;
  165. remaining_time: number | null;
  166. layer_num: number | null;
  167. total_layers: number | null;
  168. temperatures: {
  169. bed?: number;
  170. bed_target?: number;
  171. bed_heating?: boolean; // Actual heater state from MQTT
  172. nozzle?: number;
  173. nozzle_target?: number;
  174. nozzle_heating?: boolean; // Actual heater state from MQTT
  175. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  176. nozzle_2_target?: number;
  177. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  178. chamber?: number;
  179. chamber_target?: number;
  180. chamber_heating?: boolean; // Actual heater state from MQTT
  181. } | null;
  182. cover_url: string | null;
  183. hms_errors: HMSError[];
  184. ams: AMSUnit[];
  185. ams_exists: boolean;
  186. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  187. sdcard: boolean; // SD card inserted
  188. store_to_sdcard: boolean; // Store sent files on SD card
  189. timelapse: boolean; // Timelapse recording active
  190. ipcam: boolean; // Live view enabled
  191. wifi_signal: number | null; // WiFi signal strength in dBm
  192. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  193. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  194. print_options: PrintOptions | null; // AI detection and print options
  195. // Calibration stage tracking
  196. stg_cur: number; // Current stage number (-1 = not calibrating)
  197. stg_cur_name: string | null; // Human-readable current stage name
  198. stg: number[]; // List of stage numbers in calibration sequence
  199. // Air conditioning mode (0=cooling, 1=heating)
  200. airduct_mode: number;
  201. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  202. speed_level: number;
  203. // Chamber light on/off
  204. chamber_light: boolean;
  205. // Active extruder for dual nozzle (0=right, 1=left)
  206. active_extruder: number;
  207. // AMS mapping - which AMS is connected to which nozzle
  208. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  209. ams_mapping: number[];
  210. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  211. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  212. // Note: JSON keys are always strings
  213. ams_extruder_map: Record<string, number>;
  214. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  215. tray_now: number;
  216. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  217. ams_status_main: number;
  218. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  219. ams_status_sub: number;
  220. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  221. mc_print_sub_stage: number;
  222. // Timestamp of last AMS data update (for RFID refresh detection)
  223. last_ams_update: number;
  224. // Number of printable objects in current print (for skip objects feature)
  225. printable_objects_count: number;
  226. // Fan speeds (0-100 percentage, null if not available for this model)
  227. cooling_fan_speed: number | null; // Part cooling fan
  228. big_fan1_speed: number | null; // Auxiliary fan
  229. big_fan2_speed: number | null; // Chamber/exhaust fan
  230. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  231. firmware_version: string | null; // Firmware version from MQTT
  232. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  233. developer_mode: boolean | null;
  234. // Queue: user has acknowledged plate is cleared for next queued print
  235. plate_cleared: boolean;
  236. }
  237. export interface PrinterCreate {
  238. name: string;
  239. serial_number: string;
  240. ip_address: string;
  241. access_code: string;
  242. model?: string;
  243. location?: string;
  244. auto_archive?: boolean;
  245. external_camera_url?: string | null;
  246. external_camera_type?: string | null;
  247. external_camera_enabled?: boolean;
  248. plate_detection_enabled?: boolean;
  249. plate_detection_roi?: PlateDetectionROI;
  250. }
  251. // Plate Detection
  252. export interface PlateDetectionROI {
  253. x: number; // X start % (0.0-1.0)
  254. y: number; // Y start % (0.0-1.0)
  255. w: number; // Width % (0.0-1.0)
  256. h: number; // Height % (0.0-1.0)
  257. }
  258. export interface PlateDetectionResult {
  259. is_empty: boolean;
  260. confidence: number;
  261. difference_percent: number;
  262. message: string;
  263. has_debug_image: boolean;
  264. debug_image_url?: string;
  265. needs_calibration: boolean;
  266. light_warning?: boolean;
  267. reference_count?: number;
  268. max_references?: number;
  269. roi?: PlateDetectionROI;
  270. }
  271. export interface PlateDetectionStatus {
  272. available: boolean;
  273. calibrated: boolean;
  274. reference_count: number;
  275. max_references: number;
  276. message: string;
  277. }
  278. export interface CalibrationResult {
  279. success: boolean;
  280. message: string;
  281. }
  282. export interface PlateReference {
  283. index: number;
  284. label: string;
  285. timestamp: string;
  286. has_image: boolean;
  287. thumbnail_url: string;
  288. }
  289. // Archive types
  290. export interface ArchiveDuplicate {
  291. id: number;
  292. print_name: string | null;
  293. created_at: string;
  294. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  295. }
  296. export interface Archive {
  297. id: number;
  298. printer_id: number | null;
  299. project_id: number | null;
  300. project_name: string | null;
  301. filename: string;
  302. file_path: string;
  303. file_size: number;
  304. content_hash: string | null;
  305. thumbnail_path: string | null;
  306. timelapse_path: string | null;
  307. source_3mf_path: string | null;
  308. f3d_path: string | null;
  309. duplicates: ArchiveDuplicate[] | null;
  310. duplicate_count: number;
  311. object_count: number | null;
  312. print_name: string | null;
  313. print_time_seconds: number | null;
  314. actual_time_seconds: number | null; // Computed from started_at/completed_at
  315. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  316. filament_used_grams: number | null;
  317. filament_type: string | null;
  318. filament_color: string | null;
  319. layer_height: number | null;
  320. total_layers: number | null;
  321. nozzle_diameter: number | null;
  322. bed_temperature: number | null;
  323. nozzle_temperature: number | null;
  324. sliced_for_model: string | null; // Printer model this file was sliced for
  325. status: string;
  326. started_at: string | null;
  327. completed_at: string | null;
  328. extra_data: Record<string, unknown> | null;
  329. makerworld_url: string | null;
  330. designer: string | null;
  331. external_url: string | null;
  332. is_favorite: boolean;
  333. tags: string | null;
  334. notes: string | null;
  335. cost: number | null;
  336. photos: string[] | null;
  337. failure_reason: string | null;
  338. quantity: number;
  339. energy_kwh: number | null;
  340. energy_cost: number | null;
  341. created_at: string;
  342. // User tracking (Issue #206)
  343. created_by_id: number | null;
  344. created_by_username: string | null;
  345. }
  346. export interface PrintLogEntry {
  347. id: number;
  348. print_name: string | null;
  349. printer_name: string | null;
  350. printer_id: number | null;
  351. status: string;
  352. started_at: string | null;
  353. completed_at: string | null;
  354. duration_seconds: number | null;
  355. filament_type: string | null;
  356. filament_color: string | null;
  357. filament_used_grams: number | null;
  358. thumbnail_path: string | null;
  359. created_by_username: string | null;
  360. created_at: string;
  361. }
  362. export interface PrintLogResponse {
  363. items: PrintLogEntry[];
  364. total: number;
  365. }
  366. export interface ArchiveStats {
  367. total_prints: number;
  368. successful_prints: number;
  369. failed_prints: number;
  370. total_print_time_hours: number;
  371. total_filament_grams: number;
  372. total_cost: number;
  373. prints_by_filament_type: Record<string, number>;
  374. prints_by_printer: Record<string, number>;
  375. average_time_accuracy: number | null;
  376. time_accuracy_by_printer: Record<string, number> | null;
  377. total_energy_kwh: number;
  378. total_energy_cost: number;
  379. }
  380. export interface TagInfo {
  381. name: string;
  382. count: number;
  383. }
  384. export interface FailureAnalysis {
  385. period_days: number;
  386. total_prints: number;
  387. failed_prints: number;
  388. failure_rate: number;
  389. failures_by_reason: Record<string, number>;
  390. failures_by_filament: Record<string, number>;
  391. failures_by_printer: Record<string, number>;
  392. failures_by_hour: Record<number, number>;
  393. recent_failures: Array<{
  394. id: number;
  395. print_name: string;
  396. failure_reason: string | null;
  397. filament_type: string | null;
  398. printer_id: number | null;
  399. created_at: string | null;
  400. }>;
  401. trend: Array<{
  402. week_start: string;
  403. total_prints: number;
  404. failed_prints: number;
  405. failure_rate: number;
  406. }>;
  407. }
  408. export interface BulkUploadResult {
  409. uploaded: number;
  410. failed: number;
  411. results: Array<{ filename: string; id: number; status: string }>;
  412. errors: Array<{ filename: string; error: string }>;
  413. }
  414. // Archive Comparison types
  415. export interface ComparisonArchiveInfo {
  416. id: number;
  417. print_name: string;
  418. status: string;
  419. created_at: string | null;
  420. printer_id: number | null;
  421. project_name: string | null;
  422. }
  423. export interface ComparisonField {
  424. field: string;
  425. label: string;
  426. unit: string | null;
  427. values: (string | number | null)[];
  428. raw_values: (string | number | null)[];
  429. has_difference: boolean;
  430. }
  431. export interface SuccessCorrelationInsight {
  432. field: string;
  433. label: string;
  434. insight: string;
  435. success_avg?: number;
  436. failed_avg?: number;
  437. success_values?: string[];
  438. failed_values?: string[];
  439. }
  440. export interface SuccessCorrelation {
  441. has_both_outcomes: boolean;
  442. message?: string;
  443. successful_count?: number;
  444. failed_count?: number;
  445. insights?: SuccessCorrelationInsight[];
  446. }
  447. export interface ArchiveComparison {
  448. archives: ComparisonArchiveInfo[];
  449. comparison: ComparisonField[];
  450. differences: ComparisonField[];
  451. success_correlation: SuccessCorrelation;
  452. }
  453. export interface SimilarArchive {
  454. archive: {
  455. id: number;
  456. print_name: string;
  457. status: string;
  458. created_at: string | null;
  459. };
  460. match_reason: string;
  461. match_score: number;
  462. }
  463. // Project types
  464. export interface ProjectStats {
  465. total_archives: number;
  466. total_items: number; // Sum of quantities (total items printed)
  467. completed_prints: number; // Sum of quantities for completed prints (parts)
  468. failed_prints: number;
  469. queued_prints: number;
  470. in_progress_prints: number;
  471. total_print_time_hours: number;
  472. total_filament_grams: number;
  473. progress_percent: number | null; // Plates progress (total_archives / target_count)
  474. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  475. estimated_cost: number;
  476. total_energy_kwh: number;
  477. total_energy_cost: number;
  478. remaining_prints: number | null; // Remaining plates
  479. remaining_parts: number | null; // Remaining parts
  480. bom_total_items: number;
  481. bom_completed_items: number;
  482. }
  483. export interface ProjectChildPreview {
  484. id: number;
  485. name: string;
  486. color: string | null;
  487. status: string;
  488. progress_percent: number | null;
  489. }
  490. export interface Project {
  491. id: number;
  492. name: string;
  493. description: string | null;
  494. color: string | null;
  495. status: string; // active, completed, archived
  496. target_count: number | null; // Target number of plates/print jobs
  497. target_parts_count: number | null; // Target number of parts/objects
  498. notes: string | null;
  499. attachments: ProjectAttachment[] | null;
  500. tags: string | null;
  501. due_date: string | null;
  502. priority: string; // low, normal, high, urgent
  503. budget: number | null;
  504. is_template: boolean;
  505. template_source_id: number | null;
  506. parent_id: number | null;
  507. parent_name: string | null;
  508. children: ProjectChildPreview[];
  509. created_at: string;
  510. updated_at: string;
  511. stats?: ProjectStats;
  512. }
  513. export interface ProjectAttachment {
  514. filename: string;
  515. original_name: string;
  516. size: number;
  517. uploaded_at: string;
  518. }
  519. export interface ArchivePreview {
  520. id: number;
  521. print_name: string | null;
  522. thumbnail_path: string | null;
  523. status: string;
  524. filament_type: string | null;
  525. filament_color: string | null;
  526. }
  527. export interface ProjectListItem {
  528. id: number;
  529. name: string;
  530. description: string | null;
  531. color: string | null;
  532. status: string;
  533. target_count: number | null; // Target number of plates/print jobs
  534. target_parts_count: number | null; // Target number of parts/objects
  535. created_at: string;
  536. archive_count: number; // Number of print jobs (plates)
  537. total_items: number; // Sum of quantities (total items printed, including failed)
  538. completed_count: number; // Sum of quantities for completed prints only (parts)
  539. failed_count: number; // Sum of quantities for failed prints
  540. queue_count: number;
  541. progress_percent: number | null; // Plates progress
  542. archives: ArchivePreview[];
  543. }
  544. export interface ProjectCreate {
  545. name: string;
  546. description?: string;
  547. color?: string;
  548. target_count?: number;
  549. target_parts_count?: number;
  550. notes?: string;
  551. tags?: string;
  552. due_date?: string;
  553. priority?: string;
  554. budget?: number;
  555. parent_id?: number;
  556. }
  557. export interface ProjectUpdate {
  558. name?: string;
  559. description?: string;
  560. color?: string;
  561. status?: string;
  562. target_count?: number;
  563. target_parts_count?: number;
  564. notes?: string;
  565. tags?: string;
  566. due_date?: string;
  567. priority?: string;
  568. budget?: number;
  569. parent_id?: number;
  570. }
  571. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  572. export interface BOMItem {
  573. id: number;
  574. project_id: number;
  575. name: string;
  576. quantity_needed: number;
  577. quantity_acquired: number;
  578. unit_price: number | null;
  579. sourcing_url: string | null;
  580. archive_id: number | null;
  581. archive_name: string | null;
  582. stl_filename: string | null;
  583. remarks: string | null;
  584. sort_order: number;
  585. is_complete: boolean;
  586. created_at: string;
  587. updated_at: string;
  588. }
  589. export interface BOMItemCreate {
  590. name: string;
  591. quantity_needed?: number;
  592. unit_price?: number;
  593. sourcing_url?: string;
  594. archive_id?: number;
  595. stl_filename?: string;
  596. remarks?: string;
  597. }
  598. export interface BOMItemUpdate {
  599. name?: string;
  600. quantity_needed?: number;
  601. quantity_acquired?: number;
  602. unit_price?: number;
  603. sourcing_url?: string;
  604. archive_id?: number;
  605. stl_filename?: string;
  606. remarks?: string;
  607. }
  608. // Project Export/Import Types
  609. export interface BOMItemExport {
  610. name: string;
  611. quantity_needed: number;
  612. quantity_acquired: number;
  613. unit_price: number | null;
  614. sourcing_url: string | null;
  615. stl_filename: string | null;
  616. remarks: string | null;
  617. }
  618. export interface LinkedFolderExport {
  619. name: string;
  620. }
  621. export interface ProjectExport {
  622. name: string;
  623. description: string | null;
  624. color: string | null;
  625. status: string;
  626. target_count: number | null;
  627. target_parts_count: number | null;
  628. notes: string | null;
  629. tags: string | null;
  630. due_date: string | null;
  631. priority: string;
  632. budget: number | null;
  633. bom_items: BOMItemExport[];
  634. linked_folders: LinkedFolderExport[];
  635. }
  636. export interface ProjectImport {
  637. name: string;
  638. description?: string;
  639. color?: string;
  640. status?: string;
  641. target_count?: number;
  642. target_parts_count?: number;
  643. notes?: string;
  644. tags?: string;
  645. due_date?: string;
  646. priority?: string;
  647. budget?: number;
  648. bom_items?: BOMItemExport[];
  649. linked_folders?: LinkedFolderExport[];
  650. }
  651. // Timeline Types
  652. export interface TimelineEvent {
  653. event_type: string;
  654. timestamp: string;
  655. title: string;
  656. description: string | null;
  657. metadata: Record<string, unknown> | null;
  658. }
  659. // API Key types
  660. export interface APIKey {
  661. id: number;
  662. name: string;
  663. key_prefix: string;
  664. can_queue: boolean;
  665. can_control_printer: boolean;
  666. can_read_status: boolean;
  667. printer_ids: number[] | null;
  668. enabled: boolean;
  669. last_used: string | null;
  670. created_at: string;
  671. expires_at: string | null;
  672. }
  673. export interface APIKeyCreate {
  674. name: string;
  675. can_queue?: boolean;
  676. can_control_printer?: boolean;
  677. can_read_status?: boolean;
  678. printer_ids?: number[] | null;
  679. expires_at?: string | null;
  680. }
  681. export interface APIKeyCreateResponse extends APIKey {
  682. key: string; // Full key, only shown on creation
  683. }
  684. export interface APIKeyUpdate {
  685. name?: string;
  686. can_queue?: boolean;
  687. can_control_printer?: boolean;
  688. can_read_status?: boolean;
  689. printer_ids?: number[] | null;
  690. enabled?: boolean;
  691. expires_at?: string | null;
  692. }
  693. // Settings types
  694. export interface AppSettings {
  695. auto_archive: boolean;
  696. save_thumbnails: boolean;
  697. capture_finish_photo: boolean;
  698. default_filament_cost: number;
  699. currency: string;
  700. energy_cost_per_kwh: number;
  701. energy_tracking_mode: 'print' | 'total';
  702. check_updates: boolean;
  703. check_printer_firmware: boolean;
  704. include_beta_updates: boolean;
  705. notification_language: string;
  706. // AMS threshold settings
  707. ams_humidity_good: number; // <= this is green
  708. ams_humidity_fair: number; // <= this is orange, > is red
  709. ams_temp_good: number; // <= this is green/blue
  710. ams_temp_fair: number; // <= this is orange, > is red
  711. ams_history_retention_days: number; // days to keep AMS sensor history
  712. // Print modal settings
  713. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  714. // Date/time format settings
  715. date_format: 'system' | 'us' | 'eu' | 'iso';
  716. time_format: 'system' | '12h' | '24h';
  717. // Default printer
  718. default_printer_id: number | null;
  719. // Dark mode theme settings
  720. dark_style: 'classic' | 'glow' | 'vibrant';
  721. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  722. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  723. // Light mode theme settings
  724. light_style: 'classic' | 'glow' | 'vibrant';
  725. light_background: 'neutral' | 'warm' | 'cool';
  726. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  727. // FTP retry settings
  728. ftp_retry_enabled: boolean;
  729. ftp_retry_count: number;
  730. ftp_retry_delay: number;
  731. ftp_timeout: number;
  732. // MQTT relay settings
  733. mqtt_enabled: boolean;
  734. mqtt_broker: string;
  735. mqtt_port: number;
  736. mqtt_username: string;
  737. mqtt_password: string;
  738. mqtt_topic_prefix: string;
  739. mqtt_use_tls: boolean;
  740. // External URL for notifications
  741. external_url: string;
  742. // Home Assistant integration
  743. ha_enabled: boolean;
  744. ha_url: string;
  745. ha_token: string;
  746. ha_url_from_env: boolean;
  747. ha_token_from_env: boolean;
  748. ha_env_managed: boolean;
  749. // File Manager / Library settings
  750. library_archive_mode: 'always' | 'never' | 'ask';
  751. library_disk_warning_gb: number;
  752. // Camera view settings
  753. camera_view_mode: 'window' | 'embedded';
  754. // Preferred slicer
  755. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  756. // Prometheus metrics
  757. prometheus_enabled: boolean;
  758. prometheus_token: string;
  759. // Bed cooled threshold
  760. bed_cooled_threshold: number;
  761. }
  762. export type AppSettingsUpdate = Partial<AppSettings>;
  763. // MQTT relay status
  764. export interface MQTTStatus {
  765. enabled: boolean;
  766. connected: boolean;
  767. broker: string;
  768. port: number;
  769. topic_prefix: string;
  770. }
  771. // Cloud types
  772. export interface CloudAuthStatus {
  773. is_authenticated: boolean;
  774. email: string | null;
  775. }
  776. export interface CloudLoginResponse {
  777. success: boolean;
  778. needs_verification: boolean;
  779. message: string;
  780. verification_type?: 'email' | 'totp' | null;
  781. tfa_key?: string | null;
  782. }
  783. export interface SlicerSetting {
  784. setting_id: string;
  785. name: string;
  786. type: string;
  787. version: string | null;
  788. user_id: string | null;
  789. updated_time: string | null;
  790. is_custom: boolean;
  791. }
  792. export interface SpoolCatalogEntry {
  793. id: number;
  794. name: string;
  795. weight: number;
  796. is_default: boolean;
  797. }
  798. export interface ColorCatalogEntry {
  799. id: number;
  800. manufacturer: string;
  801. color_name: string;
  802. hex_color: string;
  803. material: string | null;
  804. is_default: boolean;
  805. }
  806. export interface ColorLookupResult {
  807. found: boolean;
  808. hex_color: string | null;
  809. material: string | null;
  810. }
  811. export interface SlicerSettingsResponse {
  812. filament: SlicerSetting[];
  813. printer: SlicerSetting[];
  814. process: SlicerSetting[];
  815. }
  816. export interface SlicerSettingDetail {
  817. message?: string | null;
  818. code?: string | null;
  819. error?: string | null;
  820. public: boolean;
  821. version?: string | null;
  822. type: string;
  823. name: string;
  824. update_time?: string | null;
  825. nickname?: string | null;
  826. base_id?: string | null;
  827. setting: Record<string, unknown>;
  828. filament_id?: string | null;
  829. setting_id?: string | null;
  830. }
  831. export interface SlicerSettingCreate {
  832. type: string; // 'filament', 'print', or 'printer'
  833. name: string;
  834. base_id: string;
  835. setting: Record<string, unknown>;
  836. }
  837. export interface SlicerSettingUpdate {
  838. name?: string;
  839. setting?: Record<string, unknown>;
  840. }
  841. export interface SlicerSettingDeleteResponse {
  842. success: boolean;
  843. message: string;
  844. }
  845. // Built-in filament fallback (static table from backend)
  846. export interface BuiltinFilament {
  847. filament_id: string;
  848. name: string;
  849. }
  850. // Local preset types (OrcaSlicer imports)
  851. export interface LocalPreset {
  852. id: number;
  853. name: string;
  854. preset_type: string;
  855. source: string;
  856. filament_type: string | null;
  857. filament_vendor: string | null;
  858. nozzle_temp_min: number | null;
  859. nozzle_temp_max: number | null;
  860. pressure_advance: string | null;
  861. default_filament_colour: string | null;
  862. filament_cost: string | null;
  863. filament_density: string | null;
  864. compatible_printers: string | null;
  865. inherits: string | null;
  866. version: string | null;
  867. created_at: string;
  868. updated_at: string;
  869. }
  870. export interface LocalPresetDetail extends LocalPreset {
  871. setting: Record<string, unknown>;
  872. }
  873. export interface LocalPresetsResponse {
  874. filament: LocalPreset[];
  875. printer: LocalPreset[];
  876. process: LocalPreset[];
  877. }
  878. export interface ImportResponse {
  879. success: boolean;
  880. imported: number;
  881. skipped: number;
  882. errors: string[];
  883. }
  884. export interface FieldOption {
  885. value: string;
  886. label: string;
  887. }
  888. export interface FieldDefinition {
  889. key: string;
  890. label: string;
  891. type: 'text' | 'number' | 'boolean' | 'select';
  892. category: string;
  893. description?: string;
  894. options?: FieldOption[];
  895. unit?: string;
  896. min?: number;
  897. max?: number;
  898. step?: number;
  899. }
  900. export interface FieldDefinitionsResponse {
  901. version: string;
  902. description: string;
  903. fields: FieldDefinition[];
  904. }
  905. export interface CloudDevice {
  906. dev_id: string;
  907. name: string;
  908. dev_model_name: string | null;
  909. dev_product_name: string | null;
  910. online: boolean;
  911. }
  912. // Smart Plug types
  913. export interface SmartPlug {
  914. id: number;
  915. name: string;
  916. plug_type: 'tasmota' | 'homeassistant' | 'mqtt';
  917. ip_address: string | null; // Required for Tasmota
  918. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  919. // Home Assistant energy sensor entities (optional)
  920. ha_power_entity: string | null;
  921. ha_energy_today_entity: string | null;
  922. ha_energy_total_entity: string | null;
  923. // MQTT fields (required when plug_type="mqtt")
  924. // Legacy field - kept for backward compatibility
  925. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  926. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  927. // Power monitoring
  928. mqtt_power_topic: string | null; // Topic for power data
  929. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  930. mqtt_power_multiplier: number; // Unit conversion for power
  931. // Energy monitoring
  932. mqtt_energy_topic: string | null; // Topic for energy data
  933. mqtt_energy_path: string | null; // e.g., "energy_l1"
  934. mqtt_energy_multiplier: number; // Unit conversion for energy
  935. // State monitoring
  936. mqtt_state_topic: string | null; // Topic for state data
  937. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  938. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  939. printer_id: number | null;
  940. enabled: boolean;
  941. auto_on: boolean;
  942. auto_off: boolean;
  943. off_delay_mode: 'time' | 'temperature';
  944. off_delay_minutes: number;
  945. off_temp_threshold: number;
  946. username: string | null;
  947. password: string | null;
  948. // Power alerts
  949. power_alert_enabled: boolean;
  950. power_alert_high: number | null;
  951. power_alert_low: number | null;
  952. power_alert_last_triggered: string | null;
  953. // Schedule
  954. schedule_enabled: boolean;
  955. schedule_on_time: string | null;
  956. schedule_off_time: string | null;
  957. // Visibility options
  958. show_in_switchbar: boolean;
  959. show_on_printer_card: boolean; // For scripts: show on printer card
  960. // Status
  961. last_state: string | null;
  962. last_checked: string | null;
  963. auto_off_executed: boolean; // True when auto-off was triggered after print
  964. created_at: string;
  965. updated_at: string;
  966. }
  967. export interface SmartPlugCreate {
  968. name: string;
  969. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt';
  970. ip_address?: string | null; // Required for Tasmota
  971. ha_entity_id?: string | null; // Required for Home Assistant
  972. // Home Assistant energy sensor entities (optional)
  973. ha_power_entity?: string | null;
  974. ha_energy_today_entity?: string | null;
  975. ha_energy_total_entity?: string | null;
  976. // MQTT fields (required when plug_type="mqtt")
  977. // Legacy fields - kept for backward compatibility
  978. mqtt_topic?: string | null;
  979. mqtt_multiplier?: number;
  980. // Power monitoring
  981. mqtt_power_topic?: string | null;
  982. mqtt_power_path?: string | null;
  983. mqtt_power_multiplier?: number;
  984. // Energy monitoring
  985. mqtt_energy_topic?: string | null;
  986. mqtt_energy_path?: string | null;
  987. mqtt_energy_multiplier?: number;
  988. // State monitoring
  989. mqtt_state_topic?: string | null;
  990. mqtt_state_path?: string | null;
  991. mqtt_state_on_value?: string | null;
  992. printer_id?: number | null;
  993. enabled?: boolean;
  994. auto_on?: boolean;
  995. auto_off?: boolean;
  996. off_delay_mode?: 'time' | 'temperature';
  997. off_delay_minutes?: number;
  998. off_temp_threshold?: number;
  999. username?: string | null;
  1000. password?: string | null;
  1001. // Power alerts
  1002. power_alert_enabled?: boolean;
  1003. power_alert_high?: number | null;
  1004. power_alert_low?: number | null;
  1005. // Schedule
  1006. schedule_enabled?: boolean;
  1007. schedule_on_time?: string | null;
  1008. schedule_off_time?: string | null;
  1009. // Visibility options
  1010. show_in_switchbar?: boolean;
  1011. show_on_printer_card?: boolean;
  1012. }
  1013. export interface SmartPlugUpdate {
  1014. name?: string;
  1015. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt';
  1016. ip_address?: string | null;
  1017. ha_entity_id?: string | null;
  1018. // Home Assistant energy sensor entities (optional)
  1019. ha_power_entity?: string | null;
  1020. ha_energy_today_entity?: string | null;
  1021. ha_energy_total_entity?: string | null;
  1022. // MQTT fields (legacy)
  1023. mqtt_topic?: string | null;
  1024. mqtt_multiplier?: number;
  1025. // MQTT power fields
  1026. mqtt_power_topic?: string | null;
  1027. mqtt_power_path?: string | null;
  1028. mqtt_power_multiplier?: number;
  1029. // MQTT energy fields
  1030. mqtt_energy_topic?: string | null;
  1031. mqtt_energy_path?: string | null;
  1032. mqtt_energy_multiplier?: number;
  1033. // MQTT state fields
  1034. mqtt_state_topic?: string | null;
  1035. mqtt_state_path?: string | null;
  1036. mqtt_state_on_value?: string | null;
  1037. printer_id?: number | null;
  1038. enabled?: boolean;
  1039. auto_on?: boolean;
  1040. auto_off?: boolean;
  1041. off_delay_mode?: 'time' | 'temperature';
  1042. off_delay_minutes?: number;
  1043. off_temp_threshold?: number;
  1044. username?: string | null;
  1045. password?: string | null;
  1046. // Power alerts
  1047. power_alert_enabled?: boolean;
  1048. power_alert_high?: number | null;
  1049. power_alert_low?: number | null;
  1050. // Schedule
  1051. schedule_enabled?: boolean;
  1052. schedule_on_time?: string | null;
  1053. schedule_off_time?: string | null;
  1054. // Visibility options
  1055. show_in_switchbar?: boolean;
  1056. show_on_printer_card?: boolean;
  1057. }
  1058. // Home Assistant entity for smart plug selection
  1059. export interface HAEntity {
  1060. entity_id: string;
  1061. friendly_name: string;
  1062. state: string | null;
  1063. domain: string; // "switch", "light", "input_boolean", "script"
  1064. }
  1065. // Home Assistant sensor entity for energy monitoring
  1066. export interface HASensorEntity {
  1067. entity_id: string;
  1068. friendly_name: string;
  1069. state: string | null;
  1070. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  1071. }
  1072. export interface HATestConnectionResult {
  1073. success: boolean;
  1074. message: string | null;
  1075. error: string | null;
  1076. }
  1077. export interface SmartPlugEnergy {
  1078. power: number | null; // Current watts
  1079. voltage: number | null; // Volts
  1080. current: number | null; // Amps
  1081. today: number | null; // kWh used today
  1082. yesterday: number | null; // kWh used yesterday
  1083. total: number | null; // Total kWh
  1084. factor: number | null; // Power factor (0-1)
  1085. apparent_power: number | null; // VA
  1086. reactive_power: number | null; // VAr
  1087. }
  1088. export interface SmartPlugStatus {
  1089. state: string | null;
  1090. reachable: boolean;
  1091. device_name: string | null;
  1092. energy: SmartPlugEnergy | null;
  1093. }
  1094. export interface SmartPlugTestResult {
  1095. success: boolean;
  1096. state: string | null;
  1097. device_name: string | null;
  1098. }
  1099. // Tasmota Discovery types
  1100. export interface TasmotaScanStatus {
  1101. running: boolean;
  1102. scanned: number;
  1103. total: number;
  1104. }
  1105. export interface DiscoveredTasmotaDevice {
  1106. ip_address: string;
  1107. name: string;
  1108. module: number | null;
  1109. state: string | null;
  1110. discovered_at: string | null;
  1111. }
  1112. // Print Queue types
  1113. export interface PrintQueueItem {
  1114. id: number;
  1115. printer_id: number | null; // null = unassigned
  1116. target_model: string | null; // Target printer model for model-based assignment
  1117. target_location: string | null; // Target location filter for model-based assignment
  1118. required_filament_types: string[] | null; // Required filament types for model-based assignment
  1119. waiting_reason: string | null; // Why a model-based job hasn't started yet
  1120. // Either archive_id OR library_file_id must be set (archive created at print start)
  1121. archive_id: number | null;
  1122. library_file_id: number | null;
  1123. position: number;
  1124. scheduled_time: string | null;
  1125. require_previous_success: boolean;
  1126. auto_off_after: boolean;
  1127. manual_start: boolean; // Requires manual trigger to start (staged)
  1128. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  1129. filament_overrides: Array<{ slot_id: number; type: string; color: string }> | null; // Filament overrides for model-based assignment
  1130. plate_id: number | null; // Plate ID for multi-plate 3MF files
  1131. // Print options
  1132. bed_levelling: boolean;
  1133. flow_cali: boolean;
  1134. vibration_cali: boolean;
  1135. layer_inspect: boolean;
  1136. timelapse: boolean;
  1137. use_ams: boolean;
  1138. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  1139. started_at: string | null;
  1140. completed_at: string | null;
  1141. error_message: string | null;
  1142. created_at: string;
  1143. archive_name?: string | null;
  1144. archive_thumbnail?: string | null;
  1145. library_file_name?: string | null;
  1146. library_file_thumbnail?: string | null;
  1147. printer_name?: string | null;
  1148. print_time_seconds?: number | null; // Estimated print time from archive or library file
  1149. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  1150. // User tracking (Issue #206)
  1151. created_by_id?: number | null;
  1152. created_by_username?: string | null;
  1153. }
  1154. export interface PrintQueueItemCreate {
  1155. printer_id?: number | null; // null = unassigned
  1156. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1157. target_location?: string | null; // Target location filter (only used with target_model)
  1158. filament_overrides?: Array<{ slot_id: number; type: string; color: string }> | null;
  1159. // Either archive_id OR library_file_id must be provided
  1160. archive_id?: number | null;
  1161. library_file_id?: number | null;
  1162. scheduled_time?: string | null;
  1163. require_previous_success?: boolean;
  1164. auto_off_after?: boolean;
  1165. manual_start?: boolean; // Requires manual trigger to start (staged)
  1166. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  1167. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1168. // Print options
  1169. bed_levelling?: boolean;
  1170. flow_cali?: boolean;
  1171. vibration_cali?: boolean;
  1172. layer_inspect?: boolean;
  1173. timelapse?: boolean;
  1174. use_ams?: boolean;
  1175. }
  1176. export interface PrintQueueItemUpdate {
  1177. printer_id?: number | null; // null = unassign
  1178. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1179. target_location?: string | null; // Target location filter (only used with target_model)
  1180. filament_overrides?: Array<{ slot_id: number; type: string; color: string }> | null;
  1181. position?: number;
  1182. scheduled_time?: string | null;
  1183. require_previous_success?: boolean;
  1184. auto_off_after?: boolean;
  1185. manual_start?: boolean;
  1186. ams_mapping?: number[];
  1187. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1188. // Print options
  1189. bed_levelling?: boolean;
  1190. flow_cali?: boolean;
  1191. vibration_cali?: boolean;
  1192. layer_inspect?: boolean;
  1193. timelapse?: boolean;
  1194. use_ams?: boolean;
  1195. }
  1196. export interface PrintQueueBulkUpdate {
  1197. item_ids: number[];
  1198. printer_id?: number | null;
  1199. scheduled_time?: string | null;
  1200. require_previous_success?: boolean;
  1201. auto_off_after?: boolean;
  1202. manual_start?: boolean;
  1203. // Print options
  1204. bed_levelling?: boolean;
  1205. flow_cali?: boolean;
  1206. vibration_cali?: boolean;
  1207. layer_inspect?: boolean;
  1208. timelapse?: boolean;
  1209. use_ams?: boolean;
  1210. }
  1211. export interface PrintQueueBulkUpdateResponse {
  1212. updated_count: number;
  1213. skipped_count: number;
  1214. message: string;
  1215. }
  1216. // MQTT Logging types
  1217. export interface MQTTLogEntry {
  1218. timestamp: string;
  1219. topic: string;
  1220. direction: 'in' | 'out';
  1221. payload: Record<string, unknown>;
  1222. }
  1223. export interface MQTTLogsResponse {
  1224. logging_enabled: boolean;
  1225. logs: MQTTLogEntry[];
  1226. }
  1227. // K-Profile types
  1228. export interface KProfile {
  1229. slot_id: number;
  1230. extruder_id: number;
  1231. nozzle_id: string;
  1232. nozzle_diameter: string;
  1233. filament_id: string;
  1234. name: string;
  1235. k_value: string;
  1236. n_coef: string;
  1237. ams_id: number;
  1238. tray_id: number;
  1239. setting_id: string | null;
  1240. }
  1241. export interface KProfileCreate {
  1242. slot_id?: number; // Storage slot, 0 for new profiles
  1243. extruder_id?: number;
  1244. nozzle_id: string;
  1245. nozzle_diameter: string;
  1246. filament_id: string;
  1247. name: string;
  1248. k_value: string;
  1249. n_coef?: string;
  1250. ams_id?: number;
  1251. tray_id?: number;
  1252. setting_id?: string | null;
  1253. }
  1254. export interface KProfileDelete {
  1255. slot_id: number; // cali_idx - calibration index to delete
  1256. extruder_id: number;
  1257. nozzle_id: string; // e.g., "HH00-0.4"
  1258. nozzle_diameter: string; // e.g., "0.4"
  1259. filament_id: string; // Bambu filament identifier
  1260. setting_id?: string | null; // Setting ID (for X1C series)
  1261. }
  1262. export interface KProfilesResponse {
  1263. profiles: KProfile[];
  1264. nozzle_diameter: string;
  1265. }
  1266. export interface KProfileNote {
  1267. setting_id: string;
  1268. note: string;
  1269. }
  1270. export interface KProfileNotesResponse {
  1271. notes: Record<string, string>; // setting_id -> note
  1272. }
  1273. // Slot Preset Mapping
  1274. export interface SlotPresetMapping {
  1275. ams_id: number;
  1276. tray_id: number;
  1277. preset_id: string;
  1278. preset_name: string;
  1279. }
  1280. // Filament types
  1281. export interface Filament {
  1282. id: number;
  1283. name: string;
  1284. type: string; // PLA, PETG, ABS, etc.
  1285. brand: string | null;
  1286. color: string | null;
  1287. color_hex: string | null;
  1288. cost_per_kg: number;
  1289. spool_weight_g: number;
  1290. currency: string;
  1291. density: number | null;
  1292. print_temp_min: number | null;
  1293. print_temp_max: number | null;
  1294. bed_temp_min: number | null;
  1295. bed_temp_max: number | null;
  1296. created_at: string;
  1297. updated_at: string;
  1298. }
  1299. // Notification Provider types
  1300. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook';
  1301. export interface NotificationProvider {
  1302. id: number;
  1303. name: string;
  1304. provider_type: ProviderType;
  1305. enabled: boolean;
  1306. config: Record<string, unknown>;
  1307. // Print lifecycle events
  1308. on_print_start: boolean;
  1309. on_print_complete: boolean;
  1310. on_print_failed: boolean;
  1311. on_print_stopped: boolean;
  1312. on_print_progress: boolean;
  1313. // Printer status events
  1314. on_printer_offline: boolean;
  1315. on_printer_error: boolean;
  1316. on_filament_low: boolean;
  1317. on_maintenance_due: boolean;
  1318. // AMS environmental alarms (regular AMS)
  1319. on_ams_humidity_high: boolean;
  1320. on_ams_temperature_high: boolean;
  1321. // AMS-HT environmental alarms
  1322. on_ams_ht_humidity_high: boolean;
  1323. on_ams_ht_temperature_high: boolean;
  1324. // Build plate detection
  1325. on_plate_not_empty: boolean;
  1326. // Bed cooled
  1327. on_bed_cooled: boolean;
  1328. // Print queue events
  1329. on_queue_job_added: boolean;
  1330. on_queue_job_assigned: boolean;
  1331. on_queue_job_started: boolean;
  1332. on_queue_job_waiting: boolean;
  1333. on_queue_job_skipped: boolean;
  1334. on_queue_job_failed: boolean;
  1335. on_queue_completed: boolean;
  1336. // Quiet hours
  1337. quiet_hours_enabled: boolean;
  1338. quiet_hours_start: string | null;
  1339. quiet_hours_end: string | null;
  1340. // Daily digest
  1341. daily_digest_enabled: boolean;
  1342. daily_digest_time: string | null;
  1343. // Printer filter
  1344. printer_id: number | null;
  1345. // Status tracking
  1346. last_success: string | null;
  1347. last_error: string | null;
  1348. last_error_at: string | null;
  1349. // Timestamps
  1350. created_at: string;
  1351. updated_at: string;
  1352. }
  1353. export interface NotificationProviderCreate {
  1354. name: string;
  1355. provider_type: ProviderType;
  1356. enabled?: boolean;
  1357. config: Record<string, unknown>;
  1358. // Print lifecycle events
  1359. on_print_start?: boolean;
  1360. on_print_complete?: boolean;
  1361. on_print_failed?: boolean;
  1362. on_print_stopped?: boolean;
  1363. on_print_progress?: boolean;
  1364. // Printer status events
  1365. on_printer_offline?: boolean;
  1366. on_printer_error?: boolean;
  1367. on_filament_low?: boolean;
  1368. on_maintenance_due?: boolean;
  1369. // AMS environmental alarms (regular AMS)
  1370. on_ams_humidity_high?: boolean;
  1371. on_ams_temperature_high?: boolean;
  1372. // AMS-HT environmental alarms
  1373. on_ams_ht_humidity_high?: boolean;
  1374. on_ams_ht_temperature_high?: boolean;
  1375. // Build plate detection
  1376. on_plate_not_empty?: boolean;
  1377. // Bed cooled
  1378. on_bed_cooled?: boolean;
  1379. // Print queue events
  1380. on_queue_job_added?: boolean;
  1381. on_queue_job_assigned?: boolean;
  1382. on_queue_job_started?: boolean;
  1383. on_queue_job_waiting?: boolean;
  1384. on_queue_job_skipped?: boolean;
  1385. on_queue_job_failed?: boolean;
  1386. on_queue_completed?: boolean;
  1387. // Quiet hours
  1388. quiet_hours_enabled?: boolean;
  1389. quiet_hours_start?: string | null;
  1390. quiet_hours_end?: string | null;
  1391. // Daily digest
  1392. daily_digest_enabled?: boolean;
  1393. daily_digest_time?: string | null;
  1394. // Printer filter
  1395. printer_id?: number | null;
  1396. }
  1397. export interface NotificationProviderUpdate {
  1398. name?: string;
  1399. provider_type?: ProviderType;
  1400. enabled?: boolean;
  1401. config?: Record<string, unknown>;
  1402. // Print lifecycle events
  1403. on_print_start?: boolean;
  1404. on_print_complete?: boolean;
  1405. on_print_failed?: boolean;
  1406. on_print_stopped?: boolean;
  1407. on_print_progress?: boolean;
  1408. // Printer status events
  1409. on_printer_offline?: boolean;
  1410. on_printer_error?: boolean;
  1411. on_filament_low?: boolean;
  1412. on_maintenance_due?: boolean;
  1413. // AMS environmental alarms (regular AMS)
  1414. on_ams_humidity_high?: boolean;
  1415. on_ams_temperature_high?: boolean;
  1416. // AMS-HT environmental alarms
  1417. on_ams_ht_humidity_high?: boolean;
  1418. on_ams_ht_temperature_high?: boolean;
  1419. // Build plate detection
  1420. on_plate_not_empty?: boolean;
  1421. // Bed cooled
  1422. on_bed_cooled?: boolean;
  1423. // Print queue events
  1424. on_queue_job_added?: boolean;
  1425. on_queue_job_assigned?: boolean;
  1426. on_queue_job_started?: boolean;
  1427. on_queue_job_waiting?: boolean;
  1428. on_queue_job_skipped?: boolean;
  1429. on_queue_job_failed?: boolean;
  1430. on_queue_completed?: boolean;
  1431. // Quiet hours
  1432. quiet_hours_enabled?: boolean;
  1433. quiet_hours_start?: string | null;
  1434. quiet_hours_end?: string | null;
  1435. // Daily digest
  1436. daily_digest_enabled?: boolean;
  1437. daily_digest_time?: string | null;
  1438. // Printer filter
  1439. printer_id?: number | null;
  1440. }
  1441. // GitHub Backup types
  1442. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  1443. export interface GitHubBackupConfig {
  1444. id: number;
  1445. repository_url: string;
  1446. has_token: boolean;
  1447. branch: string;
  1448. schedule_enabled: boolean;
  1449. schedule_type: ScheduleType;
  1450. backup_kprofiles: boolean;
  1451. backup_cloud_profiles: boolean;
  1452. backup_settings: boolean;
  1453. enabled: boolean;
  1454. last_backup_at: string | null;
  1455. last_backup_status: string | null;
  1456. last_backup_message: string | null;
  1457. last_backup_commit_sha: string | null;
  1458. next_scheduled_run: string | null;
  1459. created_at: string;
  1460. updated_at: string;
  1461. }
  1462. export interface GitHubBackupConfigCreate {
  1463. repository_url: string;
  1464. access_token: string;
  1465. branch?: string;
  1466. schedule_enabled?: boolean;
  1467. schedule_type?: ScheduleType;
  1468. backup_kprofiles?: boolean;
  1469. backup_cloud_profiles?: boolean;
  1470. backup_settings?: boolean;
  1471. enabled?: boolean;
  1472. }
  1473. export interface GitHubBackupLog {
  1474. id: number;
  1475. config_id: number;
  1476. started_at: string;
  1477. completed_at: string | null;
  1478. status: string;
  1479. trigger: string;
  1480. commit_sha: string | null;
  1481. files_changed: number;
  1482. error_message: string | null;
  1483. }
  1484. export interface GitHubBackupStatus {
  1485. configured: boolean;
  1486. enabled: boolean;
  1487. is_running: boolean;
  1488. progress: string | null;
  1489. last_backup_at: string | null;
  1490. last_backup_status: string | null;
  1491. next_scheduled_run: string | null;
  1492. }
  1493. export interface GitHubTestConnectionResponse {
  1494. success: boolean;
  1495. message: string;
  1496. repo_name: string | null;
  1497. permissions: Record<string, boolean> | null;
  1498. }
  1499. export interface GitHubBackupTriggerResponse {
  1500. success: boolean;
  1501. message: string;
  1502. log_id: number | null;
  1503. commit_sha: string | null;
  1504. files_changed: number;
  1505. }
  1506. export interface NotificationTestRequest {
  1507. provider_type: ProviderType;
  1508. config: Record<string, unknown>;
  1509. }
  1510. export interface NotificationTestResponse {
  1511. success: boolean;
  1512. message: string;
  1513. }
  1514. export interface BackgroundDispatchResponse {
  1515. status: 'dispatched' | string;
  1516. printer_id: number;
  1517. archive_id?: number | null;
  1518. filename: string;
  1519. dispatch_job_id: number;
  1520. dispatch_position: number;
  1521. }
  1522. // Provider-specific config types for reference
  1523. export interface CallMeBotConfig {
  1524. phone: string;
  1525. apikey: string;
  1526. }
  1527. export interface NtfyConfig {
  1528. server?: string;
  1529. topic: string;
  1530. auth_token?: string | null;
  1531. }
  1532. export interface PushoverConfig {
  1533. user_key: string;
  1534. app_token: string;
  1535. priority?: number;
  1536. }
  1537. export interface TelegramConfig {
  1538. bot_token: string;
  1539. chat_id: string;
  1540. }
  1541. export interface EmailConfig {
  1542. smtp_server: string;
  1543. smtp_port?: number;
  1544. username: string;
  1545. password: string;
  1546. from_email: string;
  1547. to_email: string;
  1548. use_tls?: boolean;
  1549. }
  1550. // Notification Template types
  1551. export interface NotificationTemplate {
  1552. id: number;
  1553. event_type: string;
  1554. name: string;
  1555. title_template: string;
  1556. body_template: string;
  1557. is_default: boolean;
  1558. created_at: string;
  1559. updated_at: string;
  1560. }
  1561. export interface NotificationTemplateUpdate {
  1562. title_template?: string;
  1563. body_template?: string;
  1564. }
  1565. export interface EventVariablesResponse {
  1566. event_type: string;
  1567. event_name: string;
  1568. variables: string[];
  1569. }
  1570. export interface TemplatePreviewRequest {
  1571. event_type: string;
  1572. title_template: string;
  1573. body_template: string;
  1574. }
  1575. export interface TemplatePreviewResponse {
  1576. title: string;
  1577. body: string;
  1578. }
  1579. // Notification Log types
  1580. export interface NotificationLogEntry {
  1581. id: number;
  1582. provider_id: number;
  1583. provider_name: string | null;
  1584. provider_type: string | null;
  1585. event_type: string;
  1586. title: string;
  1587. message: string;
  1588. success: boolean;
  1589. error_message: string | null;
  1590. printer_id: number | null;
  1591. printer_name: string | null;
  1592. created_at: string;
  1593. }
  1594. export interface NotificationLogStats {
  1595. total: number;
  1596. success_count: number;
  1597. failure_count: number;
  1598. by_event_type: Record<string, number>;
  1599. by_provider: Record<string, number>;
  1600. }
  1601. // Spoolman types
  1602. export interface SpoolmanStatus {
  1603. enabled: boolean;
  1604. connected: boolean;
  1605. url: string | null;
  1606. }
  1607. export interface SkippedSpool {
  1608. location: string;
  1609. reason: string;
  1610. filament_type: string | null;
  1611. color: string | null;
  1612. }
  1613. export interface SpoolmanSyncResult {
  1614. success: boolean;
  1615. synced_count: number;
  1616. skipped_count: number;
  1617. skipped: SkippedSpool[];
  1618. errors: string[];
  1619. }
  1620. export interface UnlinkedSpool {
  1621. id: number;
  1622. filament_name: string | null;
  1623. filament_material: string | null;
  1624. filament_color_hex: string | null;
  1625. remaining_weight: number | null;
  1626. location: string | null;
  1627. }
  1628. export interface LinkedSpoolInfo {
  1629. id: number;
  1630. remaining_weight: number | null;
  1631. filament_weight: number | null;
  1632. }
  1633. export interface LinkedSpoolsMap {
  1634. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  1635. }
  1636. // Inventory types
  1637. export interface InventorySpool {
  1638. id: number;
  1639. material: string;
  1640. subtype: string | null;
  1641. color_name: string | null;
  1642. rgba: string | null;
  1643. brand: string | null;
  1644. label_weight: number;
  1645. core_weight: number;
  1646. core_weight_catalog_id: number | null;
  1647. weight_used: number;
  1648. slicer_filament: string | null;
  1649. slicer_filament_name: string | null;
  1650. nozzle_temp_min: number | null;
  1651. nozzle_temp_max: number | null;
  1652. note: string | null;
  1653. added_full: boolean | null;
  1654. last_used: string | null;
  1655. encode_time: string | null;
  1656. tag_uid: string | null;
  1657. tray_uuid: string | null;
  1658. data_origin: string | null;
  1659. tag_type: string | null;
  1660. archived_at: string | null;
  1661. created_at: string;
  1662. updated_at: string;
  1663. cost_per_kg: number | null;
  1664. k_profiles?: SpoolKProfile[];
  1665. }
  1666. export interface SpoolUsageRecord {
  1667. id: number;
  1668. spool_id: number;
  1669. printer_id: number | null;
  1670. print_name: string | null;
  1671. weight_used: number;
  1672. percent_used: number;
  1673. status: string;
  1674. cost: number | null;
  1675. created_at: string;
  1676. }
  1677. export interface SpoolKProfile {
  1678. id: number;
  1679. spool_id: number;
  1680. printer_id: number;
  1681. extruder: number;
  1682. nozzle_diameter: string;
  1683. nozzle_type: string | null;
  1684. k_value: number;
  1685. name: string | null;
  1686. cali_idx: number | null;
  1687. setting_id: string | null;
  1688. created_at: string;
  1689. }
  1690. export interface SpoolKProfileInput {
  1691. printer_id: number;
  1692. extruder?: number;
  1693. nozzle_diameter?: string;
  1694. nozzle_type?: string | null;
  1695. k_value: number;
  1696. name?: string | null;
  1697. cali_idx?: number | null;
  1698. setting_id?: string | null;
  1699. }
  1700. export interface SpoolAssignment {
  1701. id: number;
  1702. spool_id: number;
  1703. printer_id: number;
  1704. printer_name: string | null;
  1705. ams_id: number;
  1706. tray_id: number;
  1707. fingerprint_color: string | null;
  1708. fingerprint_type: string | null;
  1709. spool?: InventorySpool | null;
  1710. configured: boolean;
  1711. created_at: string;
  1712. }
  1713. // Update types
  1714. export interface VersionInfo {
  1715. version: string;
  1716. repo: string;
  1717. }
  1718. export interface UpdateCheckResult {
  1719. update_available: boolean;
  1720. current_version: string;
  1721. latest_version: string | null;
  1722. release_name?: string;
  1723. release_notes?: string;
  1724. release_url?: string;
  1725. published_at?: string;
  1726. error?: string;
  1727. message?: string;
  1728. is_docker?: boolean;
  1729. update_method?: 'docker' | 'git';
  1730. }
  1731. export interface UpdateStatus {
  1732. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  1733. progress: number;
  1734. message: string;
  1735. error: string | null;
  1736. }
  1737. // Maintenance types
  1738. export interface MaintenanceType {
  1739. id: number;
  1740. name: string;
  1741. description: string | null;
  1742. default_interval_hours: number;
  1743. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  1744. icon: string | null;
  1745. wiki_url: string | null; // Documentation link
  1746. is_system: boolean;
  1747. created_at: string;
  1748. }
  1749. export interface MaintenanceTypeCreate {
  1750. name: string;
  1751. description?: string | null;
  1752. default_interval_hours?: number;
  1753. interval_type?: 'hours' | 'days';
  1754. icon?: string | null;
  1755. wiki_url?: string | null;
  1756. }
  1757. export interface MaintenanceStatus {
  1758. id: number;
  1759. printer_id: number;
  1760. printer_name: string;
  1761. printer_model: string | null;
  1762. maintenance_type_id: number;
  1763. maintenance_type_name: string;
  1764. maintenance_type_icon: string | null;
  1765. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  1766. enabled: boolean;
  1767. interval_hours: number; // For hours type: print hours; for days type: number of days
  1768. interval_type: 'hours' | 'days';
  1769. current_hours: number;
  1770. hours_since_maintenance: number;
  1771. hours_until_due: number;
  1772. days_since_maintenance: number | null; // For days type
  1773. days_until_due: number | null; // For days type
  1774. is_due: boolean;
  1775. is_warning: boolean;
  1776. last_performed_at: string | null;
  1777. }
  1778. export interface PrinterMaintenanceOverview {
  1779. printer_id: number;
  1780. printer_name: string;
  1781. printer_model: string | null;
  1782. total_print_hours: number;
  1783. maintenance_items: MaintenanceStatus[];
  1784. due_count: number;
  1785. warning_count: number;
  1786. }
  1787. export interface MaintenanceHistory {
  1788. id: number;
  1789. printer_maintenance_id: number;
  1790. performed_at: string;
  1791. hours_at_maintenance: number;
  1792. notes: string | null;
  1793. }
  1794. export interface MaintenanceSummary {
  1795. total_due: number;
  1796. total_warning: number;
  1797. printers_with_issues: Array<{
  1798. printer_id: number;
  1799. printer_name: string;
  1800. due_count: number;
  1801. warning_count: number;
  1802. }>;
  1803. }
  1804. // External Links (sidebar)
  1805. export interface ExternalLink {
  1806. id: number;
  1807. name: string;
  1808. url: string;
  1809. icon: string;
  1810. open_in_new_tab: boolean;
  1811. custom_icon: string | null;
  1812. sort_order: number;
  1813. created_at: string;
  1814. updated_at: string;
  1815. }
  1816. export interface ExternalLinkCreate {
  1817. name: string;
  1818. url: string;
  1819. icon: string;
  1820. open_in_new_tab?: boolean;
  1821. }
  1822. export interface ExternalLinkUpdate {
  1823. name?: string;
  1824. url?: string;
  1825. icon?: string;
  1826. open_in_new_tab?: boolean;
  1827. }
  1828. // Permission type - all available permissions
  1829. export type Permission =
  1830. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  1831. | 'archives:read' | 'archives:create'
  1832. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  1833. | 'archives:reprint_own' | 'archives:reprint_all'
  1834. | 'queue:read' | 'queue:create'
  1835. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  1836. | 'queue:reorder'
  1837. | 'library:read' | 'library:upload'
  1838. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  1839. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  1840. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  1841. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  1842. | 'camera:view'
  1843. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  1844. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  1845. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete'
  1846. | 'notification_templates:read' | 'notification_templates:update'
  1847. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  1848. | 'discovery:scan'
  1849. | 'firmware:read' | 'firmware:update'
  1850. | 'ams_history:read'
  1851. | 'stats:read'
  1852. | 'system:read'
  1853. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  1854. | 'github:backup' | 'github:restore'
  1855. | 'cloud:auth'
  1856. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  1857. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  1858. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  1859. | 'websocket:connect';
  1860. // Group types
  1861. export interface GroupBrief {
  1862. id: number;
  1863. name: string;
  1864. }
  1865. export interface Group {
  1866. id: number;
  1867. name: string;
  1868. description: string | null;
  1869. permissions: Permission[];
  1870. is_system: boolean;
  1871. user_count: number;
  1872. created_at: string;
  1873. updated_at: string;
  1874. }
  1875. export interface GroupDetail extends Group {
  1876. users: Array<{ id: number; username: string; is_active: boolean }>;
  1877. }
  1878. export interface GroupCreate {
  1879. name: string;
  1880. description?: string;
  1881. permissions: Permission[];
  1882. }
  1883. export interface GroupUpdate {
  1884. name?: string;
  1885. description?: string;
  1886. permissions?: Permission[];
  1887. }
  1888. export interface PermissionInfo {
  1889. value: Permission;
  1890. label: string;
  1891. }
  1892. export interface PermissionCategory {
  1893. name: string;
  1894. permissions: PermissionInfo[];
  1895. }
  1896. export interface PermissionsListResponse {
  1897. categories: PermissionCategory[];
  1898. all_permissions: Permission[];
  1899. }
  1900. // Auth types
  1901. export interface LoginRequest {
  1902. username: string;
  1903. password: string;
  1904. }
  1905. export interface LoginResponse {
  1906. access_token: string;
  1907. token_type: string;
  1908. user: UserResponse;
  1909. }
  1910. export interface UserResponse {
  1911. id: number;
  1912. username: string;
  1913. email?: string;
  1914. role: string; // Deprecated, kept for backward compatibility
  1915. is_active: boolean;
  1916. is_admin: boolean; // Computed from role and group membership
  1917. groups: GroupBrief[];
  1918. permissions: Permission[]; // All permissions from groups
  1919. created_at: string;
  1920. }
  1921. export interface UserCreate {
  1922. username: string;
  1923. password?: string; // Optional when advanced auth is enabled
  1924. email?: string;
  1925. role: string;
  1926. group_ids?: number[];
  1927. }
  1928. export interface UserUpdate {
  1929. username?: string;
  1930. password?: string;
  1931. email?: string;
  1932. role?: string;
  1933. is_active?: boolean;
  1934. group_ids?: number[];
  1935. }
  1936. export interface SetupRequest {
  1937. auth_enabled: boolean;
  1938. admin_username?: string;
  1939. admin_password?: string;
  1940. }
  1941. export interface ForgotPasswordRequest {
  1942. email: string;
  1943. }
  1944. export interface ForgotPasswordResponse {
  1945. message: string;
  1946. }
  1947. export interface ResetPasswordRequest {
  1948. user_id: number;
  1949. }
  1950. export interface ResetPasswordResponse {
  1951. message: string;
  1952. }
  1953. export interface SMTPSettings {
  1954. smtp_host: string;
  1955. smtp_port: number;
  1956. smtp_username?: string;
  1957. smtp_password?: string;
  1958. smtp_security: 'starttls' | 'ssl' | 'none';
  1959. smtp_auth_enabled: boolean;
  1960. smtp_from_email: string;
  1961. smtp_from_name: string;
  1962. }
  1963. export interface TestSMTPRequest {
  1964. smtp_host: string;
  1965. smtp_port: number;
  1966. smtp_username?: string;
  1967. smtp_password?: string;
  1968. smtp_security: 'starttls' | 'ssl' | 'none';
  1969. smtp_auth_enabled: boolean;
  1970. smtp_from_email: string;
  1971. test_recipient: string;
  1972. }
  1973. export interface TestSMTPResponse {
  1974. success: boolean;
  1975. message: string;
  1976. }
  1977. export interface AdvancedAuthStatus {
  1978. advanced_auth_enabled: boolean;
  1979. smtp_configured: boolean;
  1980. }
  1981. export interface SetupResponse {
  1982. auth_enabled: boolean;
  1983. admin_created?: boolean;
  1984. }
  1985. export interface AuthStatus {
  1986. auth_enabled: boolean;
  1987. requires_setup: boolean;
  1988. }
  1989. // API functions
  1990. export const api = {
  1991. // Authentication
  1992. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  1993. setupAuth: (data: SetupRequest) =>
  1994. request<SetupResponse>('/auth/setup', {
  1995. method: 'POST',
  1996. body: JSON.stringify(data),
  1997. }),
  1998. login: (data: LoginRequest) =>
  1999. request<LoginResponse>('/auth/login', {
  2000. method: 'POST',
  2001. body: JSON.stringify(data),
  2002. }),
  2003. logout: () =>
  2004. request<{ message: string }>('/auth/logout', {
  2005. method: 'POST',
  2006. }),
  2007. getCurrentUser: () => request<UserResponse>('/auth/me'),
  2008. disableAuth: () =>
  2009. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  2010. method: 'POST',
  2011. }),
  2012. // Advanced Authentication
  2013. testSMTP: (data: TestSMTPRequest) =>
  2014. request<TestSMTPResponse>('/auth/smtp/test', {
  2015. method: 'POST',
  2016. body: JSON.stringify(data),
  2017. }),
  2018. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  2019. saveSMTPSettings: (data: SMTPSettings) =>
  2020. request<{ message: string }>('/auth/smtp', {
  2021. method: 'POST',
  2022. body: JSON.stringify(data),
  2023. }),
  2024. enableAdvancedAuth: () =>
  2025. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  2026. method: 'POST',
  2027. }),
  2028. disableAdvancedAuth: () =>
  2029. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  2030. method: 'POST',
  2031. }),
  2032. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  2033. forgotPassword: (data: ForgotPasswordRequest) =>
  2034. request<ForgotPasswordResponse>('/auth/forgot-password', {
  2035. method: 'POST',
  2036. body: JSON.stringify(data),
  2037. }),
  2038. resetUserPassword: (data: ResetPasswordRequest) =>
  2039. request<ResetPasswordResponse>('/auth/reset-password', {
  2040. method: 'POST',
  2041. body: JSON.stringify(data),
  2042. }),
  2043. // Users
  2044. getUsers: () => request<UserResponse[]>('/users/'),
  2045. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  2046. createUser: (data: UserCreate) =>
  2047. request<UserResponse>('/users/', {
  2048. method: 'POST',
  2049. body: JSON.stringify(data),
  2050. }),
  2051. updateUser: (id: number, data: UserUpdate) =>
  2052. request<UserResponse>(`/users/${id}`, {
  2053. method: 'PATCH',
  2054. body: JSON.stringify(data),
  2055. }),
  2056. deleteUser: (id: number, deleteItems: boolean = false) =>
  2057. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  2058. method: 'DELETE',
  2059. }),
  2060. getUserItemsCount: (id: number) =>
  2061. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  2062. changePassword: (currentPassword: string, newPassword: string) =>
  2063. request<{ message: string }>('/users/me/change-password', {
  2064. method: 'POST',
  2065. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  2066. }),
  2067. // Groups
  2068. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  2069. getGroups: () => request<Group[]>('/groups/'),
  2070. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  2071. createGroup: (data: GroupCreate) =>
  2072. request<Group>('/groups/', {
  2073. method: 'POST',
  2074. body: JSON.stringify(data),
  2075. }),
  2076. updateGroup: (id: number, data: GroupUpdate) =>
  2077. request<Group>(`/groups/${id}`, {
  2078. method: 'PATCH',
  2079. body: JSON.stringify(data),
  2080. }),
  2081. deleteGroup: (id: number) =>
  2082. request<void>(`/groups/${id}`, {
  2083. method: 'DELETE',
  2084. }),
  2085. addUserToGroup: (groupId: number, userId: number) =>
  2086. request<void>(`/groups/${groupId}/users/${userId}`, {
  2087. method: 'POST',
  2088. }),
  2089. removeUserFromGroup: (groupId: number, userId: number) =>
  2090. request<void>(`/groups/${groupId}/users/${userId}`, {
  2091. method: 'DELETE',
  2092. }),
  2093. // Printers
  2094. getPrinters: () => request<Printer[]>('/printers/'),
  2095. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  2096. createPrinter: (data: PrinterCreate) =>
  2097. request<Printer>('/printers/', {
  2098. method: 'POST',
  2099. body: JSON.stringify(data),
  2100. }),
  2101. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  2102. request<Printer>(`/printers/${id}`, {
  2103. method: 'PATCH',
  2104. body: JSON.stringify(data),
  2105. }),
  2106. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  2107. request<{ status: string; archives_deleted: boolean }>(
  2108. `/printers/${id}?delete_archives=${deleteArchives}`,
  2109. { method: 'DELETE' }
  2110. ),
  2111. getDeveloperModeWarnings: () =>
  2112. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  2113. getAvailableFilaments: (model: string, location?: string) => {
  2114. const params = new URLSearchParams({ model });
  2115. if (location) params.set('location', location);
  2116. return request<Array<{ type: string; color: string; tray_info_idx: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  2117. },
  2118. getPrinterStatus: (id: number) =>
  2119. request<PrinterStatus>(`/printers/${id}/status`),
  2120. refreshPrinterStatus: (id: number) =>
  2121. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  2122. method: 'POST',
  2123. }),
  2124. connectPrinter: (id: number) =>
  2125. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  2126. method: 'POST',
  2127. }),
  2128. disconnectPrinter: (id: number) =>
  2129. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  2130. method: 'POST',
  2131. }),
  2132. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  2133. request<{ success: boolean; error?: string; resolution?: string }>(
  2134. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  2135. { method: 'POST' }
  2136. ),
  2137. // Print Control
  2138. stopPrint: (printerId: number) =>
  2139. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  2140. method: 'POST',
  2141. }),
  2142. pausePrint: (printerId: number) =>
  2143. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  2144. method: 'POST',
  2145. }),
  2146. resumePrint: (printerId: number) =>
  2147. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  2148. method: 'POST',
  2149. }),
  2150. clearPlate: (printerId: number) =>
  2151. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  2152. method: 'POST',
  2153. }),
  2154. // Get current print user (for reprint tracking - Issue #206)
  2155. getCurrentPrintUser: (printerId: number) =>
  2156. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  2157. // Chamber Light Control
  2158. setChamberLight: (printerId: number, on: boolean) =>
  2159. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  2160. method: 'POST',
  2161. }),
  2162. // Skip Objects
  2163. getPrintableObjects: (printerId: number) =>
  2164. request<{
  2165. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  2166. total: number;
  2167. skipped_count: number;
  2168. is_printing: boolean;
  2169. bbox_all: [number, number, number, number] | null;
  2170. }>(`/printers/${printerId}/print/objects`),
  2171. skipObjects: (printerId: number, objectIds: number[]) =>
  2172. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  2173. `/printers/${printerId}/print/skip-objects`,
  2174. {
  2175. method: 'POST',
  2176. body: JSON.stringify(objectIds),
  2177. }
  2178. ),
  2179. // HMS Errors
  2180. clearHMSErrors: (printerId: number) =>
  2181. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  2182. // AMS Control
  2183. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  2184. request<{ success: boolean; message: string }>(
  2185. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  2186. { method: 'POST' }
  2187. ),
  2188. // MQTT Debug Logging
  2189. enableMQTTLogging: (printerId: number) =>
  2190. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  2191. method: 'POST',
  2192. }),
  2193. disableMQTTLogging: (printerId: number) =>
  2194. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  2195. method: 'POST',
  2196. }),
  2197. getMQTTLogs: (printerId: number) =>
  2198. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  2199. clearMQTTLogs: (printerId: number) =>
  2200. request<{ status: string }>(`/printers/${printerId}/logging`, {
  2201. method: 'DELETE',
  2202. }),
  2203. // Printer File Manager
  2204. getPrinterFiles: (printerId: number, path = '/') =>
  2205. request<{
  2206. path: string;
  2207. files: Array<{
  2208. name: string;
  2209. is_directory: boolean;
  2210. size: number;
  2211. path: string;
  2212. mtime?: string;
  2213. }>;
  2214. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  2215. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  2216. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  2217. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  2218. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  2219. getPrinterFilePlates: (printerId: number, path: string) =>
  2220. request<{
  2221. printer_id: number;
  2222. path: string;
  2223. filename: string;
  2224. plates: Array<{
  2225. index: number;
  2226. name: string | null;
  2227. objects: string[];
  2228. has_thumbnail: boolean;
  2229. thumbnail_url: string | null;
  2230. print_time_seconds: number | null;
  2231. filament_used_grams: number | null;
  2232. filaments: Array<{
  2233. slot_id: number;
  2234. type: string;
  2235. color: string;
  2236. used_grams: number;
  2237. used_meters: number;
  2238. }>;
  2239. }>;
  2240. is_multi_plate: boolean;
  2241. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  2242. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  2243. `${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`,
  2244. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  2245. const headers: Record<string, string> = {};
  2246. if (authToken) {
  2247. headers['Authorization'] = `Bearer ${authToken}`;
  2248. }
  2249. const response = await fetch(
  2250. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  2251. { headers }
  2252. );
  2253. if (!response.ok) {
  2254. const error = await response.json().catch(() => ({}));
  2255. throw new Error(error.detail || `HTTP ${response.status}`);
  2256. }
  2257. const disposition = response.headers.get('Content-Disposition');
  2258. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  2259. const blob = await response.blob();
  2260. const url = window.URL.createObjectURL(blob);
  2261. const a = document.createElement('a');
  2262. a.href = url;
  2263. a.download = filename;
  2264. document.body.appendChild(a);
  2265. a.click();
  2266. document.body.removeChild(a);
  2267. window.URL.revokeObjectURL(url);
  2268. },
  2269. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  2270. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  2271. if (authToken) {
  2272. headers['Authorization'] = `Bearer ${authToken}`;
  2273. }
  2274. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  2275. method: 'POST',
  2276. headers,
  2277. body: JSON.stringify({ paths }),
  2278. });
  2279. if (!response.ok) {
  2280. const error = await response.json().catch(() => ({}));
  2281. throw new Error(error.detail || `HTTP ${response.status}`);
  2282. }
  2283. return response.blob();
  2284. },
  2285. deletePrinterFile: (printerId: number, path: string) =>
  2286. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  2287. method: 'DELETE',
  2288. }),
  2289. getPrinterStorage: (printerId: number) =>
  2290. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  2291. // Archives
  2292. getArchives: (printerId?: number, projectId?: number, limit = 50, offset = 0) => {
  2293. const params = new URLSearchParams();
  2294. if (printerId) params.set('printer_id', String(printerId));
  2295. if (projectId) params.set('project_id', String(projectId));
  2296. params.set('limit', String(limit));
  2297. params.set('offset', String(offset));
  2298. return request<Archive[]>(`/archives/?${params}`);
  2299. },
  2300. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  2301. searchArchives: (query: string, options?: {
  2302. printerId?: number;
  2303. projectId?: number;
  2304. status?: string;
  2305. limit?: number;
  2306. offset?: number;
  2307. }) => {
  2308. const params = new URLSearchParams();
  2309. params.set('q', query);
  2310. if (options?.printerId) params.set('printer_id', String(options.printerId));
  2311. if (options?.projectId) params.set('project_id', String(options.projectId));
  2312. if (options?.status) params.set('status', options.status);
  2313. if (options?.limit) params.set('limit', String(options.limit));
  2314. if (options?.offset) params.set('offset', String(options.offset));
  2315. return request<Archive[]>(`/archives/search?${params}`);
  2316. },
  2317. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  2318. updateArchive: (id: number, data: {
  2319. printer_id?: number | null;
  2320. project_id?: number | null;
  2321. print_name?: string;
  2322. is_favorite?: boolean;
  2323. tags?: string;
  2324. notes?: string;
  2325. cost?: number;
  2326. failure_reason?: string | null;
  2327. status?: string;
  2328. quantity?: number;
  2329. external_url?: string | null;
  2330. }) =>
  2331. request<Archive>(`/archives/${id}`, {
  2332. method: 'PATCH',
  2333. body: JSON.stringify(data),
  2334. }),
  2335. toggleFavorite: (id: number) =>
  2336. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  2337. deleteArchive: (id: number) =>
  2338. request<void>(`/archives/${id}`, { method: 'DELETE' }),
  2339. getArchiveStats: () => request<ArchiveStats>('/archives/stats'),
  2340. // Tag management
  2341. getTags: () => request<TagInfo[]>('/archives/tags'),
  2342. renameTag: (oldName: string, newName: string) =>
  2343. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  2344. method: 'PUT',
  2345. body: JSON.stringify({ new_name: newName }),
  2346. }),
  2347. deleteTag: (name: string) =>
  2348. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  2349. method: 'DELETE',
  2350. }),
  2351. recalculateCosts: () =>
  2352. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  2353. getFailureAnalysis: (options?: { days?: number; printerId?: number; projectId?: number }) => {
  2354. const params = new URLSearchParams();
  2355. if (options?.days) params.set('days', String(options.days));
  2356. if (options?.printerId) params.set('printer_id', String(options.printerId));
  2357. if (options?.projectId) params.set('project_id', String(options.projectId));
  2358. return request<FailureAnalysis>(`/archives/analysis/failures?${params}`);
  2359. },
  2360. compareArchives: (archiveIds: number[]) =>
  2361. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  2362. findSimilarArchives: (archiveId: number, limit = 10) =>
  2363. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  2364. exportArchives: async (options?: {
  2365. format?: 'csv' | 'xlsx';
  2366. fields?: string[];
  2367. printerId?: number;
  2368. projectId?: number;
  2369. status?: string;
  2370. dateFrom?: string;
  2371. dateTo?: string;
  2372. search?: string;
  2373. }): Promise<{ blob: Blob; filename: string }> => {
  2374. const params = new URLSearchParams();
  2375. if (options?.format) params.set('format', options.format);
  2376. if (options?.fields) params.set('fields', options.fields.join(','));
  2377. if (options?.printerId) params.set('printer_id', String(options.printerId));
  2378. if (options?.projectId) params.set('project_id', String(options.projectId));
  2379. if (options?.status) params.set('status', options.status);
  2380. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  2381. if (options?.dateTo) params.set('date_to', options.dateTo);
  2382. if (options?.search) params.set('search', options.search);
  2383. const headers: Record<string, string> = {};
  2384. if (authToken) {
  2385. headers['Authorization'] = `Bearer ${authToken}`;
  2386. }
  2387. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  2388. if (!response.ok) {
  2389. const error = await response.json().catch(() => ({}));
  2390. throw new Error(error.detail || `HTTP ${response.status}`);
  2391. }
  2392. const contentDisposition = response.headers.get('Content-Disposition');
  2393. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  2394. if (contentDisposition) {
  2395. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  2396. if (match) filename = match[1];
  2397. }
  2398. const blob = await response.blob();
  2399. return { blob, filename };
  2400. },
  2401. exportStats: async (options?: {
  2402. format?: 'csv' | 'xlsx';
  2403. days?: number;
  2404. printerId?: number;
  2405. projectId?: number;
  2406. }): Promise<{ blob: Blob; filename: string }> => {
  2407. const params = new URLSearchParams();
  2408. if (options?.format) params.set('format', options.format);
  2409. if (options?.days) params.set('days', String(options.days));
  2410. if (options?.printerId) params.set('printer_id', String(options.printerId));
  2411. if (options?.projectId) params.set('project_id', String(options.projectId));
  2412. const headers: Record<string, string> = {};
  2413. if (authToken) {
  2414. headers['Authorization'] = `Bearer ${authToken}`;
  2415. }
  2416. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  2417. if (!response.ok) {
  2418. const error = await response.json().catch(() => ({}));
  2419. throw new Error(error.detail || `HTTP ${response.status}`);
  2420. }
  2421. const contentDisposition = response.headers.get('Content-Disposition');
  2422. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  2423. if (contentDisposition) {
  2424. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  2425. if (match) filename = match[1];
  2426. }
  2427. const blob = await response.blob();
  2428. return { blob, filename };
  2429. },
  2430. getArchiveDuplicates: (id: number) =>
  2431. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  2432. backfillContentHashes: () =>
  2433. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  2434. method: 'POST',
  2435. }),
  2436. getArchiveThumbnail: (id: number) => `${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`,
  2437. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  2438. `${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`,
  2439. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  2440. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  2441. const headers: Record<string, string> = {};
  2442. if (authToken) {
  2443. headers['Authorization'] = `Bearer ${authToken}`;
  2444. }
  2445. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  2446. if (!response.ok) {
  2447. const error = await response.json().catch(() => ({}));
  2448. throw new Error(error.detail || `HTTP ${response.status}`);
  2449. }
  2450. const disposition = response.headers.get('Content-Disposition');
  2451. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  2452. const blob = await response.blob();
  2453. const url = window.URL.createObjectURL(blob);
  2454. const a = document.createElement('a');
  2455. a.href = url;
  2456. a.download = downloadFilename;
  2457. document.body.appendChild(a);
  2458. a.click();
  2459. document.body.removeChild(a);
  2460. window.URL.revokeObjectURL(url);
  2461. },
  2462. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  2463. getArchivePlatePreview: (id: number) => `${API_BASE}/archives/${id}/plate-preview`,
  2464. getArchiveTimelapse: (id: number) => `${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`,
  2465. scanArchiveTimelapse: (id: number) =>
  2466. request<{
  2467. status: string;
  2468. message: string;
  2469. filename?: string;
  2470. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  2471. }>(`/archives/${id}/timelapse/scan`, {
  2472. method: 'POST',
  2473. }),
  2474. selectArchiveTimelapse: (id: number, filename: string) =>
  2475. request<{ status: string; message: string; filename: string }>(
  2476. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  2477. { method: 'POST' }
  2478. ),
  2479. deleteArchiveTimelapse: (id: number) =>
  2480. request<{ status: string }>(`/archives/${id}/timelapse`, {
  2481. method: 'DELETE',
  2482. }),
  2483. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  2484. const formData = new FormData();
  2485. formData.append('file', file);
  2486. const headers: Record<string, string> = {};
  2487. if (authToken) {
  2488. headers['Authorization'] = `Bearer ${authToken}`;
  2489. }
  2490. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  2491. method: 'POST',
  2492. headers,
  2493. body: formData,
  2494. });
  2495. if (!response.ok) {
  2496. const error = await response.json().catch(() => ({}));
  2497. throw new Error(error.detail || `HTTP ${response.status}`);
  2498. }
  2499. return response.json();
  2500. },
  2501. // Timelapse Editor
  2502. getTimelapseInfo: (archiveId: number) =>
  2503. request<{
  2504. duration: number;
  2505. width: number;
  2506. height: number;
  2507. fps: number;
  2508. codec: string;
  2509. file_size: number;
  2510. has_audio: boolean;
  2511. }>(`/archives/${archiveId}/timelapse/info`),
  2512. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  2513. request<{
  2514. thumbnails: string[];
  2515. timestamps: number[];
  2516. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  2517. processTimelapse: async (
  2518. archiveId: number,
  2519. params: {
  2520. trimStart?: number;
  2521. trimEnd?: number;
  2522. speed?: number;
  2523. saveMode: 'replace' | 'new';
  2524. outputFilename?: string;
  2525. },
  2526. audioFile?: File
  2527. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  2528. const formData = new FormData();
  2529. formData.append('trim_start', String(params.trimStart ?? 0));
  2530. if (params.trimEnd !== undefined) {
  2531. formData.append('trim_end', String(params.trimEnd));
  2532. }
  2533. formData.append('speed', String(params.speed ?? 1));
  2534. formData.append('save_mode', params.saveMode);
  2535. if (params.outputFilename) {
  2536. formData.append('output_filename', params.outputFilename);
  2537. }
  2538. if (audioFile) {
  2539. formData.append('audio', audioFile);
  2540. }
  2541. const headers: Record<string, string> = {};
  2542. if (authToken) {
  2543. headers['Authorization'] = `Bearer ${authToken}`;
  2544. }
  2545. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  2546. method: 'POST',
  2547. headers,
  2548. body: formData,
  2549. });
  2550. if (!response.ok) {
  2551. const error = await response.json().catch(() => ({}));
  2552. throw new Error(error.detail || `HTTP ${response.status}`);
  2553. }
  2554. return response.json();
  2555. },
  2556. // Photos
  2557. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  2558. `${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`,
  2559. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  2560. const formData = new FormData();
  2561. formData.append('file', file);
  2562. const headers: Record<string, string> = {};
  2563. if (authToken) {
  2564. headers['Authorization'] = `Bearer ${authToken}`;
  2565. }
  2566. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  2567. headers,
  2568. method: 'POST',
  2569. body: formData,
  2570. });
  2571. if (!response.ok) {
  2572. const error = await response.json().catch(() => ({}));
  2573. throw new Error(error.detail || `HTTP ${response.status}`);
  2574. }
  2575. return response.json();
  2576. },
  2577. deleteArchivePhoto: (archiveId: number, filename: string) =>
  2578. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  2579. method: 'DELETE',
  2580. }),
  2581. // Source 3MF (original slicer project file)
  2582. getSource3mfDownloadUrl: (archiveId: number) =>
  2583. `${API_BASE}/archives/${archiveId}/source`,
  2584. downloadSource3mf: async (archiveId: number): Promise<void> => {
  2585. const headers: Record<string, string> = {};
  2586. if (authToken) {
  2587. headers['Authorization'] = `Bearer ${authToken}`;
  2588. }
  2589. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  2590. if (!response.ok) {
  2591. const error = await response.json().catch(() => ({}));
  2592. throw new Error(error.detail || `HTTP ${response.status}`);
  2593. }
  2594. const disposition = response.headers.get('Content-Disposition');
  2595. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  2596. const blob = await response.blob();
  2597. const url = window.URL.createObjectURL(blob);
  2598. const a = document.createElement('a');
  2599. a.href = url;
  2600. a.download = filename;
  2601. document.body.appendChild(a);
  2602. a.click();
  2603. document.body.removeChild(a);
  2604. window.URL.revokeObjectURL(url);
  2605. },
  2606. getSource3mfForSlicer: (archiveId: number, filename: string) =>
  2607. `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  2608. createSourceSlicerToken: (archiveId: number) =>
  2609. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  2610. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) =>
  2611. `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  2612. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  2613. const formData = new FormData();
  2614. formData.append('file', file);
  2615. const headers: Record<string, string> = {};
  2616. if (authToken) {
  2617. headers['Authorization'] = `Bearer ${authToken}`;
  2618. }
  2619. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  2620. method: 'POST',
  2621. headers,
  2622. body: formData,
  2623. });
  2624. if (!response.ok) {
  2625. const error = await response.json().catch(() => ({}));
  2626. throw new Error(error.detail || `HTTP ${response.status}`);
  2627. }
  2628. return response.json();
  2629. },
  2630. deleteSource3mf: (archiveId: number) =>
  2631. request<{ status: string }>(`/archives/${archiveId}/source`, {
  2632. method: 'DELETE',
  2633. }),
  2634. // F3D (Fusion 360 design file)
  2635. getF3dDownloadUrl: (archiveId: number) =>
  2636. `${API_BASE}/archives/${archiveId}/f3d`,
  2637. downloadF3d: async (archiveId: number): Promise<void> => {
  2638. const headers: Record<string, string> = {};
  2639. if (authToken) {
  2640. headers['Authorization'] = `Bearer ${authToken}`;
  2641. }
  2642. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  2643. if (!response.ok) {
  2644. const error = await response.json().catch(() => ({}));
  2645. throw new Error(error.detail || `HTTP ${response.status}`);
  2646. }
  2647. const disposition = response.headers.get('Content-Disposition');
  2648. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  2649. const blob = await response.blob();
  2650. const url = window.URL.createObjectURL(blob);
  2651. const a = document.createElement('a');
  2652. a.href = url;
  2653. a.download = filename;
  2654. document.body.appendChild(a);
  2655. a.click();
  2656. document.body.removeChild(a);
  2657. window.URL.revokeObjectURL(url);
  2658. },
  2659. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  2660. const formData = new FormData();
  2661. formData.append('file', file);
  2662. const headers: Record<string, string> = {};
  2663. if (authToken) {
  2664. headers['Authorization'] = `Bearer ${authToken}`;
  2665. }
  2666. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  2667. method: 'POST',
  2668. headers,
  2669. body: formData,
  2670. });
  2671. if (!response.ok) {
  2672. const error = await response.json().catch(() => ({}));
  2673. throw new Error(error.detail || `HTTP ${response.status}`);
  2674. }
  2675. return response.json();
  2676. },
  2677. deleteF3d: (archiveId: number) =>
  2678. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  2679. method: 'DELETE',
  2680. }),
  2681. // QR Code
  2682. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  2683. `${API_BASE}/archives/${archiveId}/qrcode?size=${size}`,
  2684. getArchiveCapabilities: (id: number) =>
  2685. request<{
  2686. has_model: boolean;
  2687. has_gcode: boolean;
  2688. has_source: boolean;
  2689. build_volume: { x: number; y: number; z: number };
  2690. filament_colors: string[];
  2691. }>(`/archives/${id}/capabilities`),
  2692. // Project Page
  2693. getArchiveProjectPage: (id: number) =>
  2694. request<{
  2695. title: string | null;
  2696. description: string | null;
  2697. designer: string | null;
  2698. designer_user_id: string | null;
  2699. license: string | null;
  2700. copyright: string | null;
  2701. creation_date: string | null;
  2702. modification_date: string | null;
  2703. origin: string | null;
  2704. profile_title: string | null;
  2705. profile_description: string | null;
  2706. profile_cover: string | null;
  2707. profile_user_id: string | null;
  2708. profile_user_name: string | null;
  2709. design_model_id: string | null;
  2710. design_profile_id: string | null;
  2711. design_region: string | null;
  2712. model_pictures: Array<{ name: string; path: string; url: string }>;
  2713. profile_pictures: Array<{ name: string; path: string; url: string }>;
  2714. thumbnails: Array<{ name: string; path: string; url: string }>;
  2715. }>(`/archives/${id}/project-page`),
  2716. updateArchiveProjectPage: (id: number, data: {
  2717. title?: string;
  2718. description?: string;
  2719. designer?: string;
  2720. license?: string;
  2721. copyright?: string;
  2722. profile_title?: string;
  2723. profile_description?: string;
  2724. }) =>
  2725. request(`/archives/${id}/project-page`, {
  2726. method: 'PATCH',
  2727. body: JSON.stringify(data),
  2728. }),
  2729. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  2730. `${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`,
  2731. getArchiveForSlicer: (id: number, filename: string) =>
  2732. `${API_BASE}/archives/${id}/file/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  2733. createArchiveSlicerToken: (archiveId: number) =>
  2734. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  2735. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) =>
  2736. `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  2737. getArchivePlates: (archiveId: number) =>
  2738. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  2739. getArchiveFilamentRequirements: (archiveId: number, plateId?: number) =>
  2740. request<{
  2741. archive_id: number;
  2742. filename: string;
  2743. plate_id: number | null;
  2744. filaments: Array<{
  2745. slot_id: number;
  2746. type: string;
  2747. color: string;
  2748. used_grams: number;
  2749. used_meters: number;
  2750. }>;
  2751. }>(`/archives/${archiveId}/filament-requirements${plateId !== undefined ? `?plate_id=${plateId}` : ''}`),
  2752. reprintArchive: (
  2753. archiveId: number,
  2754. printerId: number,
  2755. options?: {
  2756. plate_id?: number;
  2757. plate_name?: string;
  2758. ams_mapping?: number[];
  2759. timelapse?: boolean;
  2760. bed_levelling?: boolean;
  2761. flow_cali?: boolean;
  2762. vibration_cali?: boolean;
  2763. layer_inspect?: boolean;
  2764. use_ams?: boolean;
  2765. }
  2766. ) =>
  2767. request<BackgroundDispatchResponse>(
  2768. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  2769. {
  2770. method: 'POST',
  2771. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  2772. body: options ? JSON.stringify(options) : undefined,
  2773. }
  2774. ),
  2775. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  2776. const formData = new FormData();
  2777. formData.append('file', file);
  2778. const url = printerId
  2779. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  2780. : `${API_BASE}/archives/upload`;
  2781. const headers: Record<string, string> = {};
  2782. if (authToken) {
  2783. headers['Authorization'] = `Bearer ${authToken}`;
  2784. }
  2785. const response = await fetch(url, {
  2786. method: 'POST',
  2787. headers,
  2788. body: formData,
  2789. });
  2790. if (!response.ok) {
  2791. const error = await response.json().catch(() => ({}));
  2792. throw new Error(error.detail || `HTTP ${response.status}`);
  2793. }
  2794. return response.json();
  2795. },
  2796. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  2797. const formData = new FormData();
  2798. files.forEach((file) => formData.append('files', file));
  2799. const url = printerId
  2800. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  2801. : `${API_BASE}/archives/upload-bulk`;
  2802. const headers: Record<string, string> = {};
  2803. if (authToken) {
  2804. headers['Authorization'] = `Bearer ${authToken}`;
  2805. }
  2806. const response = await fetch(url, {
  2807. method: 'POST',
  2808. headers,
  2809. body: formData,
  2810. });
  2811. if (!response.ok) {
  2812. const error = await response.json().catch(() => ({}));
  2813. throw new Error(error.detail || `HTTP ${response.status}`);
  2814. }
  2815. return response.json();
  2816. },
  2817. // Print Log
  2818. getPrintLog: (params?: {
  2819. search?: string;
  2820. printerId?: number;
  2821. username?: string;
  2822. status?: string;
  2823. dateFrom?: string;
  2824. dateTo?: string;
  2825. limit?: number;
  2826. offset?: number;
  2827. }) => {
  2828. const searchParams = new URLSearchParams();
  2829. if (params?.search) searchParams.set('search', params.search);
  2830. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  2831. if (params?.username) searchParams.set('created_by_username', params.username);
  2832. if (params?.status) searchParams.set('status', params.status);
  2833. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  2834. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  2835. if (params?.limit) searchParams.set('limit', String(params.limit));
  2836. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  2837. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  2838. },
  2839. getPrintLogThumbnail: (id: number) => `${API_BASE}/print-log/${id}/thumbnail`,
  2840. clearPrintLog: () =>
  2841. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  2842. // Settings
  2843. getSettings: () => request<AppSettings>('/settings/'),
  2844. updateSettings: (data: AppSettingsUpdate) =>
  2845. request<AppSettings>('/settings/', {
  2846. method: 'PUT',
  2847. body: JSON.stringify(data),
  2848. }),
  2849. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  2850. resetSettings: () =>
  2851. request<AppSettings>('/settings/reset', { method: 'POST' }),
  2852. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  2853. // New simplified backup - complete database + all files
  2854. const url = `${API_BASE}/settings/backup`;
  2855. const headers: Record<string, string> = {};
  2856. if (authToken) {
  2857. headers['Authorization'] = `Bearer ${authToken}`;
  2858. }
  2859. const response = await fetch(url, { headers });
  2860. // Check for errors
  2861. if (!response.ok) {
  2862. const errorText = await response.text();
  2863. throw new Error(errorText || `Backup failed with status ${response.status}`);
  2864. }
  2865. // Get filename from Content-Disposition header
  2866. const contentDisposition = response.headers.get('Content-Disposition');
  2867. let filename = 'bambuddy-backup.zip';
  2868. if (contentDisposition) {
  2869. const match = contentDisposition.match(/filename=([^;]+)/);
  2870. if (match) filename = match[1].trim();
  2871. }
  2872. const blob = await response.blob();
  2873. return { blob, filename };
  2874. },
  2875. importBackup: async (file: File) => {
  2876. // New simplified restore - replaces database + all directories
  2877. const formData = new FormData();
  2878. formData.append('file', file);
  2879. const url = `${API_BASE}/settings/restore`;
  2880. const headers: Record<string, string> = {};
  2881. if (authToken) {
  2882. headers['Authorization'] = `Bearer ${authToken}`;
  2883. }
  2884. const response = await fetch(url, {
  2885. method: 'POST',
  2886. headers,
  2887. body: formData,
  2888. });
  2889. return response.json() as Promise<{
  2890. success: boolean;
  2891. message: string;
  2892. }>;
  2893. },
  2894. checkFfmpeg: () =>
  2895. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  2896. getNetworkInterfaces: () =>
  2897. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  2898. // Cloud
  2899. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  2900. cloudLogin: (email: string, password: string, region = 'global') =>
  2901. request<CloudLoginResponse>('/cloud/login', {
  2902. method: 'POST',
  2903. body: JSON.stringify({ email, password, region }),
  2904. }),
  2905. cloudVerify: (email: string, code: string, tfaKey?: string) =>
  2906. request<CloudLoginResponse>('/cloud/verify', {
  2907. method: 'POST',
  2908. body: JSON.stringify({ email, code, tfa_key: tfaKey }),
  2909. }),
  2910. cloudSetToken: (access_token: string) =>
  2911. request<CloudAuthStatus>('/cloud/token', {
  2912. method: 'POST',
  2913. body: JSON.stringify({ access_token }),
  2914. }),
  2915. cloudLogout: () =>
  2916. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  2917. getCloudSettings: (version = '02.04.00.70') =>
  2918. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  2919. getBuiltinFilaments: () =>
  2920. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  2921. getFilamentIdMap: () =>
  2922. request<Record<string, string>>('/cloud/filament-id-map'),
  2923. getCloudSettingDetail: (settingId: string) =>
  2924. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  2925. createCloudSetting: (data: SlicerSettingCreate) =>
  2926. request<SlicerSettingDetail>('/cloud/settings', {
  2927. method: 'POST',
  2928. body: JSON.stringify(data),
  2929. }),
  2930. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  2931. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  2932. method: 'PUT',
  2933. body: JSON.stringify(data),
  2934. }),
  2935. deleteCloudSetting: (settingId: string) =>
  2936. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  2937. method: 'DELETE',
  2938. }),
  2939. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  2940. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  2941. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  2942. getAllCloudFields: () =>
  2943. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  2944. getFilamentInfo: (settingIds: string[]) =>
  2945. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  2946. method: 'POST',
  2947. body: JSON.stringify(settingIds),
  2948. }),
  2949. // Smart Plugs
  2950. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  2951. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  2952. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  2953. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  2954. createSmartPlug: (data: SmartPlugCreate) =>
  2955. request<SmartPlug>('/smart-plugs/', {
  2956. method: 'POST',
  2957. body: JSON.stringify(data),
  2958. }),
  2959. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  2960. request<SmartPlug>(`/smart-plugs/${id}`, {
  2961. method: 'PATCH',
  2962. body: JSON.stringify(data),
  2963. }),
  2964. deleteSmartPlug: (id: number) =>
  2965. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  2966. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  2967. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  2968. method: 'POST',
  2969. body: JSON.stringify({ action }),
  2970. }),
  2971. getSmartPlugStatus: (id: number) =>
  2972. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  2973. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  2974. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  2975. method: 'POST',
  2976. body: JSON.stringify({ ip_address, username, password }),
  2977. }),
  2978. // Tasmota Discovery (auto-detects network)
  2979. startTasmotaScan: () =>
  2980. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  2981. getTasmotaScanStatus: () =>
  2982. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  2983. stopTasmotaScan: () =>
  2984. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  2985. getDiscoveredTasmotaDevices: () =>
  2986. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  2987. // Home Assistant Integration
  2988. testHAConnection: (url: string, token: string) =>
  2989. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  2990. method: 'POST',
  2991. body: JSON.stringify({ url, token }),
  2992. }),
  2993. getHAEntities: (search?: string) => {
  2994. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  2995. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  2996. },
  2997. getHASensorEntities: () =>
  2998. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  2999. // Print Queue
  3000. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  3001. const params = new URLSearchParams();
  3002. if (printerId) params.set('printer_id', String(printerId));
  3003. if (status) params.set('status', status);
  3004. if (targetModel) params.set('target_model', targetModel);
  3005. return request<PrintQueueItem[]>(`/queue/?${params}`);
  3006. },
  3007. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  3008. addToQueue: (data: PrintQueueItemCreate) =>
  3009. request<PrintQueueItem>('/queue/', {
  3010. method: 'POST',
  3011. body: JSON.stringify(data),
  3012. }),
  3013. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  3014. request<PrintQueueItem>(`/queue/${id}`, {
  3015. method: 'PATCH',
  3016. body: JSON.stringify(data),
  3017. }),
  3018. removeFromQueue: (id: number) =>
  3019. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  3020. reorderQueue: (items: { id: number; position: number }[]) =>
  3021. request<{ message: string }>('/queue/reorder', {
  3022. method: 'POST',
  3023. body: JSON.stringify({ items }),
  3024. }),
  3025. cancelQueueItem: (id: number) =>
  3026. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  3027. stopQueueItem: (id: number) =>
  3028. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  3029. startQueueItem: (id: number) =>
  3030. request<PrintQueueItem>(`/queue/${id}/start`, { method: 'POST' }),
  3031. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  3032. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  3033. method: 'PATCH',
  3034. body: JSON.stringify(data),
  3035. }),
  3036. // K-Profiles
  3037. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  3038. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  3039. setKProfile: (printerId: number, profile: KProfileCreate) =>
  3040. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  3041. method: 'POST',
  3042. body: JSON.stringify(profile),
  3043. }),
  3044. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  3045. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  3046. method: 'DELETE',
  3047. body: JSON.stringify(profile),
  3048. }),
  3049. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  3050. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  3051. method: 'POST',
  3052. body: JSON.stringify(profiles),
  3053. }),
  3054. // K-Profile Notes (stored locally, not on printer)
  3055. getKProfileNotes: (printerId: number) =>
  3056. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  3057. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  3058. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  3059. method: 'PUT',
  3060. body: JSON.stringify({ setting_id: settingId, note }),
  3061. }),
  3062. deleteKProfileNote: (printerId: number, settingId: string) =>
  3063. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  3064. method: 'DELETE',
  3065. }),
  3066. // Slot Preset Mappings
  3067. getSlotPresets: (printerId: number) =>
  3068. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  3069. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  3070. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  3071. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  3072. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  3073. method: 'PUT',
  3074. }),
  3075. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  3076. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  3077. method: 'DELETE',
  3078. }),
  3079. configureAmsSlot: (
  3080. printerId: number,
  3081. amsId: number,
  3082. trayId: number,
  3083. config: {
  3084. tray_info_idx: string;
  3085. tray_type: string;
  3086. tray_sub_brands: string;
  3087. tray_color: string;
  3088. nozzle_temp_min: number;
  3089. nozzle_temp_max: number;
  3090. cali_idx: number;
  3091. nozzle_diameter: string;
  3092. setting_id?: string;
  3093. kprofile_filament_id?: string;
  3094. kprofile_setting_id?: string;
  3095. k_value?: number;
  3096. }
  3097. ) => {
  3098. const params = new URLSearchParams({
  3099. tray_info_idx: config.tray_info_idx,
  3100. tray_type: config.tray_type,
  3101. tray_sub_brands: config.tray_sub_brands,
  3102. tray_color: config.tray_color,
  3103. nozzle_temp_min: config.nozzle_temp_min.toString(),
  3104. nozzle_temp_max: config.nozzle_temp_max.toString(),
  3105. cali_idx: config.cali_idx.toString(),
  3106. nozzle_diameter: config.nozzle_diameter,
  3107. });
  3108. if (config.setting_id) {
  3109. params.set('setting_id', config.setting_id);
  3110. }
  3111. if (config.kprofile_filament_id) {
  3112. params.set('kprofile_filament_id', config.kprofile_filament_id);
  3113. }
  3114. if (config.kprofile_setting_id) {
  3115. params.set('kprofile_setting_id', config.kprofile_setting_id);
  3116. }
  3117. if (config.k_value !== undefined && config.k_value > 0) {
  3118. params.set('k_value', config.k_value.toString());
  3119. }
  3120. return request<{ success: boolean; message: string }>(
  3121. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  3122. { method: 'POST' }
  3123. );
  3124. },
  3125. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  3126. request<{ success: boolean; message: string }>(
  3127. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  3128. { method: 'POST' }
  3129. ),
  3130. // Filament Catalog (material types with cost/temp data)
  3131. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  3132. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  3133. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  3134. // Notification Providers
  3135. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  3136. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  3137. createNotificationProvider: (data: NotificationProviderCreate) =>
  3138. request<NotificationProvider>('/notifications/', {
  3139. method: 'POST',
  3140. body: JSON.stringify(data),
  3141. }),
  3142. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  3143. request<NotificationProvider>(`/notifications/${id}`, {
  3144. method: 'PATCH',
  3145. body: JSON.stringify(data),
  3146. }),
  3147. deleteNotificationProvider: (id: number) =>
  3148. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  3149. testNotificationProvider: (id: number) =>
  3150. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  3151. testNotificationConfig: (data: NotificationTestRequest) =>
  3152. request<NotificationTestResponse>('/notifications/test-config', {
  3153. method: 'POST',
  3154. body: JSON.stringify(data),
  3155. }),
  3156. testAllNotificationProviders: () =>
  3157. request<{
  3158. tested: number;
  3159. success: number;
  3160. failed: number;
  3161. results: Array<{
  3162. provider_id: number;
  3163. provider_name: string;
  3164. provider_type: string;
  3165. success: boolean;
  3166. message: string;
  3167. }>;
  3168. }>('/notifications/test-all', { method: 'POST' }),
  3169. // Notification Templates
  3170. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  3171. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  3172. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  3173. request<NotificationTemplate>(`/notification-templates/${id}`, {
  3174. method: 'PUT',
  3175. body: JSON.stringify(data),
  3176. }),
  3177. resetNotificationTemplate: (id: number) =>
  3178. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  3179. method: 'POST',
  3180. }),
  3181. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  3182. previewTemplate: (data: TemplatePreviewRequest) =>
  3183. request<TemplatePreviewResponse>('/notification-templates/preview', {
  3184. method: 'POST',
  3185. body: JSON.stringify(data),
  3186. }),
  3187. // Notification Logs
  3188. getNotificationLogs: (params?: {
  3189. limit?: number;
  3190. offset?: number;
  3191. provider_id?: number;
  3192. event_type?: string;
  3193. success?: boolean;
  3194. days?: number;
  3195. }) => {
  3196. const searchParams = new URLSearchParams();
  3197. if (params?.limit) searchParams.set('limit', String(params.limit));
  3198. if (params?.offset) searchParams.set('offset', String(params.offset));
  3199. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  3200. if (params?.event_type) searchParams.set('event_type', params.event_type);
  3201. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  3202. if (params?.days) searchParams.set('days', String(params.days));
  3203. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  3204. },
  3205. getNotificationLogStats: (days = 7) =>
  3206. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  3207. clearNotificationLogs: (olderThanDays = 30) =>
  3208. request<{ deleted: number; message: string }>(
  3209. `/notifications/logs?older_than_days=${olderThanDays}`,
  3210. { method: 'DELETE' }
  3211. ),
  3212. // Spoolman Integration
  3213. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  3214. connectSpoolman: () =>
  3215. request<{ success: boolean; message: string }>('/spoolman/connect', {
  3216. method: 'POST',
  3217. }),
  3218. disconnectSpoolman: () =>
  3219. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  3220. method: 'POST',
  3221. }),
  3222. syncPrinterAms: (printerId: number) =>
  3223. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  3224. method: 'POST',
  3225. }),
  3226. syncAllPrintersAms: () =>
  3227. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  3228. method: 'POST',
  3229. }),
  3230. getSpoolmanSpools: () =>
  3231. request<{ spools: unknown[] }>('/spoolman/spools'),
  3232. getSpoolmanFilaments: () =>
  3233. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  3234. getUnlinkedSpools: () =>
  3235. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  3236. getLinkedSpools: () =>
  3237. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  3238. linkSpool: (spoolId: number, trayUuid: string) =>
  3239. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  3240. method: 'POST',
  3241. body: JSON.stringify({ tray_uuid: trayUuid }),
  3242. }),
  3243. getSpoolmanSettings: () =>
  3244. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman'),
  3245. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; }) =>
  3246. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman', {
  3247. method: 'PUT',
  3248. body: JSON.stringify(data),
  3249. }),
  3250. // Inventory
  3251. getSpools: (includeArchived = false) =>
  3252. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  3253. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  3254. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  3255. request<InventorySpool>('/inventory/spools', {
  3256. method: 'POST',
  3257. body: JSON.stringify(data),
  3258. }),
  3259. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  3260. request<InventorySpool[]>('/inventory/spools/bulk', {
  3261. method: 'POST',
  3262. body: JSON.stringify({ spool: data, quantity }),
  3263. }),
  3264. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  3265. request<InventorySpool>(`/inventory/spools/${id}`, {
  3266. method: 'PATCH',
  3267. body: JSON.stringify(data),
  3268. }),
  3269. deleteSpool: (id: number) =>
  3270. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  3271. archiveSpool: (id: number) =>
  3272. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  3273. restoreSpool: (id: number) =>
  3274. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  3275. getSpoolKProfiles: (spoolId: number) =>
  3276. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  3277. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  3278. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  3279. method: 'PUT',
  3280. body: JSON.stringify(profiles),
  3281. }),
  3282. getAssignments: (printerId?: number) =>
  3283. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  3284. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  3285. request<SpoolAssignment>('/inventory/assignments', {
  3286. method: 'POST',
  3287. body: JSON.stringify(data),
  3288. }),
  3289. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  3290. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  3291. getSpoolCatalog: () =>
  3292. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  3293. addCatalogEntry: (data: { name: string; weight: number }) =>
  3294. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  3295. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  3296. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  3297. deleteCatalogEntry: (id: number) =>
  3298. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  3299. resetSpoolCatalog: () =>
  3300. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  3301. getColorCatalog: () =>
  3302. request<ColorCatalogEntry[]>('/inventory/colors'),
  3303. addColorEntry: (data: { manufacturer: string; color_name: string; hex_color: string; material: string | null }) =>
  3304. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  3305. updateColorEntry: (id: number, data: { manufacturer: string; color_name: string; hex_color: string; material: string | null }) =>
  3306. request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  3307. deleteColorEntry: (id: number) =>
  3308. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  3309. resetColorCatalog: () =>
  3310. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  3311. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  3312. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  3313. searchColors: (manufacturer?: string, material?: string) =>
  3314. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  3315. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  3316. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  3317. method: 'PATCH',
  3318. body: JSON.stringify(data),
  3319. }),
  3320. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  3321. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  3322. getAllUsageHistory: (limit = 100, printerId?: number) =>
  3323. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  3324. clearSpoolUsageHistory: (spoolId: number) =>
  3325. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  3326. syncWeightsFromAms: () =>
  3327. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  3328. getFilamentPresets: () =>
  3329. request<SlicerSetting[]>('/cloud/filaments'),
  3330. // Updates
  3331. getVersion: () => request<VersionInfo>('/updates/version'),
  3332. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  3333. applyUpdate: () =>
  3334. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean }>('/updates/apply', {
  3335. method: 'POST',
  3336. }),
  3337. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  3338. // Maintenance
  3339. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  3340. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  3341. request<MaintenanceType>('/maintenance/types', {
  3342. method: 'POST',
  3343. body: JSON.stringify(data),
  3344. }),
  3345. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  3346. request<MaintenanceType>(`/maintenance/types/${id}`, {
  3347. method: 'PATCH',
  3348. body: JSON.stringify(data),
  3349. }),
  3350. deleteMaintenanceType: (id: number) =>
  3351. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  3352. restoreDefaultMaintenanceTypes: () =>
  3353. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  3354. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  3355. getPrinterMaintenance: (printerId: number) =>
  3356. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  3357. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  3358. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  3359. method: 'PATCH',
  3360. body: JSON.stringify(data),
  3361. }),
  3362. performMaintenance: (itemId: number, notes?: string) =>
  3363. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  3364. method: 'POST',
  3365. body: JSON.stringify({ notes }),
  3366. }),
  3367. getMaintenanceHistory: (itemId: number) =>
  3368. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  3369. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  3370. setPrinterHours: (printerId: number, totalHours: number) =>
  3371. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  3372. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  3373. { method: 'PATCH' }
  3374. ),
  3375. assignMaintenanceType: (printerId: number, typeId: number) =>
  3376. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  3377. method: 'POST',
  3378. }),
  3379. removeMaintenanceItem: (itemId: number) =>
  3380. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  3381. method: 'DELETE',
  3382. }),
  3383. // Camera
  3384. getCameraStreamUrl: (printerId: number, fps = 10) =>
  3385. `${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`,
  3386. getCameraSnapshotUrl: (printerId: number) =>
  3387. `${API_BASE}/printers/${printerId}/camera/snapshot`,
  3388. testCameraConnection: (printerId: number) =>
  3389. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  3390. getCameraStatus: (printerId: number) =>
  3391. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  3392. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  3393. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  3394. const params = new URLSearchParams();
  3395. params.set('use_external', String(options?.useExternal ?? false));
  3396. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  3397. return request<PlateDetectionResult>(
  3398. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  3399. );
  3400. },
  3401. getPlateDetectionStatus: (printerId: number) => {
  3402. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  3403. `/printers/${printerId}/camera/plate-detection/status`
  3404. );
  3405. },
  3406. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  3407. const params = new URLSearchParams();
  3408. if (options?.label) params.set('label', options.label);
  3409. params.set('use_external', String(options?.useExternal ?? false));
  3410. return request<CalibrationResult & { index: number }>(
  3411. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  3412. { method: 'POST' }
  3413. );
  3414. },
  3415. deletePlateCalibration: (printerId: number) => {
  3416. return request<CalibrationResult>(
  3417. `/printers/${printerId}/camera/plate-detection/calibrate`,
  3418. { method: 'DELETE' }
  3419. );
  3420. },
  3421. getPlateReferences: (printerId: number) => {
  3422. return request<{
  3423. references: PlateReference[];
  3424. max_references: number;
  3425. }>(`/printers/${printerId}/camera/plate-detection/references`);
  3426. },
  3427. getPlateReferenceThumbnailUrl: (printerId: number, index: number) => {
  3428. return `${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`;
  3429. },
  3430. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  3431. const params = new URLSearchParams();
  3432. params.set('label', label);
  3433. return request<{ success: boolean; index: number; label: string }>(
  3434. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  3435. { method: 'PUT' }
  3436. );
  3437. },
  3438. deletePlateReference: (printerId: number, index: number) => {
  3439. return request<{ success: boolean; message: string }>(
  3440. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  3441. { method: 'DELETE' }
  3442. );
  3443. },
  3444. // External Links
  3445. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  3446. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  3447. createExternalLink: (data: ExternalLinkCreate) =>
  3448. request<ExternalLink>('/external-links/', {
  3449. method: 'POST',
  3450. body: JSON.stringify(data),
  3451. }),
  3452. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  3453. request<ExternalLink>(`/external-links/${id}`, {
  3454. method: 'PATCH',
  3455. body: JSON.stringify(data),
  3456. }),
  3457. deleteExternalLink: (id: number) =>
  3458. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  3459. reorderExternalLinks: (ids: number[]) =>
  3460. request<ExternalLink[]>('/external-links/reorder', {
  3461. method: 'PUT',
  3462. body: JSON.stringify({ ids }),
  3463. }),
  3464. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  3465. const formData = new FormData();
  3466. formData.append('file', file);
  3467. const headers: Record<string, string> = {};
  3468. if (authToken) {
  3469. headers['Authorization'] = `Bearer ${authToken}`;
  3470. }
  3471. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  3472. method: 'POST',
  3473. headers,
  3474. body: formData,
  3475. });
  3476. if (!response.ok) {
  3477. const error = await response.json().catch(() => ({}));
  3478. throw new Error(error.detail || `HTTP ${response.status}`);
  3479. }
  3480. return response.json();
  3481. },
  3482. deleteExternalLinkIcon: (id: number) =>
  3483. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  3484. getExternalLinkIconUrl: (id: number) => `${API_BASE}/external-links/${id}/icon`,
  3485. // Projects
  3486. getProjects: (status?: string) => {
  3487. const params = new URLSearchParams();
  3488. if (status) params.set('status', status);
  3489. return request<ProjectListItem[]>(`/projects/?${params}`);
  3490. },
  3491. getProject: (id: number) => request<Project>(`/projects/${id}`),
  3492. createProject: (data: ProjectCreate) =>
  3493. request<Project>('/projects/', {
  3494. method: 'POST',
  3495. body: JSON.stringify(data),
  3496. }),
  3497. updateProject: (id: number, data: ProjectUpdate) =>
  3498. request<Project>(`/projects/${id}`, {
  3499. method: 'PATCH',
  3500. body: JSON.stringify(data),
  3501. }),
  3502. deleteProject: (id: number) =>
  3503. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  3504. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  3505. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  3506. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  3507. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  3508. method: 'POST',
  3509. body: JSON.stringify({ archive_ids: archiveIds }),
  3510. }),
  3511. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  3512. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  3513. method: 'POST',
  3514. body: JSON.stringify({ archive_ids: archiveIds }),
  3515. }),
  3516. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  3517. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  3518. method: 'POST',
  3519. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  3520. }),
  3521. // Project Attachments
  3522. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  3523. status: string;
  3524. filename: string;
  3525. original_name: string;
  3526. attachments: ProjectAttachment[];
  3527. }> => {
  3528. const formData = new FormData();
  3529. formData.append('file', file);
  3530. const headers: Record<string, string> = {};
  3531. if (authToken) {
  3532. headers['Authorization'] = `Bearer ${authToken}`;
  3533. }
  3534. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  3535. method: 'POST',
  3536. headers,
  3537. body: formData,
  3538. });
  3539. if (!response.ok) {
  3540. const error = await response.json().catch(() => ({}));
  3541. throw new Error(error.detail || `HTTP ${response.status}`);
  3542. }
  3543. return response.json();
  3544. },
  3545. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  3546. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  3547. deleteProjectAttachment: (projectId: number, filename: string) =>
  3548. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  3549. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  3550. { method: 'DELETE' }
  3551. ),
  3552. // BOM (Bill of Materials)
  3553. getProjectBOM: (projectId: number) =>
  3554. request<BOMItem[]>(`/projects/${projectId}/bom`),
  3555. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  3556. request<BOMItem>(`/projects/${projectId}/bom`, {
  3557. method: 'POST',
  3558. body: JSON.stringify(data),
  3559. }),
  3560. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  3561. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  3562. method: 'PATCH',
  3563. body: JSON.stringify(data),
  3564. }),
  3565. deleteBOMItem: (projectId: number, itemId: number) =>
  3566. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  3567. method: 'DELETE',
  3568. }),
  3569. // Templates
  3570. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  3571. createTemplateFromProject: (projectId: number) =>
  3572. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  3573. createProjectFromTemplate: (templateId: number, name?: string) =>
  3574. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  3575. method: 'POST',
  3576. }),
  3577. // Timeline
  3578. getProjectTimeline: (projectId: number, limit = 50) =>
  3579. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  3580. // Project Export/Import
  3581. exportProjectJson: (projectId: number) =>
  3582. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  3583. importProject: (data: ProjectImport) =>
  3584. request<Project>('/projects/import', {
  3585. method: 'POST',
  3586. body: JSON.stringify(data),
  3587. }),
  3588. importProjectFile: async (file: File): Promise<Project> => {
  3589. const formData = new FormData();
  3590. formData.append('file', file);
  3591. const headers: Record<string, string> = {};
  3592. if (authToken) {
  3593. headers['Authorization'] = `Bearer ${authToken}`;
  3594. }
  3595. const response = await fetch(`${API_BASE}/projects/import/file`, {
  3596. method: 'POST',
  3597. headers,
  3598. body: formData,
  3599. });
  3600. if (!response.ok) {
  3601. const error = await response.json().catch(() => ({}));
  3602. throw new Error(error.detail || `HTTP ${response.status}`);
  3603. }
  3604. return response.json();
  3605. },
  3606. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  3607. const headers: Record<string, string> = {};
  3608. if (authToken) {
  3609. headers['Authorization'] = `Bearer ${authToken}`;
  3610. }
  3611. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  3612. headers,
  3613. });
  3614. if (!response.ok) {
  3615. const error = await response.json().catch(() => ({}));
  3616. throw new Error(error.detail || `HTTP ${response.status}`);
  3617. }
  3618. const contentDisposition = response.headers.get('Content-Disposition');
  3619. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  3620. const blob = await response.blob();
  3621. return { blob, filename };
  3622. },
  3623. // API Keys
  3624. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  3625. createAPIKey: (data: APIKeyCreate) =>
  3626. request<APIKeyCreateResponse>('/api-keys/', {
  3627. method: 'POST',
  3628. body: JSON.stringify(data),
  3629. }),
  3630. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  3631. request<APIKey>(`/api-keys/${id}`, {
  3632. method: 'PATCH',
  3633. body: JSON.stringify(data),
  3634. }),
  3635. deleteAPIKey: (id: number) =>
  3636. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  3637. // AMS History
  3638. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  3639. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  3640. // System Info
  3641. getSystemInfo: () => request<SystemInfo>('/system/info'),
  3642. getStorageUsage: (options?: { refresh?: boolean }) => {
  3643. const params = new URLSearchParams();
  3644. if (options?.refresh) {
  3645. params.set('refresh', 'true');
  3646. }
  3647. const query = params.toString();
  3648. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  3649. },
  3650. // Library (File Manager)
  3651. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  3652. createLibraryFolder: (data: LibraryFolderCreate) =>
  3653. request<LibraryFolder>('/library/folders', {
  3654. method: 'POST',
  3655. body: JSON.stringify(data),
  3656. }),
  3657. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  3658. request<LibraryFolder>(`/library/folders/${id}`, {
  3659. method: 'PUT',
  3660. body: JSON.stringify(data),
  3661. }),
  3662. deleteLibraryFolder: (id: number) =>
  3663. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  3664. getLibraryFoldersByProject: (projectId: number) =>
  3665. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  3666. getLibraryFoldersByArchive: (archiveId: number) =>
  3667. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  3668. getLibraryFiles: (folderId?: number | null, includeRoot = true) => {
  3669. const params = new URLSearchParams();
  3670. if (folderId !== undefined && folderId !== null) {
  3671. params.set('folder_id', String(folderId));
  3672. }
  3673. params.set('include_root', String(includeRoot));
  3674. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  3675. },
  3676. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  3677. uploadLibraryFile: async (
  3678. file: File,
  3679. folderId?: number | null,
  3680. generateStlThumbnails: boolean = true
  3681. ): Promise<LibraryFileUploadResponse> => {
  3682. const formData = new FormData();
  3683. formData.append('file', file);
  3684. const params = new URLSearchParams();
  3685. if (folderId) params.set('folder_id', String(folderId));
  3686. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  3687. const headers: Record<string, string> = {};
  3688. if (authToken) {
  3689. headers['Authorization'] = `Bearer ${authToken}`;
  3690. }
  3691. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  3692. method: 'POST',
  3693. headers,
  3694. body: formData,
  3695. });
  3696. if (!response.ok) {
  3697. const error = await response.json().catch(() => ({}));
  3698. throw new Error(error.detail || `HTTP ${response.status}`);
  3699. }
  3700. return response.json();
  3701. },
  3702. extractZipFile: async (
  3703. file: File,
  3704. folderId?: number | null,
  3705. preserveStructure: boolean = true,
  3706. createFolderFromZip: boolean = false,
  3707. generateStlThumbnails: boolean = true
  3708. ): Promise<ZipExtractResponse> => {
  3709. const formData = new FormData();
  3710. formData.append('file', file);
  3711. const params = new URLSearchParams();
  3712. if (folderId) params.set('folder_id', String(folderId));
  3713. params.set('preserve_structure', String(preserveStructure));
  3714. params.set('create_folder_from_zip', String(createFolderFromZip));
  3715. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  3716. const headers: Record<string, string> = {};
  3717. if (authToken) {
  3718. headers['Authorization'] = `Bearer ${authToken}`;
  3719. }
  3720. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  3721. method: 'POST',
  3722. headers,
  3723. body: formData,
  3724. });
  3725. if (!response.ok) {
  3726. const error = await response.json().catch(() => ({}));
  3727. throw new Error(error.detail || `HTTP ${response.status}`);
  3728. }
  3729. return response.json();
  3730. },
  3731. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  3732. request<LibraryFile>(`/library/files/${id}`, {
  3733. method: 'PUT',
  3734. body: JSON.stringify(data),
  3735. }),
  3736. deleteLibraryFile: (id: number) =>
  3737. request<{ status: string; message: string }>(`/library/files/${id}`, { method: 'DELETE' }),
  3738. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  3739. createLibrarySlicerToken: (fileId: number) =>
  3740. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  3741. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  3742. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(filename)}`,
  3743. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  3744. const headers: Record<string, string> = {};
  3745. if (authToken) {
  3746. headers['Authorization'] = `Bearer ${authToken}`;
  3747. }
  3748. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  3749. if (!response.ok) {
  3750. const error = await response.json().catch(() => ({}));
  3751. throw new Error(error.detail || `HTTP ${response.status}`);
  3752. }
  3753. const disposition = response.headers.get('Content-Disposition');
  3754. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  3755. const blob = await response.blob();
  3756. const url = window.URL.createObjectURL(blob);
  3757. const a = document.createElement('a');
  3758. a.href = url;
  3759. a.download = downloadFilename;
  3760. document.body.appendChild(a);
  3761. a.click();
  3762. document.body.removeChild(a);
  3763. window.URL.revokeObjectURL(url);
  3764. },
  3765. getLibraryFileThumbnailUrl: (id: number) => `${API_BASE}/library/files/${id}/thumbnail`,
  3766. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  3767. `${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`,
  3768. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  3769. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  3770. request<{ status: string; moved: number }>('/library/files/move', {
  3771. method: 'POST',
  3772. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  3773. }),
  3774. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  3775. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  3776. method: 'POST',
  3777. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  3778. }),
  3779. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  3780. batchGenerateStlThumbnails: (options: {
  3781. file_ids?: number[];
  3782. folder_id?: number;
  3783. all_missing?: boolean;
  3784. }) =>
  3785. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  3786. method: 'POST',
  3787. body: JSON.stringify(options),
  3788. }),
  3789. addLibraryFilesToQueue: (fileIds: number[]) =>
  3790. request<AddToQueueResponse>('/library/files/add-to-queue', {
  3791. method: 'POST',
  3792. body: JSON.stringify({ file_ids: fileIds }),
  3793. }),
  3794. printLibraryFile: (
  3795. fileId: number,
  3796. printerId: number,
  3797. options?: {
  3798. plate_id?: number;
  3799. plate_name?: string;
  3800. ams_mapping?: number[];
  3801. bed_levelling?: boolean;
  3802. flow_cali?: boolean;
  3803. vibration_cali?: boolean;
  3804. layer_inspect?: boolean;
  3805. timelapse?: boolean;
  3806. use_ams?: boolean;
  3807. }
  3808. ) =>
  3809. request<BackgroundDispatchResponse>(
  3810. `/library/files/${fileId}/print?printer_id=${printerId}`,
  3811. {
  3812. method: 'POST',
  3813. body: options ? JSON.stringify(options) : undefined,
  3814. }
  3815. ),
  3816. cancelBackgroundDispatchJob: (jobId: number) =>
  3817. request<{
  3818. status: 'cancelled' | 'cancelling';
  3819. job_id: number;
  3820. source_name: string;
  3821. printer_id: number;
  3822. printer_name: string;
  3823. }>(`/background-dispatch/${jobId}`, {
  3824. method: 'DELETE',
  3825. }),
  3826. getLibraryFilePlates: (fileId: number) =>
  3827. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  3828. getLibraryFileFilamentRequirements: (fileId: number, plateId?: number) =>
  3829. request<{
  3830. file_id: number;
  3831. filename: string;
  3832. filaments: Array<{
  3833. slot_id: number;
  3834. type: string;
  3835. color: string;
  3836. used_grams: number;
  3837. used_meters: number;
  3838. }>;
  3839. }>(`/library/files/${fileId}/filament-requirements${plateId !== undefined ? `?plate_id=${plateId}` : ''}`),
  3840. // GitHub Backup
  3841. getGitHubBackupConfig: () =>
  3842. request<GitHubBackupConfig | null>('/github-backup/config'),
  3843. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  3844. request<GitHubBackupConfig>('/github-backup/config', {
  3845. method: 'POST',
  3846. body: JSON.stringify(config),
  3847. }),
  3848. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  3849. request<GitHubBackupConfig>('/github-backup/config', {
  3850. method: 'PATCH',
  3851. body: JSON.stringify(config),
  3852. }),
  3853. deleteGitHubBackupConfig: () =>
  3854. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  3855. testGitHubConnection: (repoUrl: string, token: string) =>
  3856. request<GitHubTestConnectionResponse>(
  3857. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}`,
  3858. { method: 'POST' }
  3859. ),
  3860. testGitHubStoredConnection: () =>
  3861. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  3862. triggerGitHubBackup: () =>
  3863. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  3864. getGitHubBackupStatus: () =>
  3865. request<GitHubBackupStatus>('/github-backup/status'),
  3866. getGitHubBackupLogs: (limit: number = 50) =>
  3867. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  3868. clearGitHubBackupLogs: (keepLast: number = 10) =>
  3869. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  3870. // Local Presets (OrcaSlicer imports)
  3871. getLocalPresets: () =>
  3872. request<LocalPresetsResponse>('/local-presets/'),
  3873. getLocalPresetDetail: (id: number) =>
  3874. request<LocalPresetDetail>(`/local-presets/${id}`),
  3875. importLocalPresets: (formData: FormData) =>
  3876. fetch(`${API_BASE}/local-presets/import`, {
  3877. method: 'POST',
  3878. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  3879. body: formData,
  3880. }).then(async (res) => {
  3881. if (!res.ok) {
  3882. const err = await res.json().catch(() => ({}));
  3883. throw new Error(err.detail || `HTTP ${res.status}`);
  3884. }
  3885. return res.json() as Promise<ImportResponse>;
  3886. }),
  3887. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  3888. request<LocalPreset>('/local-presets/', {
  3889. method: 'POST',
  3890. body: JSON.stringify(data),
  3891. }),
  3892. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  3893. request<LocalPreset>(`/local-presets/${id}`, {
  3894. method: 'PUT',
  3895. body: JSON.stringify(data),
  3896. }),
  3897. deleteLocalPreset: (id: number) =>
  3898. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  3899. refreshBaseProfileCache: () =>
  3900. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  3901. };
  3902. // AMS History types
  3903. export interface AMSHistoryPoint {
  3904. recorded_at: string;
  3905. humidity: number | null;
  3906. humidity_raw: number | null;
  3907. temperature: number | null;
  3908. }
  3909. export interface AMSHistoryResponse {
  3910. printer_id: number;
  3911. ams_id: number;
  3912. data: AMSHistoryPoint[];
  3913. min_humidity: number | null;
  3914. max_humidity: number | null;
  3915. avg_humidity: number | null;
  3916. min_temperature: number | null;
  3917. max_temperature: number | null;
  3918. avg_temperature: number | null;
  3919. }
  3920. // System Info types
  3921. export interface SystemInfo {
  3922. app: {
  3923. version: string;
  3924. base_dir: string;
  3925. archive_dir: string;
  3926. };
  3927. database: {
  3928. archives: number;
  3929. archives_completed: number;
  3930. archives_failed: number;
  3931. archives_printing: number;
  3932. printers: number;
  3933. filaments: number;
  3934. projects: number;
  3935. smart_plugs: number;
  3936. total_print_time_seconds: number;
  3937. total_print_time_formatted: string;
  3938. total_filament_grams: number;
  3939. total_filament_kg: number;
  3940. };
  3941. printers: {
  3942. total: number;
  3943. connected: number;
  3944. connected_list: Array<{
  3945. id: number;
  3946. name: string;
  3947. state: string;
  3948. model: string;
  3949. }>;
  3950. };
  3951. storage: {
  3952. archive_size_bytes: number;
  3953. archive_size_formatted: string;
  3954. database_size_bytes: number;
  3955. database_size_formatted: string;
  3956. disk_total_bytes: number;
  3957. disk_total_formatted: string;
  3958. disk_used_bytes: number;
  3959. disk_used_formatted: string;
  3960. disk_free_bytes: number;
  3961. disk_free_formatted: string;
  3962. disk_percent_used: number;
  3963. };
  3964. system: {
  3965. platform: string;
  3966. platform_release: string;
  3967. platform_version: string;
  3968. architecture: string;
  3969. hostname: string;
  3970. python_version: string;
  3971. uptime_seconds: number;
  3972. uptime_formatted: string;
  3973. boot_time: string;
  3974. };
  3975. memory: {
  3976. total_bytes: number;
  3977. total_formatted: string;
  3978. available_bytes: number;
  3979. available_formatted: string;
  3980. used_bytes: number;
  3981. used_formatted: string;
  3982. percent_used: number;
  3983. };
  3984. cpu: {
  3985. count: number;
  3986. count_logical: number;
  3987. percent: number;
  3988. };
  3989. }
  3990. export interface StorageUsageCategory {
  3991. key: string;
  3992. label: string;
  3993. bytes: number;
  3994. formatted: string;
  3995. percent_of_total: number;
  3996. }
  3997. export interface StorageUsageOtherItem {
  3998. bucket: string;
  3999. label: string;
  4000. kind: 'system' | 'data';
  4001. deletable: boolean;
  4002. bytes: number;
  4003. formatted: string;
  4004. percent_of_total: number;
  4005. }
  4006. export interface StorageUsageResponse {
  4007. roots: string[];
  4008. total_bytes: number;
  4009. total_formatted: string;
  4010. categories: StorageUsageCategory[];
  4011. other_breakdown: StorageUsageOtherItem[];
  4012. scan_errors: number;
  4013. generated_at: string;
  4014. cache: {
  4015. hit: boolean;
  4016. age_seconds: number;
  4017. max_age_seconds: number;
  4018. };
  4019. }
  4020. // Library (File Manager) types
  4021. export interface LibraryFolderTree {
  4022. id: number;
  4023. name: string;
  4024. parent_id: number | null;
  4025. project_id: number | null;
  4026. archive_id: number | null;
  4027. project_name: string | null;
  4028. archive_name: string | null;
  4029. file_count: number;
  4030. children: LibraryFolderTree[];
  4031. }
  4032. export interface LibraryFolder {
  4033. id: number;
  4034. name: string;
  4035. parent_id: number | null;
  4036. project_id: number | null;
  4037. archive_id: number | null;
  4038. project_name: string | null;
  4039. archive_name: string | null;
  4040. file_count: number;
  4041. created_at: string;
  4042. updated_at: string;
  4043. }
  4044. export interface LibraryFolderCreate {
  4045. name: string;
  4046. parent_id?: number | null;
  4047. project_id?: number | null;
  4048. archive_id?: number | null;
  4049. }
  4050. export interface LibraryFolderUpdate {
  4051. name?: string;
  4052. parent_id?: number | null;
  4053. project_id?: number | null; // 0 to unlink
  4054. archive_id?: number | null; // 0 to unlink
  4055. }
  4056. export interface LibraryFileDuplicate {
  4057. id: number;
  4058. filename: string;
  4059. folder_id: number | null;
  4060. folder_name: string | null;
  4061. created_at: string;
  4062. }
  4063. export interface LibraryFile {
  4064. id: number;
  4065. folder_id: number | null;
  4066. folder_name: string | null;
  4067. project_id: number | null;
  4068. project_name: string | null;
  4069. filename: string;
  4070. file_path: string;
  4071. file_type: string;
  4072. file_size: number;
  4073. file_hash: string | null;
  4074. thumbnail_path: string | null;
  4075. metadata: Record<string, unknown> | null;
  4076. print_count: number;
  4077. last_printed_at: string | null;
  4078. notes: string | null;
  4079. duplicates: LibraryFileDuplicate[] | null;
  4080. duplicate_count: number;
  4081. // User tracking (Issue #206)
  4082. created_by_id: number | null;
  4083. created_by_username: string | null;
  4084. created_at: string;
  4085. updated_at: string;
  4086. // Metadata fields
  4087. print_name: string | null;
  4088. print_time_seconds: number | null;
  4089. filament_used_grams: number | null;
  4090. sliced_for_model: string | null;
  4091. }
  4092. export interface LibraryFileListItem {
  4093. id: number;
  4094. folder_id: number | null;
  4095. filename: string;
  4096. file_type: string;
  4097. file_size: number;
  4098. thumbnail_path: string | null;
  4099. print_count: number;
  4100. duplicate_count: number;
  4101. // User tracking (Issue #206)
  4102. created_by_id: number | null;
  4103. created_by_username: string | null;
  4104. created_at: string;
  4105. print_name: string | null;
  4106. print_time_seconds: number | null;
  4107. filament_used_grams: number | null;
  4108. sliced_for_model: string | null;
  4109. }
  4110. export interface LibraryFileUpdate {
  4111. filename?: string;
  4112. folder_id?: number | null;
  4113. project_id?: number | null;
  4114. notes?: string | null;
  4115. }
  4116. export interface LibraryFileUploadResponse {
  4117. id: number;
  4118. filename: string;
  4119. file_type: string;
  4120. file_size: number;
  4121. thumbnail_path: string | null;
  4122. duplicate_of: number | null;
  4123. metadata: Record<string, unknown> | null;
  4124. }
  4125. export interface LibraryStats {
  4126. total_files: number;
  4127. total_folders: number;
  4128. total_size_bytes: number;
  4129. files_by_type: Record<string, number>;
  4130. total_prints: number;
  4131. disk_free_bytes: number;
  4132. disk_total_bytes: number;
  4133. disk_used_bytes: number;
  4134. }
  4135. export interface ZipExtractResult {
  4136. filename: string;
  4137. file_id: number;
  4138. folder_id: number | null;
  4139. }
  4140. export interface ZipExtractError {
  4141. filename: string;
  4142. error: string;
  4143. }
  4144. export interface ZipExtractResponse {
  4145. extracted: number;
  4146. folders_created: number;
  4147. files: ZipExtractResult[];
  4148. errors: ZipExtractError[];
  4149. }
  4150. // STL Thumbnail Generation types
  4151. export interface BatchThumbnailResult {
  4152. file_id: number;
  4153. filename: string;
  4154. success: boolean;
  4155. error?: string | null;
  4156. }
  4157. export interface BatchThumbnailResponse {
  4158. processed: number;
  4159. succeeded: number;
  4160. failed: number;
  4161. results: BatchThumbnailResult[];
  4162. }
  4163. // Library Queue types
  4164. export interface AddToQueueResult {
  4165. file_id: number;
  4166. filename: string;
  4167. queue_item_id: number;
  4168. archive_id: number;
  4169. }
  4170. export interface AddToQueueError {
  4171. file_id: number;
  4172. filename: string;
  4173. error: string;
  4174. }
  4175. export interface AddToQueueResponse {
  4176. added: AddToQueueResult[];
  4177. errors: AddToQueueError[];
  4178. }
  4179. // Discovery types
  4180. export interface DiscoveredPrinter {
  4181. serial: string;
  4182. name: string;
  4183. ip_address: string;
  4184. model: string | null;
  4185. discovered_at: string | null;
  4186. }
  4187. export interface DiscoveryStatus {
  4188. running: boolean;
  4189. }
  4190. export interface DiscoveryInfo {
  4191. is_docker: boolean;
  4192. ssdp_running: boolean;
  4193. scan_running: boolean;
  4194. subnets: string[];
  4195. }
  4196. export interface SubnetScanStatus {
  4197. running: boolean;
  4198. scanned: number;
  4199. total: number;
  4200. }
  4201. // Discovery API
  4202. export const discoveryApi = {
  4203. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  4204. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  4205. startDiscovery: (duration: number = 10) =>
  4206. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  4207. stopDiscovery: () =>
  4208. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  4209. getDiscoveredPrinters: () =>
  4210. request<DiscoveredPrinter[]>('/discovery/printers'),
  4211. // Subnet scanning (for Docker environments)
  4212. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  4213. request<SubnetScanStatus>('/discovery/scan', {
  4214. method: 'POST',
  4215. body: JSON.stringify({ subnet, timeout }),
  4216. }),
  4217. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  4218. stopSubnetScan: () =>
  4219. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  4220. };
  4221. // Virtual Printer types
  4222. export type VirtualPrinterMode = 'immediate' | 'queue' | 'review' | 'print_queue' | 'proxy'; // 'queue' is legacy, normalized to 'review'
  4223. export interface VirtualPrinterProxyStatus {
  4224. running: boolean;
  4225. target_host: string;
  4226. ftp_port: number;
  4227. mqtt_port: number;
  4228. ftp_connections: number;
  4229. mqtt_connections: number;
  4230. }
  4231. export interface VirtualPrinterStatus {
  4232. enabled: boolean;
  4233. running: boolean;
  4234. mode: VirtualPrinterMode;
  4235. name: string;
  4236. serial: string;
  4237. model: string;
  4238. model_name: string;
  4239. pending_files: number;
  4240. target_printer_ip?: string; // For proxy mode
  4241. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  4242. }
  4243. export interface VirtualPrinterSettings {
  4244. enabled: boolean;
  4245. access_code_set: boolean;
  4246. mode: VirtualPrinterMode;
  4247. model: string;
  4248. target_printer_id: number | null; // For proxy mode
  4249. remote_interface_ip: string | null; // For SSDP proxy across networks
  4250. status: VirtualPrinterStatus;
  4251. }
  4252. export interface NetworkInterface {
  4253. name: string;
  4254. ip: string;
  4255. netmask: string;
  4256. subnet: string;
  4257. is_alias?: boolean;
  4258. label?: string;
  4259. }
  4260. export interface VirtualPrinterModels {
  4261. models: Record<string, string>; // SSDP code -> display name
  4262. default: string;
  4263. }
  4264. export interface PendingUpload {
  4265. id: number;
  4266. filename: string;
  4267. file_size: number;
  4268. source_ip: string | null;
  4269. status: string;
  4270. tags: string | null;
  4271. notes: string | null;
  4272. project_id: number | null;
  4273. uploaded_at: string;
  4274. }
  4275. // Virtual Printer API
  4276. export const virtualPrinterApi = {
  4277. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  4278. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  4279. updateSettings: (data: {
  4280. enabled?: boolean;
  4281. access_code?: string;
  4282. mode?: 'immediate' | 'review' | 'print_queue' | 'proxy';
  4283. model?: string;
  4284. target_printer_id?: number;
  4285. remote_interface_ip?: string;
  4286. }) => {
  4287. const params = new URLSearchParams();
  4288. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  4289. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  4290. if (data.mode !== undefined) params.set('mode', data.mode);
  4291. if (data.model !== undefined) params.set('model', data.model);
  4292. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  4293. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  4294. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  4295. method: 'PUT',
  4296. });
  4297. },
  4298. };
  4299. // Multi Virtual Printer API
  4300. export interface VirtualPrinterConfig {
  4301. id: number;
  4302. name: string;
  4303. enabled: boolean;
  4304. mode: VirtualPrinterMode;
  4305. model: string | null;
  4306. model_name: string | null;
  4307. access_code_set: boolean;
  4308. serial: string;
  4309. target_printer_id: number | null;
  4310. bind_ip: string | null;
  4311. remote_interface_ip: string | null;
  4312. position: number;
  4313. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  4314. }
  4315. export interface VirtualPrinterListResponse {
  4316. printers: VirtualPrinterConfig[];
  4317. models: Record<string, string>;
  4318. }
  4319. export const multiVirtualPrinterApi = {
  4320. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  4321. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  4322. create: (data: {
  4323. name?: string;
  4324. enabled?: boolean;
  4325. mode?: string;
  4326. model?: string;
  4327. access_code?: string;
  4328. target_printer_id?: number;
  4329. bind_ip?: string;
  4330. remote_interface_ip?: string;
  4331. }) =>
  4332. request<VirtualPrinterConfig>('/virtual-printers', {
  4333. method: 'POST',
  4334. body: JSON.stringify(data),
  4335. }),
  4336. update: (id: number, data: {
  4337. name?: string;
  4338. enabled?: boolean;
  4339. mode?: string;
  4340. model?: string;
  4341. access_code?: string;
  4342. target_printer_id?: number;
  4343. bind_ip?: string;
  4344. remote_interface_ip?: string;
  4345. }) =>
  4346. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  4347. method: 'PUT',
  4348. body: JSON.stringify(data),
  4349. }),
  4350. remove: (id: number) =>
  4351. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  4352. method: 'DELETE',
  4353. }),
  4354. };
  4355. // Pending Uploads API
  4356. export const pendingUploadsApi = {
  4357. list: () => request<PendingUpload[]>('/pending-uploads/'),
  4358. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  4359. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  4360. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  4361. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  4362. method: 'POST',
  4363. body: JSON.stringify(data || {}),
  4364. }),
  4365. discard: (id: number) =>
  4366. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  4367. archiveAll: () =>
  4368. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  4369. discardAll: () =>
  4370. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  4371. };
  4372. // Firmware API Types
  4373. export interface FirmwareUpdateInfo {
  4374. printer_id: number;
  4375. printer_name: string;
  4376. model: string | null;
  4377. current_version: string | null;
  4378. latest_version: string | null;
  4379. update_available: boolean;
  4380. download_url: string | null;
  4381. release_notes: string | null;
  4382. }
  4383. export interface FirmwareUploadPrepare {
  4384. can_proceed: boolean;
  4385. sd_card_present: boolean;
  4386. sd_card_free_space: number;
  4387. firmware_size: number;
  4388. space_sufficient: boolean;
  4389. update_available: boolean;
  4390. current_version: string | null;
  4391. latest_version: string | null;
  4392. firmware_filename: string | null;
  4393. errors: string[];
  4394. }
  4395. export interface FirmwareUploadStatus {
  4396. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  4397. progress: number;
  4398. message: string;
  4399. error: string | null;
  4400. firmware_filename: string | null;
  4401. firmware_version: string | null;
  4402. }
  4403. // Firmware API
  4404. export const firmwareApi = {
  4405. checkUpdates: () =>
  4406. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  4407. checkPrinterUpdate: (printerId: number) =>
  4408. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  4409. prepareUpload: (printerId: number) =>
  4410. request<FirmwareUploadPrepare>(`/firmware/updates/${printerId}/prepare`),
  4411. startUpload: (printerId: number) =>
  4412. request<{ started: boolean; message: string }>(`/firmware/updates/${printerId}/upload`, {
  4413. method: 'POST',
  4414. }),
  4415. getUploadStatus: (printerId: number) =>
  4416. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  4417. };
  4418. // Support types
  4419. export interface DebugLoggingState {
  4420. enabled: boolean;
  4421. enabled_at: string | null;
  4422. duration_seconds: number | null;
  4423. }
  4424. export interface LogEntry {
  4425. timestamp: string;
  4426. level: string;
  4427. logger_name: string;
  4428. message: string;
  4429. }
  4430. export interface LogsResponse {
  4431. entries: LogEntry[];
  4432. total_in_file: number;
  4433. filtered_count: number;
  4434. }
  4435. // Support API
  4436. export const supportApi = {
  4437. getDebugLoggingState: () =>
  4438. request<DebugLoggingState>('/support/debug-logging'),
  4439. setDebugLogging: (enabled: boolean) =>
  4440. request<DebugLoggingState>('/support/debug-logging', {
  4441. method: 'POST',
  4442. body: JSON.stringify({ enabled }),
  4443. }),
  4444. downloadSupportBundle: async () => {
  4445. const headers: Record<string, string> = {};
  4446. if (authToken) {
  4447. headers['Authorization'] = `Bearer ${authToken}`;
  4448. }
  4449. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  4450. if (!response.ok) {
  4451. const error = await response.json().catch(() => ({}));
  4452. throw new Error(error.detail || `HTTP ${response.status}`);
  4453. }
  4454. // Get filename from Content-Disposition header or use default
  4455. const disposition = response.headers.get('Content-Disposition');
  4456. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  4457. // Download the blob
  4458. const blob = await response.blob();
  4459. const url = window.URL.createObjectURL(blob);
  4460. const a = document.createElement('a');
  4461. a.href = url;
  4462. a.download = filename;
  4463. document.body.appendChild(a);
  4464. a.click();
  4465. document.body.removeChild(a);
  4466. window.URL.revokeObjectURL(url);
  4467. },
  4468. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  4469. const searchParams = new URLSearchParams();
  4470. if (params?.limit) searchParams.set('limit', params.limit.toString());
  4471. if (params?.level) searchParams.set('level', params.level);
  4472. if (params?.search) searchParams.set('search', params.search);
  4473. const query = searchParams.toString();
  4474. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  4475. },
  4476. clearLogs: () =>
  4477. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  4478. };