client.ts 167 KB

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