client.ts 172 KB

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