client.ts 229 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825
  1. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  2. const API_BASE = '/api/v1';
  3. export class ApiError extends Error {
  4. status: number;
  5. /** Stable error code from a structured backend detail (`{code, message}`).
  6. * Frontend uses this to look up an i18n key instead of showing the raw
  7. * English fallback. Null when the backend returned a plain-string detail. */
  8. code: string | null;
  9. /** Full structured detail object when the backend returned `{code, ...}`
  10. * with additional fields (e.g. the deficit list for 409s on queue
  11. * start, #1496). Null for plain-string or array-shaped details. */
  12. detail: Record<string, unknown> | null;
  13. constructor(
  14. message: string,
  15. status: number,
  16. code: string | null = null,
  17. detail: Record<string, unknown> | null = null,
  18. ) {
  19. super(message);
  20. this.name = 'ApiError';
  21. this.status = status;
  22. this.code = code;
  23. this.detail = detail;
  24. }
  25. }
  26. // Auth token storage
  27. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  28. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  29. // additionally persisted in localStorage so the kiosk survives page reloads.
  30. // 'persistent' also writes to localStorage so the token survives tab close
  31. // (used by Remember Me and the ?token= kiosk bootstrap).
  32. let authToken: string | null =
  33. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  34. export type TokenPersistence = 'session' | 'persistent';
  35. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  36. authToken = token;
  37. try {
  38. if (token) {
  39. sessionStorage.setItem('auth_token', token);
  40. } else {
  41. sessionStorage.removeItem('auth_token');
  42. }
  43. } catch (err) {
  44. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  45. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  46. }
  47. try {
  48. if (!token) {
  49. localStorage.removeItem('auth_token');
  50. } else if (persistence === 'persistent') {
  51. localStorage.setItem('auth_token', token);
  52. }
  53. } catch (err) {
  54. console.warn('setAuthToken: localStorage operation failed', err);
  55. }
  56. }
  57. export function getAuthToken(): string | null {
  58. return authToken;
  59. }
  60. // Stream token for image/video URLs loaded via <img>/<video> tags
  61. // (these can't send Authorization headers, so a query param token is used)
  62. let streamToken: string | null = null;
  63. export function setStreamToken(token: string | null) {
  64. streamToken = token;
  65. }
  66. export function getStreamToken(): string | null {
  67. return streamToken;
  68. }
  69. /** Append the stream token to a URL if available (for <img>/<video> src). */
  70. export function withStreamToken(url: string): string {
  71. if (!streamToken) return url;
  72. const sep = url.includes('?') ? '&' : '?';
  73. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  74. }
  75. function parseContentDispositionFilename(header: string | null): string | null {
  76. if (!header) return null;
  77. // RFC 5987: filename*=utf-8''percent-encoded-name
  78. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  79. if (rfc5987Match) {
  80. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  81. }
  82. // Standard: filename="name" or filename=name
  83. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  84. return standardMatch?.[1] || null;
  85. }
  86. function buildSlicerUrlFilename(filename: string): string {
  87. const safe = filename.replace(/[/\\?#]/g, '_');
  88. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  89. }
  90. async function request<T>(
  91. endpoint: string,
  92. options: RequestInit = {}
  93. ): Promise<T> {
  94. const headers: Record<string, string> = {
  95. 'Content-Type': 'application/json',
  96. ...options.headers as Record<string, string>,
  97. };
  98. // Add auth token if available
  99. if (authToken) {
  100. headers['Authorization'] = `Bearer ${authToken}`;
  101. }
  102. const response = await fetch(`${API_BASE}${endpoint}`, {
  103. ...options,
  104. cache: 'no-store', // Prevent browser caching of API responses
  105. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  106. headers,
  107. });
  108. if (!response.ok) {
  109. const error = await response.json().catch(() => ({}));
  110. const detail = error.detail;
  111. let message: string;
  112. let code: string | null = null;
  113. if (typeof detail === 'string') {
  114. message = detail;
  115. } else if (Array.isArray(detail)) {
  116. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  117. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  118. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  119. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  120. const joined = detail
  121. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  122. .filter(Boolean)
  123. .join('; ');
  124. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  125. } else if (detail && typeof detail === 'object') {
  126. // Structured detail `{code, message, ...}` — frontend uses the code
  127. // to pick an i18n key, message is the English fallback, any extra
  128. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  129. code = typeof detail.code === 'string' ? detail.code : null;
  130. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  131. } else {
  132. message = `HTTP ${response.status}`;
  133. }
  134. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  135. ? (detail as Record<string, unknown>)
  136. : null;
  137. // Handle 401 Unauthorized - only clear token if it's actually invalid
  138. // Don't clear on "Authentication required" which might be a timing issue
  139. if (response.status === 401) {
  140. const invalidTokenMessages = [
  141. 'Could not validate credentials',
  142. 'Token has expired',
  143. 'User not found or inactive',
  144. 'Invalid API key',
  145. 'API key has expired',
  146. ];
  147. if (invalidTokenMessages.some(m => message.includes(m))) {
  148. setAuthToken(null);
  149. }
  150. }
  151. throw new ApiError(message, response.status, code, structuredDetail);
  152. }
  153. // Handle empty responses (204 No Content, etc.)
  154. const contentLength = response.headers.get('content-length');
  155. if (response.status === 204 || contentLength === '0') {
  156. return undefined as T;
  157. }
  158. return await response.json();
  159. }
  160. // Camera diagnostic result (#1395 follow-up). Returned by
  161. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  162. // row per stage and looks up the summary code in i18n for the user-
  163. // facing remediation hint.
  164. export interface CameraDiagnoseStage {
  165. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  166. status: 'ok' | 'failed' | 'skipped';
  167. duration_ms: number;
  168. code: string | null;
  169. }
  170. export interface CameraDiagnoseResult {
  171. printer_id: number;
  172. protocol: 'rtsp' | 'chamber_image';
  173. port: number;
  174. // 'default' = historical X1/H2 tuning. Anything else = this model has
  175. // an override entry in backend/app/services/camera_profiles.py.
  176. profile: string;
  177. overall_status: 'ok' | 'failed';
  178. stages: CameraDiagnoseStage[];
  179. // i18n key under `camera.diagnose.summary.*`.
  180. summary_code: string;
  181. }
  182. // Connection diagnostic (GET /printers/{id}/diagnostic and
  183. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  184. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  185. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  186. export interface DiagnosticCheck {
  187. id:
  188. | 'port_mqtt'
  189. | 'port_ftps'
  190. | 'port_rtsps'
  191. | 'network_mode'
  192. | 'subnet'
  193. | 'mqtt_auth'
  194. | 'developer_mode';
  195. status: DiagnosticStatus;
  196. params: Record<string, string | number>;
  197. }
  198. export interface PrinterDiagnosticResult {
  199. printer_id: number | null;
  200. ip_address: string;
  201. overall: 'ok' | 'warnings' | 'problems';
  202. checks: DiagnosticCheck[];
  203. }
  204. // --- Log-health scan: self-service triage on the System page + bug reporter.
  205. // The backend matches recent logs against a curated known-issue catalog;
  206. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  207. export type LogFindingSeverity = 'error' | 'warning';
  208. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  209. export interface LogFinding {
  210. signature_id: string;
  211. severity: LogFindingSeverity;
  212. category: LogFindingCategory;
  213. wiki_anchor: string;
  214. count: number;
  215. first_seen: string;
  216. last_seen: string;
  217. sample: string;
  218. }
  219. export interface SystemHealthResult {
  220. findings: LogFinding[];
  221. scanned_entries: number;
  222. log_available: boolean;
  223. summary: {
  224. total: number;
  225. layer8: number;
  226. environment: number;
  227. bug: number;
  228. };
  229. }
  230. // Long-lived camera-stream tokens (#1108). The `token` field is populated
  231. // only on the create response — listing endpoints set it to null because
  232. // the plaintext value is shown to the user exactly once.
  233. export interface LongLivedCameraToken {
  234. id: number;
  235. user_id: number;
  236. name: string;
  237. scope: 'camera_stream';
  238. lookup_prefix: string;
  239. created_at: string;
  240. expires_at: string;
  241. last_used_at: string | null;
  242. token: string | null;
  243. }
  244. // Printer types
  245. export interface Printer {
  246. id: number;
  247. name: string;
  248. serial_number: string;
  249. ip_address: string;
  250. access_code: string;
  251. model: string | null;
  252. location: string | null; // Group/location name
  253. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  254. is_active: boolean;
  255. auto_archive: boolean;
  256. external_camera_url: string | null;
  257. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  258. external_camera_enabled: boolean;
  259. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  260. camera_rotation: number; // 0, 90, 180, 270 degrees
  261. plate_detection_enabled: boolean; // Check plate before print
  262. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  263. created_at: string;
  264. updated_at: string;
  265. }
  266. export interface HMSError {
  267. code: string;
  268. attr: number; // Attribute value for constructing wiki URL
  269. module: number;
  270. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  271. }
  272. export interface AMSTray {
  273. id: number;
  274. tray_color: string | null;
  275. tray_type: string | null;
  276. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  277. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  278. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  279. remain: number;
  280. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  281. cali_idx: number | null; // Calibration index for K-profile lookup
  282. tag_uid: string | null; // RFID tag UID (any tag)
  283. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  284. nozzle_temp_min: number | null; // Min nozzle temperature
  285. nozzle_temp_max: number | null; // Max nozzle temperature
  286. drying_temp: number | null; // RFID-recommended drying temp
  287. drying_time: number | null; // RFID-recommended drying time (hours)
  288. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  289. }
  290. export interface AMSUnit {
  291. id: number;
  292. humidity: number | null;
  293. temp: number | null;
  294. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  295. tray: AMSTray[];
  296. serial_number: string; // AMS unit serial number (from MQTT sn field)
  297. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  298. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  299. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  300. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  301. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  302. module_type: string; // "ams", "n3f", "n3s"
  303. }
  304. export interface NozzleInfo {
  305. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  306. nozzle_diameter: string; // e.g., "0.4"
  307. }
  308. export interface NozzleRackSlot {
  309. id: number;
  310. nozzle_type: string;
  311. nozzle_diameter: string;
  312. wear: number | null;
  313. stat: number | null; // Nozzle status (e.g. mounted/docked)
  314. max_temp: number;
  315. serial_number: string;
  316. filament_color: string; // RGBA hex ("00000000" = no filament)
  317. filament_id: string;
  318. filament_type: string; // Material type (e.g. "PLA", "PETG")
  319. }
  320. export interface PrintOptions {
  321. // Core AI detectors
  322. spaghetti_detector: boolean;
  323. print_halt: boolean;
  324. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  325. first_layer_inspector: boolean;
  326. printing_monitor: boolean;
  327. buildplate_marker_detector: boolean;
  328. allow_skip_parts: boolean;
  329. // Additional AI detectors (decoded from cfg bitmask)
  330. nozzle_clumping_detector: boolean;
  331. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  332. pileup_detector: boolean;
  333. pileup_sensitivity: string; // "low", "medium", "high"
  334. airprint_detector: boolean;
  335. airprint_sensitivity: string; // "low", "medium", "high"
  336. auto_recovery_step_loss: boolean;
  337. filament_tangle_detect: boolean;
  338. }
  339. export interface FilaSwitchState {
  340. installed: boolean;
  341. // in[track] = currently loaded slot for that track (-1 = empty)
  342. in_slots: number[];
  343. // out[track] = extruder this track terminates at (0 = right, 1 = left)
  344. out_extruders: number[];
  345. stat: number;
  346. info: number;
  347. }
  348. export interface PrinterStatus {
  349. id: number;
  350. name: string;
  351. connected: boolean;
  352. state: string | null;
  353. current_print: string | null;
  354. subtask_name: string | null;
  355. current_archive_id: number | null;
  356. current_plate_id: number | null;
  357. gcode_file: string | null;
  358. progress: number | null;
  359. remaining_time: number | null;
  360. layer_num: number | null;
  361. total_layers: number | null;
  362. temperatures: {
  363. bed?: number;
  364. bed_target?: number;
  365. bed_heating?: boolean; // Actual heater state from MQTT
  366. nozzle?: number;
  367. nozzle_target?: number;
  368. nozzle_heating?: boolean; // Actual heater state from MQTT
  369. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  370. nozzle_2_target?: number;
  371. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  372. chamber?: number;
  373. chamber_target?: number;
  374. chamber_heating?: boolean; // Actual heater state from MQTT
  375. } | null;
  376. cover_url: string | null;
  377. hms_errors: HMSError[];
  378. ams: AMSUnit[];
  379. ams_exists: boolean;
  380. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  381. store_to_sdcard: boolean; // Store sent files on SD card
  382. timelapse: boolean; // Timelapse recording active
  383. ipcam: boolean; // Live view enabled
  384. wifi_signal: number | null; // WiFi signal strength in dBm
  385. wired_network: boolean; // Ethernet connection detected
  386. door_open: boolean; // Enclosure door open (X1/P1S/P2S/H2*)
  387. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  388. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  389. print_options: PrintOptions | null; // AI detection and print options
  390. // Calibration stage tracking
  391. stg_cur: number; // Current stage number (-1 = not calibrating)
  392. stg_cur_name: string | null; // Human-readable current stage name
  393. stg: number[]; // List of stage numbers in calibration sequence
  394. // Air conditioning mode (0=cooling, 1=heating)
  395. airduct_mode: number;
  396. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  397. speed_level: number;
  398. // Chamber light on/off
  399. chamber_light: boolean;
  400. // Active extruder for dual nozzle (0=right, 1=left)
  401. active_extruder: number;
  402. // AMS mapping - which AMS is connected to which nozzle
  403. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  404. ams_mapping: number[];
  405. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  406. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  407. // Note: JSON keys are always strings
  408. ams_extruder_map: Record<string, number>;
  409. // Filament Track Switch accessory — null when not installed. When present,
  410. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  411. // either extruder, so per-extruder slot filtering must be skipped.
  412. fila_switch: FilaSwitchState | null;
  413. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  414. tray_now: number;
  415. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  416. ams_status_main: number;
  417. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  418. ams_status_sub: number;
  419. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  420. mc_print_sub_stage: number;
  421. // Timestamp of last AMS data update (for RFID refresh detection)
  422. last_ams_update: number;
  423. // Number of printable objects in current print (for skip objects feature)
  424. printable_objects_count: number;
  425. // Fan speeds (0-100 percentage, null if not available for this model)
  426. cooling_fan_speed: number | null; // Part cooling fan
  427. big_fan1_speed: number | null; // Auxiliary fan
  428. big_fan2_speed: number | null; // Chamber/exhaust fan
  429. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  430. firmware_version: string | null; // Firmware version from MQTT
  431. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  432. developer_mode: boolean | null;
  433. // Queue: printer is awaiting user ack that the build plate was cleared after a
  434. // finished/failed print. Persisted across restarts (#961).
  435. awaiting_plate_clear: boolean;
  436. // AMS drying support
  437. supports_drying: boolean;
  438. }
  439. export interface PrinterCreate {
  440. name: string;
  441. serial_number: string;
  442. ip_address: string;
  443. access_code: string;
  444. model?: string;
  445. location?: string;
  446. auto_archive?: boolean;
  447. external_camera_url?: string | null;
  448. external_camera_type?: string | null;
  449. external_camera_enabled?: boolean;
  450. external_camera_snapshot_url?: string | null;
  451. camera_rotation?: number;
  452. plate_detection_enabled?: boolean;
  453. plate_detection_roi?: PlateDetectionROI;
  454. }
  455. // Plate Detection
  456. export interface PlateDetectionROI {
  457. x: number; // X start % (0.0-1.0)
  458. y: number; // Y start % (0.0-1.0)
  459. w: number; // Width % (0.0-1.0)
  460. h: number; // Height % (0.0-1.0)
  461. }
  462. export interface PlateDetectionResult {
  463. is_empty: boolean;
  464. confidence: number;
  465. difference_percent: number;
  466. message: string;
  467. has_debug_image: boolean;
  468. debug_image_url?: string;
  469. needs_calibration: boolean;
  470. light_warning?: boolean;
  471. reference_count?: number;
  472. max_references?: number;
  473. roi?: PlateDetectionROI;
  474. }
  475. export interface PlateDetectionStatus {
  476. available: boolean;
  477. calibrated: boolean;
  478. reference_count: number;
  479. max_references: number;
  480. message: string;
  481. }
  482. export interface CalibrationResult {
  483. success: boolean;
  484. message: string;
  485. }
  486. export interface PlateReference {
  487. index: number;
  488. label: string;
  489. timestamp: string;
  490. has_image: boolean;
  491. thumbnail_url: string;
  492. }
  493. // Archive types
  494. export interface ArchiveDuplicate {
  495. id: number;
  496. print_name: string | null;
  497. created_at: string;
  498. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  499. }
  500. export interface Archive {
  501. id: number;
  502. printer_id: number | null;
  503. project_id: number | null;
  504. project_name: string | null;
  505. filename: string;
  506. file_path: string;
  507. file_size: number;
  508. content_hash: string | null;
  509. thumbnail_path: string | null;
  510. timelapse_path: string | null;
  511. source_3mf_path: string | null;
  512. f3d_path: string | null;
  513. duplicates: ArchiveDuplicate[] | null;
  514. duplicate_count: number;
  515. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  516. original_archive_id: number | null; // ID of the first/original archive
  517. object_count: number | null;
  518. print_name: string | null;
  519. print_time_seconds: number | null;
  520. actual_time_seconds: number | null; // Computed from started_at/completed_at
  521. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  522. filament_used_grams: number | null;
  523. filament_type: string | null;
  524. filament_color: string | null;
  525. layer_height: number | null;
  526. total_layers: number | null;
  527. nozzle_diameter: number | null;
  528. bed_temperature: number | null;
  529. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  530. nozzle_temperature: number | null;
  531. sliced_for_model: string | null; // Printer model this file was sliced for
  532. status: string;
  533. started_at: string | null;
  534. completed_at: string | null;
  535. extra_data: Record<string, unknown> | null;
  536. makerworld_url: string | null;
  537. designer: string | null;
  538. external_url: string | null;
  539. is_favorite: boolean;
  540. tags: string | null;
  541. notes: string | null;
  542. cost: number | null;
  543. photos: string[] | null;
  544. failure_reason: string | null;
  545. quantity: number;
  546. energy_kwh: number | null;
  547. energy_cost: number | null;
  548. created_at: string;
  549. // User tracking (Issue #206)
  550. created_by_id: number | null;
  551. created_by_username: string | null;
  552. // Per-archive run aggregates from PrintLogEntry (#1378)
  553. run_count: number;
  554. last_run_at: string | null;
  555. total_filament_actual_grams: number | null;
  556. successful_run_count: number;
  557. failed_run_count: number;
  558. }
  559. export interface ArchiveSlim {
  560. printer_id: number | null;
  561. print_name: string | null;
  562. print_time_seconds: number | null;
  563. actual_time_seconds: number | null;
  564. filament_used_grams: number | null;
  565. filament_type: string | null;
  566. filament_color: string | null;
  567. status: string;
  568. started_at: string | null;
  569. completed_at: string | null;
  570. cost: number | null;
  571. quantity: number;
  572. created_at: string;
  573. }
  574. export interface PrintLogEntry {
  575. id: number;
  576. archive_id: number | null;
  577. print_name: string | null;
  578. printer_name: string | null;
  579. printer_id: number | null;
  580. status: string;
  581. started_at: string | null;
  582. completed_at: string | null;
  583. duration_seconds: number | null;
  584. filament_type: string | null;
  585. filament_color: string | null;
  586. filament_used_grams: number | null;
  587. cost: number | null;
  588. energy_kwh: number | null;
  589. energy_cost: number | null;
  590. failure_reason: string | null;
  591. thumbnail_path: string | null;
  592. created_by_id: number | null;
  593. created_by_username: string | null;
  594. created_at: string;
  595. }
  596. export interface PrintLogResponse {
  597. items: PrintLogEntry[];
  598. total: number;
  599. }
  600. export interface ArchiveStats {
  601. total_prints: number;
  602. successful_prints: number;
  603. failed_prints: number;
  604. cancelled_prints: number;
  605. total_print_time_hours: number;
  606. total_filament_grams: number;
  607. total_cost: number;
  608. prints_by_filament_type: Record<string, number>;
  609. prints_by_printer: Record<string, number>;
  610. average_time_accuracy: number | null;
  611. time_accuracy_by_printer: Record<string, number> | null;
  612. total_energy_kwh: number;
  613. total_energy_cost: number;
  614. // True when a date-filtered total-consumption query is running on incomplete
  615. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  616. // a baseline). UI should explain why the number may undercount.
  617. energy_data_warming_up?: boolean;
  618. }
  619. export interface TagInfo {
  620. name: string;
  621. count: number;
  622. }
  623. export interface FailureAnalysis {
  624. period_days: number;
  625. total_prints: number;
  626. failed_prints: number;
  627. failure_rate: number;
  628. failures_by_reason: Record<string, number>;
  629. failures_by_filament: Record<string, number>;
  630. failures_by_printer: Record<string, number>;
  631. failures_by_hour: Record<number, number>;
  632. recent_failures: Array<{
  633. id: number;
  634. print_name: string;
  635. failure_reason: string | null;
  636. filament_type: string | null;
  637. printer_id: number | null;
  638. created_at: string | null;
  639. }>;
  640. trend: Array<{
  641. week_start: string;
  642. total_prints: number;
  643. failed_prints: number;
  644. failure_rate: number;
  645. }>;
  646. }
  647. export interface BulkUploadResult {
  648. uploaded: number;
  649. failed: number;
  650. results: Array<{ filename: string; id: number; status: string }>;
  651. errors: Array<{ filename: string; error: string }>;
  652. }
  653. // Archive Comparison types
  654. export interface ComparisonArchiveInfo {
  655. id: number;
  656. print_name: string;
  657. status: string;
  658. created_at: string | null;
  659. printer_id: number | null;
  660. project_name: string | null;
  661. }
  662. export interface ComparisonField {
  663. field: string;
  664. label: string;
  665. unit: string | null;
  666. values: (string | number | null)[];
  667. raw_values: (string | number | null)[];
  668. has_difference: boolean;
  669. }
  670. export interface SuccessCorrelationInsight {
  671. field: string;
  672. label: string;
  673. insight: string;
  674. success_avg?: number;
  675. failed_avg?: number;
  676. success_values?: string[];
  677. failed_values?: string[];
  678. }
  679. export interface SuccessCorrelation {
  680. has_both_outcomes: boolean;
  681. message?: string;
  682. successful_count?: number;
  683. failed_count?: number;
  684. insights?: SuccessCorrelationInsight[];
  685. }
  686. export interface ArchiveComparison {
  687. archives: ComparisonArchiveInfo[];
  688. comparison: ComparisonField[];
  689. differences: ComparisonField[];
  690. success_correlation: SuccessCorrelation;
  691. }
  692. export interface SimilarArchive {
  693. archive: {
  694. id: number;
  695. print_name: string;
  696. status: string;
  697. created_at: string | null;
  698. };
  699. match_reason: string;
  700. match_score: number;
  701. }
  702. // Project types
  703. export interface ProjectStats {
  704. total_archives: number;
  705. total_items: number; // Sum of quantities (total items printed)
  706. completed_prints: number; // Sum of quantities for completed prints (parts)
  707. failed_prints: number;
  708. queued_prints: number;
  709. in_progress_prints: number;
  710. total_print_time_hours: number;
  711. total_filament_grams: number;
  712. progress_percent: number | null; // Plates progress (total_archives / target_count)
  713. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  714. estimated_cost: number;
  715. total_energy_kwh: number;
  716. total_energy_cost: number;
  717. remaining_prints: number | null; // Remaining plates
  718. remaining_parts: number | null; // Remaining parts
  719. bom_total_items: number;
  720. bom_completed_items: number;
  721. bom_cost: number;
  722. }
  723. export interface ProjectChildPreview {
  724. id: number;
  725. name: string;
  726. color: string | null;
  727. status: string;
  728. progress_percent: number | null;
  729. }
  730. export interface Project {
  731. id: number;
  732. name: string;
  733. description: string | null;
  734. color: string | null;
  735. status: string; // active, completed, archived
  736. target_count: number | null; // Target number of plates/print jobs
  737. target_parts_count: number | null; // Target number of parts/objects
  738. notes: string | null;
  739. attachments: ProjectAttachment[] | null;
  740. tags: string | null;
  741. due_date: string | null;
  742. priority: string; // low, normal, high, urgent
  743. budget: number | null;
  744. is_template: boolean;
  745. template_source_id: number | null;
  746. parent_id: number | null;
  747. parent_name: string | null;
  748. children: ProjectChildPreview[];
  749. created_at: string;
  750. updated_at: string;
  751. stats?: ProjectStats;
  752. url: string | null; // External link rendered next to project name on the card (#1155)
  753. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  754. }
  755. export interface ProjectAttachment {
  756. filename: string;
  757. original_name: string;
  758. size: number;
  759. uploaded_at: string;
  760. }
  761. export interface ArchivePreview {
  762. id: number;
  763. print_name: string | null;
  764. thumbnail_path: string | null;
  765. status: string;
  766. filament_type: string | null;
  767. filament_color: string | null;
  768. }
  769. export interface ProjectListItem {
  770. id: number;
  771. name: string;
  772. description: string | null;
  773. color: string | null;
  774. status: string;
  775. target_count: number | null; // Target number of plates/print jobs
  776. target_parts_count: number | null; // Target number of parts/objects
  777. budget: number | null;
  778. created_at: string;
  779. archive_count: number; // Number of print jobs (plates)
  780. total_items: number; // Sum of quantities (total items printed, including failed)
  781. completed_count: number; // Sum of quantities for completed prints only (parts)
  782. failed_count: number; // Sum of quantities for failed prints
  783. queue_count: number;
  784. progress_percent: number | null; // Plates progress
  785. archives: ArchivePreview[];
  786. url: string | null; // #1155
  787. cover_image_filename: string | null; // #1155
  788. }
  789. export interface ProjectCreate {
  790. name: string;
  791. description?: string;
  792. color?: string;
  793. target_count?: number;
  794. target_parts_count?: number;
  795. notes?: string;
  796. tags?: string;
  797. due_date?: string;
  798. priority?: string;
  799. budget?: number | null;
  800. parent_id?: number;
  801. url?: string | null; // #1155
  802. }
  803. export interface ProjectUpdate {
  804. name?: string;
  805. description?: string;
  806. color?: string;
  807. status?: string;
  808. target_count?: number;
  809. target_parts_count?: number;
  810. notes?: string;
  811. tags?: string;
  812. due_date?: string;
  813. priority?: string;
  814. budget?: number | null;
  815. parent_id?: number;
  816. url?: string | null; // #1155 — explicit null clears the URL
  817. }
  818. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  819. export interface BOMItem {
  820. id: number;
  821. project_id: number;
  822. name: string;
  823. quantity_needed: number;
  824. quantity_acquired: number;
  825. unit_price: number | null;
  826. sourcing_url: string | null;
  827. archive_id: number | null;
  828. archive_name: string | null;
  829. stl_filename: string | null;
  830. remarks: string | null;
  831. sort_order: number;
  832. is_complete: boolean;
  833. created_at: string;
  834. updated_at: string;
  835. }
  836. export interface BOMItemCreate {
  837. name: string;
  838. quantity_needed?: number;
  839. unit_price?: number;
  840. sourcing_url?: string;
  841. archive_id?: number;
  842. stl_filename?: string;
  843. remarks?: string;
  844. }
  845. export interface BOMItemUpdate {
  846. name?: string;
  847. quantity_needed?: number;
  848. quantity_acquired?: number;
  849. unit_price?: number;
  850. sourcing_url?: string;
  851. archive_id?: number;
  852. stl_filename?: string;
  853. remarks?: string;
  854. }
  855. // Project Export/Import Types
  856. export interface BOMItemExport {
  857. name: string;
  858. quantity_needed: number;
  859. quantity_acquired: number;
  860. unit_price: number | null;
  861. sourcing_url: string | null;
  862. stl_filename: string | null;
  863. remarks: string | null;
  864. }
  865. export interface LinkedFolderExport {
  866. name: string;
  867. }
  868. export interface ProjectExport {
  869. name: string;
  870. description: string | null;
  871. color: string | null;
  872. status: string;
  873. target_count: number | null;
  874. target_parts_count: number | null;
  875. notes: string | null;
  876. tags: string | null;
  877. due_date: string | null;
  878. priority: string;
  879. budget: number | null;
  880. bom_items: BOMItemExport[];
  881. linked_folders: LinkedFolderExport[];
  882. }
  883. export interface ProjectImport {
  884. name: string;
  885. description?: string;
  886. color?: string;
  887. status?: string;
  888. target_count?: number;
  889. target_parts_count?: number;
  890. notes?: string;
  891. tags?: string;
  892. due_date?: string;
  893. priority?: string;
  894. budget?: number | null;
  895. bom_items?: BOMItemExport[];
  896. linked_folders?: LinkedFolderExport[];
  897. }
  898. // Timeline Types
  899. export interface TimelineEvent {
  900. event_type: string;
  901. timestamp: string;
  902. title: string;
  903. description: string | null;
  904. metadata: Record<string, unknown> | null;
  905. }
  906. // API Key types
  907. export interface APIKey {
  908. id: number;
  909. name: string;
  910. key_prefix: string;
  911. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  912. can_queue: boolean;
  913. can_control_printer: boolean;
  914. can_read_status: boolean;
  915. can_access_cloud: boolean;
  916. can_update_energy_cost: boolean;
  917. printer_ids: number[] | null;
  918. enabled: boolean;
  919. last_used: string | null;
  920. created_at: string;
  921. expires_at: string | null;
  922. }
  923. export interface APIKeyCreate {
  924. name: string;
  925. can_queue?: boolean;
  926. can_control_printer?: boolean;
  927. can_read_status?: boolean;
  928. can_access_cloud?: boolean;
  929. can_update_energy_cost?: boolean;
  930. printer_ids?: number[] | null;
  931. expires_at?: string | null;
  932. }
  933. export interface APIKeyCreateResponse extends APIKey {
  934. key: string; // Full key, only shown on creation
  935. }
  936. export interface APIKeyUpdate {
  937. name?: string;
  938. can_queue?: boolean;
  939. can_control_printer?: boolean;
  940. can_read_status?: boolean;
  941. can_access_cloud?: boolean;
  942. can_update_energy_cost?: boolean;
  943. printer_ids?: number[] | null;
  944. enabled?: boolean;
  945. expires_at?: string | null;
  946. }
  947. // Settings types
  948. export interface AppSettings {
  949. auto_archive: boolean;
  950. save_thumbnails: boolean;
  951. capture_finish_photo: boolean;
  952. default_filament_cost: number;
  953. currency: string;
  954. energy_cost_per_kwh: number;
  955. energy_tracking_mode: 'print' | 'total';
  956. check_updates: boolean;
  957. check_printer_firmware: boolean;
  958. include_beta_updates: boolean;
  959. language: string;
  960. notification_language: string;
  961. // AMS threshold settings
  962. ams_humidity_good: number; // <= this is green
  963. ams_humidity_fair: number; // <= this is orange, > is red
  964. ams_temp_good: number; // <= this is green/blue
  965. ams_temp_fair: number; // <= this is orange, > is red
  966. ams_history_retention_days: number; // days to keep AMS sensor history
  967. // Queue auto-drying settings
  968. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  969. queue_drying_block: boolean; // Block queue until drying completes
  970. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  971. drying_presets: string; // JSON blob of drying presets per filament type
  972. gcode_snippets: string; // JSON: per-model G-code injection snippets
  973. // Scheduled local backup
  974. local_backup_enabled: boolean;
  975. local_backup_schedule: string;
  976. local_backup_time: string;
  977. local_backup_retention: number;
  978. local_backup_path: string;
  979. // Print modal settings
  980. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  981. // Date/time format settings
  982. date_format: 'system' | 'us' | 'eu' | 'iso';
  983. time_format: 'system' | '12h' | '24h';
  984. // Filament tracking
  985. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  986. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  987. // Default printer
  988. default_printer_id: number | null;
  989. // Dark mode theme settings
  990. dark_style: 'classic' | 'glow' | 'vibrant';
  991. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  992. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  993. // Light mode theme settings
  994. light_style: 'classic' | 'glow' | 'vibrant';
  995. light_background: 'neutral' | 'warm' | 'cool';
  996. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  997. // FTP retry settings
  998. ftp_retry_enabled: boolean;
  999. ftp_retry_count: number;
  1000. ftp_retry_delay: number;
  1001. ftp_timeout: number;
  1002. // MQTT relay settings
  1003. mqtt_enabled: boolean;
  1004. mqtt_broker: string;
  1005. mqtt_port: number;
  1006. mqtt_username: string;
  1007. mqtt_password: string;
  1008. mqtt_topic_prefix: string;
  1009. mqtt_use_tls: boolean;
  1010. // External URL for notifications
  1011. external_url: string;
  1012. // Home Assistant integration
  1013. ha_enabled: boolean;
  1014. ha_url: string;
  1015. ha_token: string;
  1016. ha_url_from_env: boolean;
  1017. ha_token_from_env: boolean;
  1018. ha_env_managed: boolean;
  1019. // File Manager / Library settings
  1020. library_archive_mode: 'always' | 'never' | 'ask';
  1021. library_disk_warning_gb: number;
  1022. // Camera view settings
  1023. camera_view_mode: 'window' | 'embedded';
  1024. // Preferred slicer
  1025. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1026. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1027. use_slicer_api: boolean;
  1028. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1029. orcaslicer_api_url: string;
  1030. bambu_studio_api_url: string;
  1031. // Prometheus metrics
  1032. prometheus_enabled: boolean;
  1033. prometheus_token: string;
  1034. // Bed cooled threshold
  1035. bed_cooled_threshold: number;
  1036. // Inventory low stock threshold
  1037. low_stock_threshold: number;
  1038. // User email notifications toggle
  1039. user_notifications_enabled: boolean;
  1040. // Default print options
  1041. default_bed_levelling: boolean;
  1042. default_flow_cali: boolean;
  1043. default_vibration_cali: boolean;
  1044. default_layer_inspect: boolean;
  1045. default_timelapse: boolean;
  1046. // Staggered batch start defaults
  1047. stagger_group_size: number;
  1048. stagger_interval_minutes: number;
  1049. // Plate-clear confirmation
  1050. require_plate_clear: boolean;
  1051. // Shortest job first scheduling
  1052. queue_shortest_first: boolean;
  1053. // Default sidebar order (admin-set for all users)
  1054. default_sidebar_order: string;
  1055. // LDAP authentication
  1056. ldap_enabled: boolean;
  1057. ldap_server_url: string;
  1058. ldap_bind_dn: string;
  1059. ldap_bind_password: string;
  1060. ldap_search_base: string;
  1061. ldap_user_filter: string;
  1062. ldap_security: string;
  1063. ldap_group_mapping: string;
  1064. ldap_auto_provision: boolean;
  1065. ldap_default_group: string;
  1066. obico_enabled: boolean;
  1067. obico_ml_url: string;
  1068. obico_sensitivity: 'low' | 'medium' | 'high';
  1069. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1070. obico_poll_interval: number;
  1071. obico_enabled_printers: string;
  1072. // Inventory forecasting global lead time
  1073. forecast_global_lead_time_days: number;
  1074. }
  1075. export type AppSettingsUpdate = Partial<AppSettings>;
  1076. // MQTT relay status
  1077. export interface MQTTStatus {
  1078. enabled: boolean;
  1079. connected: boolean;
  1080. broker: string;
  1081. port: number;
  1082. topic_prefix: string;
  1083. }
  1084. // Cloud types
  1085. export interface CloudAuthStatus {
  1086. is_authenticated: boolean;
  1087. email: string | null;
  1088. region?: 'global' | 'china' | null;
  1089. }
  1090. export interface CloudLoginResponse {
  1091. success: boolean;
  1092. needs_verification: boolean;
  1093. message: string;
  1094. verification_type?: 'email' | 'totp' | null;
  1095. tfa_key?: string | null;
  1096. }
  1097. // MakerWorld integration. Full metadata/instance shapes come back as
  1098. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1099. // pass them through verbatim rather than maintaining a brittle mirror.
  1100. export interface MakerworldStatus {
  1101. has_cloud_token: boolean;
  1102. can_download: boolean;
  1103. }
  1104. export interface MakerworldResolvedModel {
  1105. model_id: number;
  1106. profile_id: number | null;
  1107. design: Record<string, unknown>;
  1108. instances: Array<Record<string, unknown>>;
  1109. already_imported_library_ids: number[];
  1110. }
  1111. export interface MakerworldImportResponse {
  1112. library_file_id: number;
  1113. filename: string;
  1114. folder_id: number | null;
  1115. profile_id: number | null;
  1116. was_existing: boolean;
  1117. }
  1118. export interface MakerworldRecentImport {
  1119. library_file_id: number;
  1120. filename: string;
  1121. folder_id: number | null;
  1122. thumbnail_path: string | null;
  1123. source_url: string | null;
  1124. created_at: string;
  1125. }
  1126. export interface SlicerSetting {
  1127. setting_id: string;
  1128. name: string;
  1129. type: string;
  1130. version: string | null;
  1131. user_id: string | null;
  1132. updated_time: string | null;
  1133. is_custom: boolean;
  1134. }
  1135. export interface SpoolCatalogEntry {
  1136. id: number;
  1137. name: string;
  1138. weight: number;
  1139. is_default: boolean;
  1140. }
  1141. export interface ColorCatalogEntry {
  1142. id: number;
  1143. manufacturer: string;
  1144. color_name: string;
  1145. hex_color: string;
  1146. material: string | null;
  1147. is_default: boolean;
  1148. // #1154: optional multi-colour gradient stops + visual effect.
  1149. extra_colors?: string | null;
  1150. effect_type?: string | null;
  1151. }
  1152. export interface ColorLookupResult {
  1153. found: boolean;
  1154. hex_color: string | null;
  1155. material: string | null;
  1156. }
  1157. export interface SlicerSettingsResponse {
  1158. filament: SlicerSetting[];
  1159. printer: SlicerSetting[];
  1160. process: SlicerSetting[];
  1161. }
  1162. export interface SlicerSettingDetail {
  1163. message?: string | null;
  1164. code?: string | null;
  1165. error?: string | null;
  1166. public: boolean;
  1167. version?: string | null;
  1168. type: string;
  1169. name: string;
  1170. update_time?: string | null;
  1171. nickname?: string | null;
  1172. base_id?: string | null;
  1173. setting: Record<string, unknown>;
  1174. filament_id?: string | null;
  1175. setting_id?: string | null;
  1176. }
  1177. export interface SlicerSettingCreate {
  1178. type: string; // 'filament', 'print', or 'printer'
  1179. name: string;
  1180. base_id: string;
  1181. setting: Record<string, unknown>;
  1182. }
  1183. export interface SlicerSettingUpdate {
  1184. name?: string;
  1185. setting?: Record<string, unknown>;
  1186. }
  1187. export interface SlicerSettingDeleteResponse {
  1188. success: boolean;
  1189. message: string;
  1190. }
  1191. // Built-in filament fallback (static table from backend)
  1192. export interface BuiltinFilament {
  1193. filament_id: string;
  1194. name: string;
  1195. }
  1196. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1197. //
  1198. // Two preset shapes are accepted per slot:
  1199. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1200. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1201. // across cloud / local / standard tiers. Source-aware refs win when both
  1202. // are present in the same payload.
  1203. export type PresetSource = 'cloud' | 'local' | 'standard';
  1204. export interface PresetRef {
  1205. source: PresetSource;
  1206. id: string;
  1207. }
  1208. export interface SliceBundleSpec {
  1209. bundle_id: string;
  1210. printer_name: string;
  1211. process_name: string;
  1212. // Per-slot filament names in plate order. Index 0 = slot 1, etc.
  1213. filament_names: string[];
  1214. }
  1215. export interface SliceRequest {
  1216. printer_preset_id?: number;
  1217. process_preset_id?: number;
  1218. filament_preset_id?: number;
  1219. printer_preset?: PresetRef;
  1220. process_preset?: PresetRef;
  1221. filament_preset?: PresetRef;
  1222. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1223. // preferred over the singular `filament_preset` when both are sent; the
  1224. // backend validator promotes a singular into a one-element list when this
  1225. // is omitted, so legacy single-color clients keep working unchanged.
  1226. filament_presets?: PresetRef[];
  1227. // Bundle dispatch: when set, the backend skips PresetRef resolution and
  1228. // picks the JSON triplet from a sidecar-stored .bbscfg by name. Mutually
  1229. // exclusive with the preset fields above (validator accepts both, but
  1230. // dispatch ignores the preset side when bundle is set).
  1231. bundle?: SliceBundleSpec;
  1232. plate?: number;
  1233. export_3mf?: boolean;
  1234. // Build-plate override (#1337). When omitted, the slicer uses the process
  1235. // preset's curr_bed_type as-is. Canonical values match BambuStudio /
  1236. // OrcaSlicer's enum: "Cool Plate", "Engineering Plate", "High Temp Plate",
  1237. // "Textured PEI Plate", "Smooth PEI Plate", "Cool Plate (SuperTack)",
  1238. // "Supertack Plate".
  1239. bed_type?: string | null;
  1240. }
  1241. // GET /api/v1/slicer/bundles — Printer Preset Bundles imported from
  1242. // BambuStudio's "File → Export → Export Preset Bundle" dialog. Each bundle
  1243. // is a .bbscfg zip the user uploads once per printer, after which the
  1244. // SliceModal can pick its inner presets by name (no re-upload per slice).
  1245. // Backend: backend/app/api/routes/slicer_presets.py — bundle endpoints.
  1246. export interface SlicerBundle {
  1247. id: string;
  1248. printer_preset_name: string;
  1249. printer: string[];
  1250. process: string[];
  1251. filament: string[];
  1252. version: string | null;
  1253. }
  1254. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1255. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1256. export interface UnifiedPreset {
  1257. id: string;
  1258. name: string;
  1259. source: PresetSource;
  1260. // Populated for the filament slot only — used by the SliceModal multi-color
  1261. // pre-pick to score presets against each plate slot's required (type,
  1262. // colour). Optional because the bundled / standard tier rarely carries a
  1263. // colour (colour is a runtime spool attribute on Bambu) and older API
  1264. // responses pre-date these fields entirely.
  1265. filament_type?: string | null;
  1266. filament_colour?: string | null;
  1267. // Printer-preset names a process / filament preset declares itself
  1268. // compatible with. Populated for the local tier (the slicer's own
  1269. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1270. // the process / filament dropdowns by the selected printer using this when
  1271. // present, and otherwise by the user's uploaded Slicer Bundles (#1325).
  1272. compatible_printers?: string[] | null;
  1273. }
  1274. export interface UnifiedPresetsBySlot {
  1275. printer: UnifiedPreset[];
  1276. process: UnifiedPreset[];
  1277. filament: UnifiedPreset[];
  1278. }
  1279. export interface UnifiedPresetsResponse {
  1280. cloud: UnifiedPresetsBySlot;
  1281. local: UnifiedPresetsBySlot;
  1282. standard: UnifiedPresetsBySlot;
  1283. cloud_status: SlicerCloudStatus;
  1284. }
  1285. export interface SliceResponse {
  1286. library_file_id: number;
  1287. name: string;
  1288. print_time_seconds: number;
  1289. filament_used_g: number;
  1290. filament_used_mm: number;
  1291. used_embedded_settings: boolean;
  1292. }
  1293. export interface SliceArchiveResponse {
  1294. archive_id: number;
  1295. name: string;
  1296. print_time_seconds: number;
  1297. filament_used_g: number;
  1298. filament_used_mm: number;
  1299. used_embedded_settings: boolean;
  1300. }
  1301. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  1302. // the frontend polls /slice-jobs/{id} until status is terminal.
  1303. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  1304. export interface SliceJobEnqueueResponse {
  1305. job_id: number;
  1306. status: SliceJobStatus;
  1307. status_url: string;
  1308. }
  1309. export interface SliceJobProgress {
  1310. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  1311. stage: string;
  1312. total_percent: number;
  1313. plate_percent: number;
  1314. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  1315. plate_index: number;
  1316. plate_count: number;
  1317. updated_at: number;
  1318. /** When the backend is in the cross-class slice-all loop (#1493), each
  1319. * per-plate sub-slice's progress is augmented with the loop position
  1320. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  1321. * fields are absent on a single-plate slice. */
  1322. multi_plate_index?: number;
  1323. multi_plate_count?: number;
  1324. }
  1325. export interface SliceJobState {
  1326. job_id: number;
  1327. status: SliceJobStatus;
  1328. kind: 'library_file' | 'archive';
  1329. source_id: number;
  1330. source_name: string;
  1331. created_at: string;
  1332. started_at: string | null;
  1333. completed_at: string | null;
  1334. /** Live progress fed by the sidecar's --pipe channel; null until the
  1335. * slicer emits its first frame (early "Initializing" phase) or when
  1336. * the sidecar doesn't support progress. */
  1337. progress: SliceJobProgress | null;
  1338. result?: SliceResponse | SliceArchiveResponse;
  1339. error_status?: number;
  1340. error_detail?: string;
  1341. }
  1342. // Local preset types (OrcaSlicer imports)
  1343. export interface LocalPreset {
  1344. id: number;
  1345. name: string;
  1346. preset_type: string;
  1347. source: string;
  1348. filament_type: string | null;
  1349. filament_vendor: string | null;
  1350. nozzle_temp_min: number | null;
  1351. nozzle_temp_max: number | null;
  1352. pressure_advance: string | null;
  1353. default_filament_colour: string | null;
  1354. filament_cost: string | null;
  1355. filament_density: string | null;
  1356. compatible_printers: string | null;
  1357. inherits: string | null;
  1358. version: string | null;
  1359. created_at: string;
  1360. updated_at: string;
  1361. }
  1362. export interface LocalPresetDetail extends LocalPreset {
  1363. setting: Record<string, unknown>;
  1364. }
  1365. export interface LocalPresetsResponse {
  1366. filament: LocalPreset[];
  1367. printer: LocalPreset[];
  1368. process: LocalPreset[];
  1369. }
  1370. export interface ImportResponse {
  1371. success: boolean;
  1372. imported: number;
  1373. skipped: number;
  1374. errors: string[];
  1375. }
  1376. export interface FieldOption {
  1377. value: string;
  1378. label: string;
  1379. }
  1380. export interface FieldDefinition {
  1381. key: string;
  1382. label: string;
  1383. type: 'text' | 'number' | 'boolean' | 'select';
  1384. category: string;
  1385. description?: string;
  1386. options?: FieldOption[];
  1387. unit?: string;
  1388. min?: number;
  1389. max?: number;
  1390. step?: number;
  1391. }
  1392. export interface FieldDefinitionsResponse {
  1393. version: string;
  1394. description: string;
  1395. fields: FieldDefinition[];
  1396. }
  1397. export interface CloudDevice {
  1398. dev_id: string;
  1399. name: string;
  1400. dev_model_name: string | null;
  1401. dev_product_name: string | null;
  1402. online: boolean;
  1403. }
  1404. // Smart Plug types
  1405. export interface SmartPlug {
  1406. id: number;
  1407. name: string;
  1408. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1409. ip_address: string | null; // Required for Tasmota
  1410. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  1411. // Home Assistant energy sensor entities (optional)
  1412. ha_power_entity: string | null;
  1413. ha_energy_today_entity: string | null;
  1414. ha_energy_total_entity: string | null;
  1415. // MQTT fields (required when plug_type="mqtt")
  1416. // Legacy field - kept for backward compatibility
  1417. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  1418. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  1419. // Power monitoring
  1420. mqtt_power_topic: string | null; // Topic for power data
  1421. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  1422. mqtt_power_multiplier: number; // Unit conversion for power
  1423. // Energy monitoring
  1424. mqtt_energy_topic: string | null; // Topic for energy data
  1425. mqtt_energy_path: string | null; // e.g., "energy_l1"
  1426. mqtt_energy_multiplier: number; // Unit conversion for energy
  1427. // State monitoring
  1428. mqtt_state_topic: string | null; // Topic for state data
  1429. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  1430. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  1431. // REST/Webhook fields (required when plug_type="rest")
  1432. rest_on_url: string | null;
  1433. rest_on_body: string | null;
  1434. rest_off_url: string | null;
  1435. rest_off_body: string | null;
  1436. rest_method: string | null;
  1437. rest_headers: string | null;
  1438. rest_status_url: string | null;
  1439. rest_status_path: string | null;
  1440. rest_status_on_value: string | null;
  1441. rest_power_url: string | null;
  1442. rest_power_path: string | null;
  1443. rest_power_multiplier: number;
  1444. rest_energy_url: string | null;
  1445. rest_energy_path: string | null;
  1446. rest_energy_multiplier: number;
  1447. printer_id: number | null;
  1448. enabled: boolean;
  1449. auto_on: boolean;
  1450. auto_off: boolean;
  1451. auto_off_persistent: boolean;
  1452. off_delay_mode: 'time' | 'temperature';
  1453. off_delay_minutes: number;
  1454. off_temp_threshold: number;
  1455. // #1349: auto-off after AMS drying completes.
  1456. auto_off_after_drying: boolean;
  1457. off_delay_after_drying_minutes: number;
  1458. username: string | null;
  1459. password: string | null;
  1460. // Power alerts
  1461. power_alert_enabled: boolean;
  1462. power_alert_high: number | null;
  1463. power_alert_low: number | null;
  1464. power_alert_last_triggered: string | null;
  1465. // Schedule
  1466. schedule_enabled: boolean;
  1467. schedule_on_time: string | null;
  1468. schedule_off_time: string | null;
  1469. // Visibility options
  1470. show_in_switchbar: boolean;
  1471. show_on_printer_card: boolean; // For scripts: show on printer card
  1472. // Status
  1473. last_state: string | null;
  1474. last_checked: string | null;
  1475. auto_off_executed: boolean; // True when auto-off was triggered after print
  1476. created_at: string;
  1477. updated_at: string;
  1478. }
  1479. export interface SmartPlugCreate {
  1480. name: string;
  1481. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1482. ip_address?: string | null; // Required for Tasmota
  1483. ha_entity_id?: string | null; // Required for Home Assistant
  1484. // Home Assistant energy sensor entities (optional)
  1485. ha_power_entity?: string | null;
  1486. ha_energy_today_entity?: string | null;
  1487. ha_energy_total_entity?: string | null;
  1488. // MQTT fields (required when plug_type="mqtt")
  1489. // Legacy fields - kept for backward compatibility
  1490. mqtt_topic?: string | null;
  1491. mqtt_multiplier?: number;
  1492. // Power monitoring
  1493. mqtt_power_topic?: string | null;
  1494. mqtt_power_path?: string | null;
  1495. mqtt_power_multiplier?: number;
  1496. // Energy monitoring
  1497. mqtt_energy_topic?: string | null;
  1498. mqtt_energy_path?: string | null;
  1499. mqtt_energy_multiplier?: number;
  1500. // State monitoring
  1501. mqtt_state_topic?: string | null;
  1502. mqtt_state_path?: string | null;
  1503. mqtt_state_on_value?: string | null;
  1504. // REST fields
  1505. rest_on_url?: string | null;
  1506. rest_on_body?: string | null;
  1507. rest_off_url?: string | null;
  1508. rest_off_body?: string | null;
  1509. rest_method?: string | null;
  1510. rest_headers?: string | null;
  1511. rest_status_url?: string | null;
  1512. rest_status_path?: string | null;
  1513. rest_status_on_value?: string | null;
  1514. rest_power_url?: string | null;
  1515. rest_power_path?: string | null;
  1516. rest_power_multiplier?: number;
  1517. rest_energy_url?: string | null;
  1518. rest_energy_path?: string | null;
  1519. rest_energy_multiplier?: number;
  1520. printer_id?: number | null;
  1521. enabled?: boolean;
  1522. auto_on?: boolean;
  1523. auto_off?: boolean;
  1524. auto_off_persistent?: boolean;
  1525. off_delay_mode?: 'time' | 'temperature';
  1526. off_delay_minutes?: number;
  1527. off_temp_threshold?: number;
  1528. // #1349
  1529. auto_off_after_drying?: boolean;
  1530. off_delay_after_drying_minutes?: number;
  1531. username?: string | null;
  1532. password?: string | null;
  1533. // Power alerts
  1534. power_alert_enabled?: boolean;
  1535. power_alert_high?: number | null;
  1536. power_alert_low?: number | null;
  1537. // Schedule
  1538. schedule_enabled?: boolean;
  1539. schedule_on_time?: string | null;
  1540. schedule_off_time?: string | null;
  1541. // Visibility options
  1542. show_in_switchbar?: boolean;
  1543. show_on_printer_card?: boolean;
  1544. }
  1545. export interface SmartPlugUpdate {
  1546. name?: string;
  1547. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1548. ip_address?: string | null;
  1549. ha_entity_id?: string | null;
  1550. // Home Assistant energy sensor entities (optional)
  1551. ha_power_entity?: string | null;
  1552. ha_energy_today_entity?: string | null;
  1553. ha_energy_total_entity?: string | null;
  1554. // MQTT fields (legacy)
  1555. mqtt_topic?: string | null;
  1556. mqtt_multiplier?: number;
  1557. // MQTT power fields
  1558. mqtt_power_topic?: string | null;
  1559. mqtt_power_path?: string | null;
  1560. mqtt_power_multiplier?: number;
  1561. // MQTT energy fields
  1562. mqtt_energy_topic?: string | null;
  1563. mqtt_energy_path?: string | null;
  1564. mqtt_energy_multiplier?: number;
  1565. // MQTT state fields
  1566. mqtt_state_topic?: string | null;
  1567. mqtt_state_path?: string | null;
  1568. mqtt_state_on_value?: string | null;
  1569. // REST fields
  1570. rest_on_url?: string | null;
  1571. rest_on_body?: string | null;
  1572. rest_off_url?: string | null;
  1573. rest_off_body?: string | null;
  1574. rest_method?: string | null;
  1575. rest_headers?: string | null;
  1576. rest_status_url?: string | null;
  1577. rest_status_path?: string | null;
  1578. rest_status_on_value?: string | null;
  1579. rest_power_url?: string | null;
  1580. rest_power_path?: string | null;
  1581. rest_power_multiplier?: number;
  1582. rest_energy_url?: string | null;
  1583. rest_energy_path?: string | null;
  1584. rest_energy_multiplier?: number;
  1585. printer_id?: number | null;
  1586. enabled?: boolean;
  1587. auto_on?: boolean;
  1588. auto_off?: boolean;
  1589. auto_off_persistent?: boolean;
  1590. off_delay_mode?: 'time' | 'temperature';
  1591. off_delay_minutes?: number;
  1592. off_temp_threshold?: number;
  1593. // #1349
  1594. auto_off_after_drying?: boolean;
  1595. off_delay_after_drying_minutes?: number;
  1596. username?: string | null;
  1597. password?: string | null;
  1598. // Power alerts
  1599. power_alert_enabled?: boolean;
  1600. power_alert_high?: number | null;
  1601. power_alert_low?: number | null;
  1602. // Schedule
  1603. schedule_enabled?: boolean;
  1604. schedule_on_time?: string | null;
  1605. schedule_off_time?: string | null;
  1606. // Visibility options
  1607. show_in_switchbar?: boolean;
  1608. show_on_printer_card?: boolean;
  1609. }
  1610. // Home Assistant entity for smart plug selection
  1611. export interface HAEntity {
  1612. entity_id: string;
  1613. friendly_name: string;
  1614. state: string | null;
  1615. domain: string; // "switch", "light", "input_boolean", "script"
  1616. }
  1617. // Home Assistant sensor entity for energy monitoring
  1618. export interface HASensorEntity {
  1619. entity_id: string;
  1620. friendly_name: string;
  1621. state: string | null;
  1622. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  1623. }
  1624. export interface HATestConnectionResult {
  1625. success: boolean;
  1626. message: string | null;
  1627. error: string | null;
  1628. }
  1629. export interface SmartPlugEnergy {
  1630. power: number | null; // Current watts
  1631. voltage: number | null; // Volts
  1632. current: number | null; // Amps
  1633. today: number | null; // kWh used today
  1634. yesterday: number | null; // kWh used yesterday
  1635. total: number | null; // Total kWh
  1636. factor: number | null; // Power factor (0-1)
  1637. apparent_power: number | null; // VA
  1638. reactive_power: number | null; // VAr
  1639. }
  1640. export interface SmartPlugStatus {
  1641. state: string | null;
  1642. reachable: boolean;
  1643. device_name: string | null;
  1644. energy: SmartPlugEnergy | null;
  1645. }
  1646. export interface SmartPlugTestResult {
  1647. success: boolean;
  1648. state: string | null;
  1649. device_name: string | null;
  1650. }
  1651. // Tasmota Discovery types
  1652. export interface TasmotaScanStatus {
  1653. running: boolean;
  1654. scanned: number;
  1655. total: number;
  1656. }
  1657. export interface DiscoveredTasmotaDevice {
  1658. ip_address: string;
  1659. name: string;
  1660. module: number | null;
  1661. state: string | null;
  1662. discovered_at: string | null;
  1663. }
  1664. // Print Queue types
  1665. export interface PrintQueueItem {
  1666. id: number;
  1667. printer_id: number | null; // null = unassigned
  1668. target_model: string | null; // Target printer model for model-based assignment
  1669. target_location: string | null; // Target location filter for model-based assignment
  1670. required_filament_types: string[] | null; // Required filament types for model-based assignment
  1671. waiting_reason: string | null; // Why a model-based job hasn't started yet
  1672. // Either archive_id OR library_file_id must be set (archive created at print start)
  1673. archive_id: number | null;
  1674. library_file_id: number | null;
  1675. position: number;
  1676. scheduled_time: string | null;
  1677. require_previous_success: boolean;
  1678. auto_off_after: boolean;
  1679. manual_start: boolean; // Requires manual trigger to start (staged)
  1680. // Set by the dispatch scheduler when the assigned spool can't satisfy
  1681. // any required slot's grams (#1496). Surfaced on the queue row as a
  1682. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  1683. filament_short: boolean;
  1684. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  1685. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  1686. plate_id: number | null; // Plate ID for multi-plate 3MF files
  1687. // Print options
  1688. bed_levelling: boolean;
  1689. flow_cali: boolean;
  1690. vibration_cali: boolean;
  1691. layer_inspect: boolean;
  1692. timelapse: boolean;
  1693. use_ams: boolean;
  1694. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  1695. started_at: string | null;
  1696. completed_at: string | null;
  1697. error_message: string | null;
  1698. created_at: string;
  1699. archive_name?: string | null;
  1700. archive_thumbnail?: string | null;
  1701. // True when the linked archive has been soft-deleted; archive_name /
  1702. // archive_thumbnail / downstream metadata are left null in that case so
  1703. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  1704. archive_deleted?: boolean;
  1705. library_file_name?: string | null;
  1706. library_file_thumbnail?: string | null;
  1707. printer_name?: string | null;
  1708. print_time_seconds?: number | null; // Estimated print time from archive or library file
  1709. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  1710. // User tracking (Issue #206)
  1711. created_by_id?: number | null;
  1712. created_by_username?: string | null;
  1713. // Batch grouping
  1714. batch_id?: number | null;
  1715. batch_name?: string | null;
  1716. // Shortest-job-first scheduling
  1717. been_jumped?: boolean;
  1718. // Auto-print G-code injection
  1719. gcode_injection?: boolean;
  1720. }
  1721. export interface PrintBatch {
  1722. id: number;
  1723. name: string;
  1724. archive_id: number | null;
  1725. library_file_id: number | null;
  1726. quantity: number;
  1727. status: string;
  1728. created_at: string;
  1729. created_by_id: number | null;
  1730. created_by_username: string | null;
  1731. pending_count: number;
  1732. printing_count: number;
  1733. completed_count: number;
  1734. failed_count: number;
  1735. cancelled_count: number;
  1736. }
  1737. export interface PrintQueueItemCreate {
  1738. printer_id?: number | null; // null = unassigned
  1739. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1740. target_location?: string | null; // Target location filter (only used with target_model)
  1741. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  1742. archive_id?: number | null;
  1743. library_file_id?: number | null;
  1744. scheduled_time?: string | null;
  1745. require_previous_success?: boolean;
  1746. auto_off_after?: boolean;
  1747. manual_start?: boolean; // Requires manual trigger to start (staged)
  1748. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  1749. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1750. // Print options
  1751. bed_levelling?: boolean;
  1752. flow_cali?: boolean;
  1753. vibration_cali?: boolean;
  1754. layer_inspect?: boolean;
  1755. timelapse?: boolean;
  1756. use_ams?: boolean;
  1757. // Auto-print G-code injection
  1758. gcode_injection?: boolean;
  1759. // Batch: create multiple copies (creates a batch if > 1)
  1760. quantity?: number;
  1761. // Project to associate the resulting archive with
  1762. project_id?: number;
  1763. }
  1764. export interface PrintQueueItemUpdate {
  1765. printer_id?: number | null; // null = unassign
  1766. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1767. target_location?: string | null; // Target location filter (only used with target_model)
  1768. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  1769. position?: number;
  1770. scheduled_time?: string | null;
  1771. require_previous_success?: boolean;
  1772. auto_off_after?: boolean;
  1773. manual_start?: boolean;
  1774. ams_mapping?: number[];
  1775. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1776. // Print options
  1777. bed_levelling?: boolean;
  1778. flow_cali?: boolean;
  1779. vibration_cali?: boolean;
  1780. layer_inspect?: boolean;
  1781. timelapse?: boolean;
  1782. use_ams?: boolean;
  1783. // Auto-print G-code injection
  1784. gcode_injection?: boolean;
  1785. }
  1786. export interface PrintQueueBulkUpdate {
  1787. item_ids: number[];
  1788. printer_id?: number | null;
  1789. scheduled_time?: string | null;
  1790. require_previous_success?: boolean;
  1791. auto_off_after?: boolean;
  1792. manual_start?: boolean;
  1793. // Print options
  1794. bed_levelling?: boolean;
  1795. flow_cali?: boolean;
  1796. vibration_cali?: boolean;
  1797. layer_inspect?: boolean;
  1798. timelapse?: boolean;
  1799. use_ams?: boolean;
  1800. // Auto-print G-code injection
  1801. gcode_injection?: boolean;
  1802. }
  1803. export interface PrintQueueBulkUpdateResponse {
  1804. updated_count: number;
  1805. skipped_count: number;
  1806. message: string;
  1807. }
  1808. // MQTT Logging types
  1809. export interface MQTTLogEntry {
  1810. timestamp: string;
  1811. topic: string;
  1812. direction: 'in' | 'out';
  1813. payload: Record<string, unknown>;
  1814. }
  1815. export interface MQTTLogsResponse {
  1816. logging_enabled: boolean;
  1817. logs: MQTTLogEntry[];
  1818. }
  1819. // K-Profile types
  1820. export interface KProfile {
  1821. slot_id: number;
  1822. extruder_id: number;
  1823. nozzle_id: string;
  1824. nozzle_diameter: string;
  1825. filament_id: string;
  1826. name: string;
  1827. k_value: string;
  1828. n_coef: string;
  1829. ams_id: number;
  1830. tray_id: number;
  1831. setting_id: string | null;
  1832. }
  1833. export interface KProfileCreate {
  1834. slot_id?: number; // Storage slot, 0 for new profiles
  1835. extruder_id?: number;
  1836. nozzle_id: string;
  1837. nozzle_diameter: string;
  1838. filament_id: string;
  1839. name: string;
  1840. k_value: string;
  1841. n_coef?: string;
  1842. ams_id?: number;
  1843. tray_id?: number;
  1844. setting_id?: string | null;
  1845. }
  1846. export interface KProfileDelete {
  1847. slot_id: number; // cali_idx - calibration index to delete
  1848. extruder_id: number;
  1849. nozzle_id: string; // e.g., "HH00-0.4"
  1850. nozzle_diameter: string; // e.g., "0.4"
  1851. filament_id: string; // Bambu filament identifier
  1852. setting_id?: string | null; // Setting ID (for X1C series)
  1853. }
  1854. export interface KProfilesResponse {
  1855. profiles: KProfile[];
  1856. nozzle_diameter: string;
  1857. }
  1858. export interface KProfileNote {
  1859. setting_id: string;
  1860. note: string;
  1861. }
  1862. export interface KProfileNotesResponse {
  1863. notes: Record<string, string>; // setting_id -> note
  1864. }
  1865. // Slot Preset Mapping
  1866. export interface SlotPresetMapping {
  1867. ams_id: number;
  1868. tray_id: number;
  1869. preset_id: string;
  1870. preset_name: string;
  1871. }
  1872. // Filament types
  1873. export interface Filament {
  1874. id: number;
  1875. name: string;
  1876. type: string; // PLA, PETG, ABS, etc.
  1877. brand: string | null;
  1878. color: string | null;
  1879. color_hex: string | null;
  1880. cost_per_kg: number;
  1881. spool_weight_g: number;
  1882. currency: string;
  1883. density: number | null;
  1884. print_temp_min: number | null;
  1885. print_temp_max: number | null;
  1886. bed_temp_min: number | null;
  1887. bed_temp_max: number | null;
  1888. created_at: string;
  1889. updated_at: string;
  1890. }
  1891. // Notification Provider types
  1892. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant';
  1893. export interface NotificationProvider {
  1894. id: number;
  1895. name: string;
  1896. provider_type: ProviderType;
  1897. enabled: boolean;
  1898. config: Record<string, unknown>;
  1899. // Print lifecycle events
  1900. on_print_start: boolean;
  1901. on_print_complete: boolean;
  1902. on_print_failed: boolean;
  1903. on_print_stopped: boolean;
  1904. on_print_progress: boolean;
  1905. on_print_missing_spool_assignment: boolean;
  1906. // Printer status events
  1907. on_printer_offline: boolean;
  1908. on_printer_error: boolean;
  1909. on_filament_low: boolean;
  1910. on_maintenance_due: boolean;
  1911. // AMS environmental alarms (regular AMS)
  1912. on_ams_humidity_high: boolean;
  1913. on_ams_temperature_high: boolean;
  1914. // AMS-HT environmental alarms
  1915. on_ams_ht_humidity_high: boolean;
  1916. on_ams_ht_temperature_high: boolean;
  1917. // Build plate detection
  1918. on_plate_not_empty: boolean;
  1919. // Bed cooled
  1920. on_bed_cooled: boolean;
  1921. // First layer complete
  1922. on_first_layer_complete: boolean;
  1923. // Inventory stock alerts
  1924. on_stock_reorder_alert: boolean;
  1925. on_stock_break_alert: boolean;
  1926. // Print queue events
  1927. on_queue_job_added: boolean;
  1928. on_queue_job_assigned: boolean;
  1929. on_queue_job_started: boolean;
  1930. on_queue_job_waiting: boolean;
  1931. on_queue_job_skipped: boolean;
  1932. on_queue_job_failed: boolean;
  1933. on_queue_completed: boolean;
  1934. // Quiet hours
  1935. quiet_hours_enabled: boolean;
  1936. quiet_hours_start: string | null;
  1937. quiet_hours_end: string | null;
  1938. // Daily digest
  1939. daily_digest_enabled: boolean;
  1940. daily_digest_time: string | null;
  1941. // Printer filter
  1942. printer_id: number | null;
  1943. // Status tracking
  1944. last_success: string | null;
  1945. last_error: string | null;
  1946. last_error_at: string | null;
  1947. // Timestamps
  1948. created_at: string;
  1949. updated_at: string;
  1950. }
  1951. export interface NotificationProviderCreate {
  1952. name: string;
  1953. provider_type: ProviderType;
  1954. enabled?: boolean;
  1955. config: Record<string, unknown>;
  1956. // Print lifecycle events
  1957. on_print_start?: boolean;
  1958. on_print_complete?: boolean;
  1959. on_print_failed?: boolean;
  1960. on_print_stopped?: boolean;
  1961. on_print_progress?: boolean;
  1962. on_print_missing_spool_assignment?: boolean;
  1963. // Printer status events
  1964. on_printer_offline?: boolean;
  1965. on_printer_error?: boolean;
  1966. on_filament_low?: boolean;
  1967. on_maintenance_due?: boolean;
  1968. // AMS environmental alarms (regular AMS)
  1969. on_ams_humidity_high?: boolean;
  1970. on_ams_temperature_high?: boolean;
  1971. // AMS-HT environmental alarms
  1972. on_ams_ht_humidity_high?: boolean;
  1973. on_ams_ht_temperature_high?: boolean;
  1974. // Build plate detection
  1975. on_plate_not_empty?: boolean;
  1976. // Bed cooled
  1977. on_bed_cooled?: boolean;
  1978. // First layer complete
  1979. on_first_layer_complete?: boolean;
  1980. // Inventory stock alerts
  1981. on_stock_reorder_alert?: boolean;
  1982. on_stock_break_alert?: boolean;
  1983. // Print queue events
  1984. on_queue_job_added?: boolean;
  1985. on_queue_job_assigned?: boolean;
  1986. on_queue_job_started?: boolean;
  1987. on_queue_job_waiting?: boolean;
  1988. on_queue_job_skipped?: boolean;
  1989. on_queue_job_failed?: boolean;
  1990. on_queue_completed?: boolean;
  1991. // Quiet hours
  1992. quiet_hours_enabled?: boolean;
  1993. quiet_hours_start?: string | null;
  1994. quiet_hours_end?: string | null;
  1995. // Daily digest
  1996. daily_digest_enabled?: boolean;
  1997. daily_digest_time?: string | null;
  1998. // Printer filter
  1999. printer_id?: number | null;
  2000. }
  2001. export interface NotificationProviderUpdate {
  2002. name?: string;
  2003. provider_type?: ProviderType;
  2004. enabled?: boolean;
  2005. config?: Record<string, unknown>;
  2006. // Print lifecycle events
  2007. on_print_start?: boolean;
  2008. on_print_complete?: boolean;
  2009. on_print_failed?: boolean;
  2010. on_print_stopped?: boolean;
  2011. on_print_progress?: boolean;
  2012. on_print_missing_spool_assignment?: boolean;
  2013. // Printer status events
  2014. on_printer_offline?: boolean;
  2015. on_printer_error?: boolean;
  2016. on_filament_low?: boolean;
  2017. on_maintenance_due?: boolean;
  2018. // AMS environmental alarms (regular AMS)
  2019. on_ams_humidity_high?: boolean;
  2020. on_ams_temperature_high?: boolean;
  2021. // AMS-HT environmental alarms
  2022. on_ams_ht_humidity_high?: boolean;
  2023. on_ams_ht_temperature_high?: boolean;
  2024. // Build plate detection
  2025. on_plate_not_empty?: boolean;
  2026. // Bed cooled
  2027. on_bed_cooled?: boolean;
  2028. // First layer complete
  2029. on_first_layer_complete?: boolean;
  2030. // Inventory stock alerts
  2031. on_stock_reorder_alert?: boolean;
  2032. on_stock_break_alert?: boolean;
  2033. // Print queue events
  2034. on_queue_job_added?: boolean;
  2035. on_queue_job_assigned?: boolean;
  2036. on_queue_job_started?: boolean;
  2037. on_queue_job_waiting?: boolean;
  2038. on_queue_job_skipped?: boolean;
  2039. on_queue_job_failed?: boolean;
  2040. on_queue_completed?: boolean;
  2041. // Quiet hours
  2042. quiet_hours_enabled?: boolean;
  2043. quiet_hours_start?: string | null;
  2044. quiet_hours_end?: string | null;
  2045. // Daily digest
  2046. daily_digest_enabled?: boolean;
  2047. daily_digest_time?: string | null;
  2048. // Printer filter
  2049. printer_id?: number | null;
  2050. }
  2051. // GitHub Backup types
  2052. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  2053. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  2054. export interface GitHubBackupConfig {
  2055. id: number;
  2056. repository_url: string;
  2057. has_token: boolean;
  2058. branch: string;
  2059. provider: GitProviderType;
  2060. allow_insecure_http: boolean;
  2061. schedule_enabled: boolean;
  2062. schedule_type: ScheduleType;
  2063. backup_kprofiles: boolean;
  2064. backup_cloud_profiles: boolean;
  2065. backup_settings: boolean;
  2066. backup_spools: boolean;
  2067. backup_archives: boolean;
  2068. enabled: boolean;
  2069. last_backup_at: string | null;
  2070. last_backup_status: string | null;
  2071. last_backup_message: string | null;
  2072. last_backup_commit_sha: string | null;
  2073. next_scheduled_run: string | null;
  2074. created_at: string;
  2075. updated_at: string;
  2076. }
  2077. export interface GitHubBackupConfigCreate {
  2078. repository_url: string;
  2079. access_token: string;
  2080. branch?: string;
  2081. provider?: GitProviderType;
  2082. allow_insecure_http?: boolean;
  2083. schedule_enabled?: boolean;
  2084. schedule_type?: ScheduleType;
  2085. backup_kprofiles?: boolean;
  2086. backup_cloud_profiles?: boolean;
  2087. backup_settings?: boolean;
  2088. backup_spools?: boolean;
  2089. backup_archives?: boolean;
  2090. enabled?: boolean;
  2091. }
  2092. export interface GitHubBackupLog {
  2093. id: number;
  2094. config_id: number;
  2095. started_at: string;
  2096. completed_at: string | null;
  2097. status: string;
  2098. trigger: string;
  2099. commit_sha: string | null;
  2100. files_changed: number;
  2101. error_message: string | null;
  2102. }
  2103. export interface GitHubBackupStatus {
  2104. configured: boolean;
  2105. enabled: boolean;
  2106. is_running: boolean;
  2107. progress: string | null;
  2108. last_backup_at: string | null;
  2109. last_backup_status: string | null;
  2110. next_scheduled_run: string | null;
  2111. }
  2112. export interface LocalBackupStatus {
  2113. enabled: boolean;
  2114. schedule: string;
  2115. time: string;
  2116. retention: number;
  2117. path: string;
  2118. default_path: string;
  2119. is_running: boolean;
  2120. last_backup_at: string | null;
  2121. last_status: string | null;
  2122. last_message: string | null;
  2123. next_run: string | null;
  2124. }
  2125. export interface LocalBackupFile {
  2126. filename: string;
  2127. size: number;
  2128. created_at: string;
  2129. }
  2130. export interface ObicoDetectionEvent {
  2131. printer_id: number;
  2132. task_name: string;
  2133. timestamp: string;
  2134. current_p: number;
  2135. score: number;
  2136. class: 'safe' | 'warning' | 'failure';
  2137. detections: number;
  2138. }
  2139. export interface ObicoStatus {
  2140. is_running: boolean;
  2141. last_error: string | null;
  2142. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  2143. thresholds: { low: number; high: number };
  2144. history: ObicoDetectionEvent[];
  2145. enabled: boolean;
  2146. ml_url: string;
  2147. sensitivity: 'low' | 'medium' | 'high';
  2148. action: 'notify' | 'pause' | 'pause_and_off';
  2149. poll_interval: number;
  2150. external_url_configured: boolean;
  2151. }
  2152. export interface ObicoTestConnection {
  2153. ok: boolean;
  2154. status_code: number | null;
  2155. body: string | null;
  2156. error: string | null;
  2157. }
  2158. export interface GitHubTestConnectionResponse {
  2159. success: boolean;
  2160. message: string;
  2161. repo_name: string | null;
  2162. permissions: Record<string, boolean> | null;
  2163. // true = confirmed private, false = confirmed public/internal,
  2164. // null = could not determine. Backend rejects save unless true.
  2165. is_private: boolean | null;
  2166. }
  2167. export interface GitHubBackupTriggerResponse {
  2168. success: boolean;
  2169. message: string;
  2170. log_id: number | null;
  2171. commit_sha: string | null;
  2172. files_changed: number;
  2173. }
  2174. export interface NotificationTestRequest {
  2175. provider_type: ProviderType;
  2176. config: Record<string, unknown>;
  2177. }
  2178. export interface NotificationTestResponse {
  2179. success: boolean;
  2180. message: string;
  2181. }
  2182. export interface BackgroundDispatchResponse {
  2183. status: 'dispatched' | string;
  2184. printer_id: number;
  2185. archive_id?: number | null;
  2186. filename: string;
  2187. dispatch_job_id: number;
  2188. dispatch_position: number;
  2189. }
  2190. // Provider-specific config types for reference
  2191. export interface CallMeBotConfig {
  2192. phone: string;
  2193. apikey: string;
  2194. }
  2195. export interface NtfyConfig {
  2196. server?: string;
  2197. topic: string;
  2198. auth_token?: string | null;
  2199. }
  2200. export interface PushoverConfig {
  2201. user_key: string;
  2202. app_token: string;
  2203. priority?: number;
  2204. }
  2205. export interface TelegramConfig {
  2206. bot_token: string;
  2207. chat_id: string;
  2208. }
  2209. export interface EmailConfig {
  2210. smtp_server: string;
  2211. smtp_port?: number;
  2212. username: string;
  2213. password: string;
  2214. from_email: string;
  2215. to_email: string;
  2216. use_tls?: boolean;
  2217. }
  2218. // Notification Template types
  2219. export interface NotificationTemplate {
  2220. id: number;
  2221. event_type: string;
  2222. name: string;
  2223. title_template: string;
  2224. body_template: string;
  2225. is_default: boolean;
  2226. created_at: string;
  2227. updated_at: string;
  2228. }
  2229. export interface NotificationTemplateUpdate {
  2230. title_template?: string;
  2231. body_template?: string;
  2232. }
  2233. export interface EventVariablesResponse {
  2234. event_type: string;
  2235. event_name: string;
  2236. variables: string[];
  2237. }
  2238. export interface TemplatePreviewRequest {
  2239. event_type: string;
  2240. title_template: string;
  2241. body_template: string;
  2242. }
  2243. export interface TemplatePreviewResponse {
  2244. title: string;
  2245. body: string;
  2246. }
  2247. // Notification Log types
  2248. export interface NotificationLogEntry {
  2249. id: number;
  2250. provider_id: number;
  2251. provider_name: string | null;
  2252. provider_type: string | null;
  2253. event_type: string;
  2254. title: string;
  2255. message: string;
  2256. success: boolean;
  2257. error_message: string | null;
  2258. printer_id: number | null;
  2259. printer_name: string | null;
  2260. created_at: string;
  2261. }
  2262. export interface NotificationLogStats {
  2263. total: number;
  2264. success_count: number;
  2265. failure_count: number;
  2266. by_event_type: Record<string, number>;
  2267. by_provider: Record<string, number>;
  2268. }
  2269. // Spoolman types
  2270. export interface SpoolmanStatus {
  2271. enabled: boolean;
  2272. connected: boolean;
  2273. url: string | null;
  2274. }
  2275. export interface SkippedSpool {
  2276. location: string;
  2277. reason: string;
  2278. filament_type: string | null;
  2279. color: string | null;
  2280. }
  2281. export interface SpoolmanSyncResult {
  2282. success: boolean;
  2283. synced_count: number;
  2284. skipped_count: number;
  2285. skipped: SkippedSpool[];
  2286. errors: string[];
  2287. }
  2288. export interface UnlinkedSpool {
  2289. id: number;
  2290. filament_name: string | null;
  2291. filament_vendor: string | null;
  2292. filament_material: string | null;
  2293. filament_color_hex: string | null;
  2294. remaining_weight: number | null;
  2295. location: string | null;
  2296. }
  2297. export interface LinkedSpoolInfo {
  2298. id: number;
  2299. remaining_weight: number | null;
  2300. filament_weight: number | null;
  2301. }
  2302. export interface LinkedSpoolsMap {
  2303. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  2304. }
  2305. export interface SpoolmanVendor {
  2306. id: number;
  2307. name: string;
  2308. }
  2309. export interface SpoolmanFilamentEntry {
  2310. id: number;
  2311. name: string;
  2312. material: string | null;
  2313. color_hex: string | null;
  2314. color_name: string | null;
  2315. weight: number | null;
  2316. spool_weight: number | null;
  2317. vendor: SpoolmanVendor | null;
  2318. }
  2319. // Inventory types
  2320. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  2321. export type SpoolLabelTemplate =
  2322. | 'ams_holder_74x33'
  2323. | 'ams_holder_75x55'
  2324. | 'box_40x30'
  2325. | 'box_62x29'
  2326. | 'avery_5160'
  2327. | 'avery_l7160';
  2328. export interface InventorySpool {
  2329. id: number;
  2330. material: string;
  2331. subtype: string | null;
  2332. color_name: string | null;
  2333. // True when color_name was synthesised from subtype because Spoolman has no
  2334. // stored value (Spoolman-backed inventory only). The edit form uses this to
  2335. // leave the input blank, so the user doesn't round-trip the synth value
  2336. // back to Spoolman as if it were a real user-set color_name (#1319).
  2337. color_name_is_synthesized?: boolean;
  2338. rgba: string | null;
  2339. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  2340. extra_colors: string | null;
  2341. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  2342. effect_type: string | null;
  2343. brand: string | null;
  2344. label_weight: number;
  2345. core_weight: number;
  2346. core_weight_catalog_id: number | null;
  2347. weight_used: number;
  2348. // Anchor for the resettable "Total Consumed" display (#1390). The
  2349. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  2350. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  2351. // zeroes the counter without disturbing remaining. Optional for back-compat
  2352. // with rows from a pre-migration DB snapshot — default to 0.
  2353. weight_used_baseline?: number;
  2354. slicer_filament: string | null;
  2355. slicer_filament_name: string | null;
  2356. nozzle_temp_min: number | null;
  2357. nozzle_temp_max: number | null;
  2358. note: string | null;
  2359. added_full: boolean | null;
  2360. last_used: string | null;
  2361. encode_time: string | null;
  2362. tag_uid: string | null;
  2363. tray_uuid: string | null;
  2364. data_origin: string | null;
  2365. tag_type: string | null;
  2366. archived_at: string | null;
  2367. created_at: string;
  2368. updated_at: string;
  2369. cost_per_kg: number | null;
  2370. last_scale_weight: number | null;
  2371. last_weighed_at: string | null;
  2372. // User-defined category + per-spool low-stock threshold override (#729).
  2373. category: string | null;
  2374. low_stock_threshold_pct: number | null;
  2375. k_profiles?: SpoolKProfile[];
  2376. storage_location?: string | null;
  2377. }
  2378. export interface SpoolmanBulkCreateResult {
  2379. created: InventorySpool[];
  2380. requested_count: number;
  2381. failed_count: number;
  2382. }
  2383. export interface SpoolUsageRecord {
  2384. id: number;
  2385. spool_id: number;
  2386. printer_id: number | null;
  2387. print_name: string | null;
  2388. weight_used: number;
  2389. percent_used: number;
  2390. status: string;
  2391. cost: number | null;
  2392. created_at: string;
  2393. }
  2394. export interface SpoolKProfile {
  2395. id: number;
  2396. spool_id: number;
  2397. printer_id: number;
  2398. extruder: number;
  2399. nozzle_diameter: string;
  2400. nozzle_type: string | null;
  2401. k_value: number;
  2402. name: string | null;
  2403. cali_idx: number | null;
  2404. setting_id: string | null;
  2405. created_at: string;
  2406. }
  2407. export interface SpoolKProfileInput {
  2408. printer_id: number;
  2409. extruder?: number;
  2410. nozzle_diameter?: string;
  2411. nozzle_type?: string | null;
  2412. k_value: number;
  2413. name?: string | null;
  2414. cali_idx?: number | null;
  2415. setting_id?: string | null;
  2416. }
  2417. export interface SpoolAssignment {
  2418. id: number;
  2419. spool_id: number;
  2420. printer_id: number;
  2421. printer_name: string | null;
  2422. ams_id: number;
  2423. tray_id: number;
  2424. fingerprint_color: string | null;
  2425. fingerprint_type: string | null;
  2426. spool?: InventorySpool | null;
  2427. configured: boolean;
  2428. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  2429. created_at: string;
  2430. ams_label?: string | null; // User-defined friendly name for the AMS unit
  2431. }
  2432. export interface FilamentSkuSettings {
  2433. id: number;
  2434. material: string;
  2435. subtype: string | null;
  2436. brand: string | null;
  2437. lead_time_days: number;
  2438. safety_margin_value: number;
  2439. safety_margin_unit: 'days' | 'g';
  2440. alerts_snoozed: boolean;
  2441. }
  2442. export interface ShoppingListItem {
  2443. id: number;
  2444. material: string;
  2445. subtype: string | null;
  2446. brand: string | null;
  2447. quantity_spools: number;
  2448. note: string | null;
  2449. status: 'pending' | 'purchased' | 'received';
  2450. purchased_at: string | null;
  2451. added_at: string;
  2452. }
  2453. export interface ShoppingListItemCreate {
  2454. material: string;
  2455. subtype: string | null;
  2456. brand: string | null;
  2457. quantity_spools: number;
  2458. note?: string | null;
  2459. }
  2460. // Update types
  2461. export interface VersionInfo {
  2462. version: string;
  2463. repo: string;
  2464. }
  2465. export interface UpdateCheckResult {
  2466. update_available: boolean;
  2467. current_version: string;
  2468. latest_version: string | null;
  2469. release_name?: string;
  2470. release_notes?: string;
  2471. release_url?: string;
  2472. published_at?: string;
  2473. error?: string;
  2474. message?: string;
  2475. is_docker?: boolean;
  2476. is_ha_addon?: boolean;
  2477. update_method?: 'docker' | 'git' | 'ha_addon';
  2478. }
  2479. export interface UpdateStatus {
  2480. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  2481. progress: number;
  2482. message: string;
  2483. error: string | null;
  2484. }
  2485. // Maintenance types
  2486. export interface MaintenanceType {
  2487. id: number;
  2488. name: string;
  2489. description: string | null;
  2490. default_interval_hours: number;
  2491. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  2492. icon: string | null;
  2493. wiki_url: string | null; // Documentation link
  2494. is_system: boolean;
  2495. created_at: string;
  2496. }
  2497. export interface MaintenanceTypeCreate {
  2498. name: string;
  2499. description?: string | null;
  2500. default_interval_hours?: number;
  2501. interval_type?: 'hours' | 'days';
  2502. icon?: string | null;
  2503. wiki_url?: string | null;
  2504. }
  2505. export interface MaintenanceStatus {
  2506. id: number;
  2507. printer_id: number;
  2508. printer_name: string;
  2509. printer_model: string | null;
  2510. maintenance_type_id: number;
  2511. maintenance_type_name: string;
  2512. maintenance_type_icon: string | null;
  2513. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  2514. enabled: boolean;
  2515. interval_hours: number; // For hours type: print hours; for days type: number of days
  2516. interval_type: 'hours' | 'days';
  2517. current_hours: number;
  2518. hours_since_maintenance: number;
  2519. hours_until_due: number;
  2520. days_since_maintenance: number | null; // For days type
  2521. days_until_due: number | null; // For days type
  2522. is_due: boolean;
  2523. is_warning: boolean;
  2524. last_performed_at: string | null;
  2525. }
  2526. export interface PrinterMaintenanceOverview {
  2527. printer_id: number;
  2528. printer_name: string;
  2529. printer_model: string | null;
  2530. total_print_hours: number;
  2531. maintenance_items: MaintenanceStatus[];
  2532. due_count: number;
  2533. warning_count: number;
  2534. }
  2535. export interface MaintenanceHistory {
  2536. id: number;
  2537. printer_maintenance_id: number;
  2538. performed_at: string;
  2539. hours_at_maintenance: number;
  2540. notes: string | null;
  2541. }
  2542. export interface MaintenanceSummary {
  2543. total_due: number;
  2544. total_warning: number;
  2545. printers_with_issues: Array<{
  2546. printer_id: number;
  2547. printer_name: string;
  2548. due_count: number;
  2549. warning_count: number;
  2550. }>;
  2551. }
  2552. // External Links (sidebar)
  2553. export interface ExternalLink {
  2554. id: number;
  2555. name: string;
  2556. url: string;
  2557. icon: string;
  2558. open_in_new_tab: boolean;
  2559. custom_icon: string | null;
  2560. sort_order: number;
  2561. created_at: string;
  2562. updated_at: string;
  2563. }
  2564. export interface ExternalLinkCreate {
  2565. name: string;
  2566. url: string;
  2567. icon: string;
  2568. open_in_new_tab?: boolean;
  2569. }
  2570. export interface ExternalLinkUpdate {
  2571. name?: string;
  2572. url?: string;
  2573. icon?: string;
  2574. open_in_new_tab?: boolean;
  2575. }
  2576. // Permission type - all available permissions
  2577. export type Permission =
  2578. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  2579. | 'archives:read' | 'archives:create'
  2580. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  2581. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  2582. | 'queue:read' | 'queue:create'
  2583. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  2584. | 'queue:reorder'
  2585. | 'library:read' | 'library:upload'
  2586. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  2587. | 'library:purge'
  2588. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  2589. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  2590. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  2591. | 'inventory:forecast_read' | 'inventory:forecast_write'
  2592. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  2593. | 'camera:view'
  2594. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  2595. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  2596. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  2597. | 'notification_templates:read' | 'notification_templates:update'
  2598. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  2599. | 'discovery:scan'
  2600. | 'firmware:read' | 'firmware:update'
  2601. | 'ams_history:read'
  2602. | 'stats:read' | 'stats:filter_by_user'
  2603. | 'system:read'
  2604. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  2605. | 'github:backup' | 'github:restore'
  2606. | 'cloud:auth'
  2607. | 'makerworld:view' | 'makerworld:import'
  2608. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  2609. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  2610. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  2611. | 'websocket:connect';
  2612. // Group types
  2613. export interface GroupBrief {
  2614. id: number;
  2615. name: string;
  2616. }
  2617. export interface Group {
  2618. id: number;
  2619. name: string;
  2620. description: string | null;
  2621. permissions: Permission[];
  2622. is_system: boolean;
  2623. user_count: number;
  2624. created_at: string;
  2625. updated_at: string;
  2626. }
  2627. export interface GroupDetail extends Group {
  2628. users: Array<{ id: number; username: string; is_active: boolean }>;
  2629. }
  2630. export interface GroupCreate {
  2631. name: string;
  2632. description?: string;
  2633. permissions: Permission[];
  2634. }
  2635. export interface GroupUpdate {
  2636. name?: string;
  2637. description?: string;
  2638. permissions?: Permission[];
  2639. }
  2640. export interface PermissionInfo {
  2641. value: Permission;
  2642. label: string;
  2643. }
  2644. export interface PermissionCategory {
  2645. name: string;
  2646. permissions: PermissionInfo[];
  2647. }
  2648. export interface PermissionsListResponse {
  2649. categories: PermissionCategory[];
  2650. all_permissions: Permission[];
  2651. }
  2652. // User email notification preferences
  2653. export interface UserEmailPreferences {
  2654. notify_print_start: boolean;
  2655. notify_print_complete: boolean;
  2656. notify_print_failed: boolean;
  2657. notify_print_stopped: boolean;
  2658. }
  2659. // Auth types
  2660. export interface LoginRequest {
  2661. username: string;
  2662. password: string;
  2663. }
  2664. export interface LoginResponse {
  2665. access_token?: string;
  2666. token_type?: string;
  2667. user?: UserResponse;
  2668. /** Set when 2FA verification is required before a full token is issued. */
  2669. requires_2fa?: boolean;
  2670. pre_auth_token?: string;
  2671. two_fa_methods?: string[];
  2672. }
  2673. export interface UserResponse {
  2674. id: number;
  2675. username: string;
  2676. email?: string;
  2677. role: string; // Deprecated, kept for backward compatibility
  2678. is_active: boolean;
  2679. is_admin: boolean; // Computed from role and group membership
  2680. auth_source: string; // "local" or "ldap"
  2681. groups: GroupBrief[];
  2682. permissions: Permission[]; // All permissions from groups
  2683. created_at: string;
  2684. }
  2685. export interface UserCreate {
  2686. username: string;
  2687. password?: string; // Optional when advanced auth is enabled
  2688. email?: string;
  2689. role: string;
  2690. group_ids?: number[];
  2691. }
  2692. export interface UserUpdate {
  2693. username?: string;
  2694. password?: string;
  2695. email?: string;
  2696. role?: string;
  2697. is_active?: boolean;
  2698. group_ids?: number[];
  2699. }
  2700. export interface SetupRequest {
  2701. auth_enabled: boolean;
  2702. admin_username?: string;
  2703. admin_password?: string;
  2704. }
  2705. export interface ForgotPasswordRequest {
  2706. email: string;
  2707. }
  2708. export interface ForgotPasswordResponse {
  2709. message: string;
  2710. }
  2711. export interface ResetPasswordRequest {
  2712. user_id: number;
  2713. }
  2714. export interface ResetPasswordResponse {
  2715. message: string;
  2716. }
  2717. export interface SMTPSettings {
  2718. smtp_host: string;
  2719. smtp_port: number;
  2720. smtp_username?: string;
  2721. smtp_password?: string;
  2722. smtp_security: 'starttls' | 'ssl' | 'none';
  2723. smtp_auth_enabled: boolean;
  2724. smtp_from_email: string;
  2725. smtp_from_name: string;
  2726. }
  2727. // 2FA / MFA interfaces
  2728. export interface TwoFAStatus {
  2729. totp_enabled: boolean;
  2730. email_otp_enabled: boolean;
  2731. backup_codes_remaining: number;
  2732. }
  2733. export interface TOTPSetupResponse {
  2734. secret: string;
  2735. qr_code_b64: string;
  2736. issuer: string;
  2737. }
  2738. export interface TOTPEnableResponse {
  2739. message: string;
  2740. backup_codes: string[];
  2741. }
  2742. export interface BackupCodesResponse {
  2743. backup_codes: string[];
  2744. message: string;
  2745. }
  2746. export interface TwoFAVerifyRequest {
  2747. pre_auth_token: string;
  2748. code: string;
  2749. method: 'totp' | 'email' | 'backup';
  2750. }
  2751. /**
  2752. * A URL that is known to be same-origin (a relative path starting with ``/``).
  2753. *
  2754. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  2755. * can be distinguished from arbitrary strings at the type level. The brand
  2756. * is compile-time only; at runtime these are plain strings.
  2757. *
  2758. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  2759. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  2760. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  2761. * that no external URL slips through.
  2762. */
  2763. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  2764. // OIDC interfaces
  2765. export interface OIDCProvider {
  2766. id: number;
  2767. name: string;
  2768. issuer_url: string;
  2769. client_id: string;
  2770. scopes: string;
  2771. is_enabled: boolean;
  2772. auto_create_users: boolean;
  2773. auto_link_existing_accounts: boolean;
  2774. email_claim: string;
  2775. require_email_verified: boolean;
  2776. icon_url?: string | null;
  2777. default_group_id?: number | null;
  2778. // True when the backend has cached icon bytes for this provider.
  2779. // Login page / admin preview consume this via the proxy URL
  2780. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  2781. // hotlinks the external icon URL — that would require loosening
  2782. // the strict img-src CSP. Required, not optional: the backend always
  2783. // includes this field in the response (Pydantic default-False is
  2784. // populated unconditionally in the route handler).
  2785. has_icon: boolean;
  2786. }
  2787. export interface OIDCProviderCreate {
  2788. name: string;
  2789. issuer_url: string;
  2790. client_id: string;
  2791. client_secret: string;
  2792. scopes?: string;
  2793. is_enabled?: boolean;
  2794. auto_create_users?: boolean;
  2795. auto_link_existing_accounts?: boolean;
  2796. email_claim?: string;
  2797. require_email_verified?: boolean;
  2798. icon_url?: string | null;
  2799. default_group_id?: number | null;
  2800. }
  2801. export interface OIDCLink {
  2802. id: number;
  2803. provider_id: number;
  2804. provider_name: string;
  2805. provider_email?: string | null;
  2806. created_at: string;
  2807. }
  2808. export interface TestSMTPRequest {
  2809. test_recipient: string;
  2810. }
  2811. export interface TestSMTPResponse {
  2812. success: boolean;
  2813. message: string;
  2814. }
  2815. export interface AdvancedAuthStatus {
  2816. advanced_auth_enabled: boolean;
  2817. smtp_configured: boolean;
  2818. }
  2819. export interface LDAPStatus {
  2820. ldap_enabled: boolean;
  2821. ldap_configured: boolean;
  2822. }
  2823. export interface EncryptionRowCounts {
  2824. oidc_providers: number;
  2825. user_totp: number;
  2826. }
  2827. export interface EncryptionStatus {
  2828. key_configured: boolean;
  2829. key_source: 'env' | 'file' | 'generated' | 'none';
  2830. legacy_plaintext_rows: EncryptionRowCounts;
  2831. encrypted_rows: EncryptionRowCounts;
  2832. decryption_broken: boolean;
  2833. // B2: count of rows skipped during the last legacy re-encryption migration.
  2834. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  2835. migration_error_count: number;
  2836. }
  2837. export interface LDAPTestResponse {
  2838. success: boolean;
  2839. message: string;
  2840. }
  2841. export interface LDAPSearchResult {
  2842. username: string;
  2843. email: string | null;
  2844. display_name: string | null;
  2845. dn: string;
  2846. already_provisioned: boolean;
  2847. }
  2848. export interface SetupResponse {
  2849. auth_enabled: boolean;
  2850. admin_created?: boolean;
  2851. }
  2852. export interface AuthStatus {
  2853. auth_enabled: boolean;
  2854. requires_setup: boolean;
  2855. }
  2856. // API functions
  2857. export const api = {
  2858. // Authentication
  2859. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  2860. setupAuth: (data: SetupRequest) =>
  2861. request<SetupResponse>('/auth/setup', {
  2862. method: 'POST',
  2863. body: JSON.stringify(data),
  2864. }),
  2865. login: (data: LoginRequest) =>
  2866. request<LoginResponse>('/auth/login', {
  2867. method: 'POST',
  2868. body: JSON.stringify(data),
  2869. }),
  2870. logout: () =>
  2871. request<{ message: string }>('/auth/logout', {
  2872. method: 'POST',
  2873. }),
  2874. getCurrentUser: () => request<UserResponse>('/auth/me'),
  2875. disableAuth: () =>
  2876. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  2877. method: 'POST',
  2878. }),
  2879. // Advanced Authentication
  2880. testSMTP: (data: TestSMTPRequest) =>
  2881. request<TestSMTPResponse>('/auth/smtp/test', {
  2882. method: 'POST',
  2883. body: JSON.stringify(data),
  2884. }),
  2885. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  2886. saveSMTPSettings: (data: SMTPSettings) =>
  2887. request<{ message: string }>('/auth/smtp', {
  2888. method: 'POST',
  2889. body: JSON.stringify(data),
  2890. }),
  2891. enableAdvancedAuth: () =>
  2892. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  2893. method: 'POST',
  2894. }),
  2895. disableAdvancedAuth: () =>
  2896. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  2897. method: 'POST',
  2898. }),
  2899. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  2900. // LDAP Authentication
  2901. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  2902. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  2903. testLDAP: () =>
  2904. request<LDAPTestResponse>('/auth/ldap/test', {
  2905. method: 'POST',
  2906. }),
  2907. searchLDAPDirectory: (q: string) =>
  2908. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  2909. provisionLDAPUser: (username: string) =>
  2910. request<UserResponse>('/auth/ldap/provision', {
  2911. method: 'POST',
  2912. body: JSON.stringify({ username }),
  2913. }),
  2914. forgotPassword: (data: ForgotPasswordRequest) =>
  2915. request<ForgotPasswordResponse>('/auth/forgot-password', {
  2916. method: 'POST',
  2917. body: JSON.stringify(data),
  2918. }),
  2919. // H-6: Confirm password reset using the token from the emailed link
  2920. forgotPasswordConfirm: (token: string, newPassword: string) =>
  2921. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  2922. method: 'POST',
  2923. body: JSON.stringify({ token, new_password: newPassword }),
  2924. }),
  2925. resetUserPassword: (data: ResetPasswordRequest) =>
  2926. request<ResetPasswordResponse>('/auth/reset-password', {
  2927. method: 'POST',
  2928. body: JSON.stringify(data),
  2929. }),
  2930. // 2FA - status
  2931. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  2932. // 2FA - TOTP
  2933. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  2934. enableTOTP: (code: string) =>
  2935. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  2936. method: 'POST',
  2937. body: JSON.stringify({ code }),
  2938. }),
  2939. disableTOTP: (code: string) =>
  2940. request<{ message: string }>('/auth/2fa/totp/disable', {
  2941. method: 'POST',
  2942. body: JSON.stringify({ code }),
  2943. }),
  2944. regenerateBackupCodes: (code: string) =>
  2945. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  2946. method: 'POST',
  2947. body: JSON.stringify({ code }),
  2948. }),
  2949. // 2FA - Email OTP
  2950. // Step 1: send a verification code to the user's email (proof of possession)
  2951. enableEmailOTP: () =>
  2952. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  2953. // Step 2: confirm with the code received by email
  2954. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  2955. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  2956. method: 'POST',
  2957. body: JSON.stringify({ setup_token, code }),
  2958. }),
  2959. // Disable requires account password for re-auth
  2960. disableEmailOTP: (password: string) =>
  2961. request<{ message: string }>('/auth/2fa/email/disable', {
  2962. method: 'POST',
  2963. body: JSON.stringify({ password }),
  2964. }),
  2965. sendEmailOTP: (preAuthToken: string) =>
  2966. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  2967. method: 'POST',
  2968. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  2969. }),
  2970. // 2FA - verify (completes login)
  2971. verify2FA: (data: TwoFAVerifyRequest) =>
  2972. request<LoginResponse>('/auth/2fa/verify', {
  2973. method: 'POST',
  2974. body: JSON.stringify(data),
  2975. }),
  2976. // 2FA - admin
  2977. admin2FADisable: (userId: number) =>
  2978. request<{ message: string }>(`/auth/2fa/admin/${userId}`, { method: 'DELETE' }),
  2979. // OIDC providers (public list)
  2980. getOIDCProviders: () => request<OIDCProvider[]>('/auth/oidc/providers'),
  2981. // OIDC providers (admin)
  2982. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  2983. createOIDCProvider: (data: OIDCProviderCreate) =>
  2984. request<OIDCProvider>('/auth/oidc/providers', {
  2985. method: 'POST',
  2986. body: JSON.stringify(data),
  2987. }),
  2988. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  2989. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  2990. method: 'PUT',
  2991. body: JSON.stringify(data),
  2992. }),
  2993. deleteOIDCProvider: (id: number) =>
  2994. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  2995. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  2996. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  2997. // so a future caller can't accidentally substitute an attacker-
  2998. // controlled URL where this is consumed.
  2999. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  3000. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  3001. deleteOIDCProviderIcon: (id: number) =>
  3002. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  3003. refreshOIDCProviderIcon: (id: number) =>
  3004. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  3005. // OIDC authorize URL
  3006. getOIDCAuthorizeUrl: (providerId: number) =>
  3007. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  3008. // OIDC exchange token for JWT
  3009. exchangeOIDCToken: (oidcToken: string) =>
  3010. request<LoginResponse>('/auth/oidc/exchange', {
  3011. method: 'POST',
  3012. body: JSON.stringify({ oidc_token: oidcToken }),
  3013. }),
  3014. // OIDC links for current user
  3015. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  3016. deleteOIDCLink: (providerId: number) =>
  3017. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  3018. // Users
  3019. getUsers: () => request<UserResponse[]>('/users/'),
  3020. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  3021. createUser: (data: UserCreate) =>
  3022. request<UserResponse>('/users/', {
  3023. method: 'POST',
  3024. body: JSON.stringify(data),
  3025. }),
  3026. updateUser: (id: number, data: UserUpdate) =>
  3027. request<UserResponse>(`/users/${id}`, {
  3028. method: 'PATCH',
  3029. body: JSON.stringify(data),
  3030. }),
  3031. deleteUser: (id: number, deleteItems: boolean = false) =>
  3032. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  3033. method: 'DELETE',
  3034. }),
  3035. getUserItemsCount: (id: number) =>
  3036. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  3037. changePassword: (currentPassword: string, newPassword: string) =>
  3038. request<{ message: string }>('/users/me/change-password', {
  3039. method: 'POST',
  3040. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  3041. }),
  3042. // User Email Notifications
  3043. getUserEmailPreferences: () =>
  3044. request<UserEmailPreferences>('/user-notifications/preferences'),
  3045. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  3046. request<UserEmailPreferences>('/user-notifications/preferences', {
  3047. method: 'PUT',
  3048. body: JSON.stringify(data),
  3049. }),
  3050. // Groups
  3051. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  3052. getGroups: () => request<Group[]>('/groups/'),
  3053. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  3054. createGroup: (data: GroupCreate) =>
  3055. request<Group>('/groups/', {
  3056. method: 'POST',
  3057. body: JSON.stringify(data),
  3058. }),
  3059. updateGroup: (id: number, data: GroupUpdate) =>
  3060. request<Group>(`/groups/${id}`, {
  3061. method: 'PATCH',
  3062. body: JSON.stringify(data),
  3063. }),
  3064. deleteGroup: (id: number) =>
  3065. request<void>(`/groups/${id}`, {
  3066. method: 'DELETE',
  3067. }),
  3068. addUserToGroup: (groupId: number, userId: number) =>
  3069. request<void>(`/groups/${groupId}/users/${userId}`, {
  3070. method: 'POST',
  3071. }),
  3072. removeUserFromGroup: (groupId: number, userId: number) =>
  3073. request<void>(`/groups/${groupId}/users/${userId}`, {
  3074. method: 'DELETE',
  3075. }),
  3076. // Printers
  3077. getPrinters: () => request<Printer[]>('/printers/'),
  3078. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  3079. createPrinter: (data: PrinterCreate) =>
  3080. request<Printer>('/printers/', {
  3081. method: 'POST',
  3082. body: JSON.stringify(data),
  3083. }),
  3084. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  3085. request<Printer>(`/printers/${id}`, {
  3086. method: 'PATCH',
  3087. body: JSON.stringify(data),
  3088. }),
  3089. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  3090. request<{ status: string; archives_deleted: boolean }>(
  3091. `/printers/${id}?delete_archives=${deleteArchives}`,
  3092. { method: 'DELETE' }
  3093. ),
  3094. getDeveloperModeWarnings: () =>
  3095. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  3096. getAvailableFilaments: (model: string, location?: string) => {
  3097. const params = new URLSearchParams({ model });
  3098. if (location) params.set('location', location);
  3099. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  3100. },
  3101. getPrinterStatus: (id: number) =>
  3102. request<PrinterStatus>(`/printers/${id}/status`),
  3103. refreshPrinterStatus: (id: number) =>
  3104. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  3105. method: 'POST',
  3106. }),
  3107. connectPrinter: (id: number) =>
  3108. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  3109. method: 'POST',
  3110. }),
  3111. disconnectPrinter: (id: number) =>
  3112. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  3113. method: 'POST',
  3114. }),
  3115. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  3116. request<{ success: boolean; error?: string; resolution?: string }>(
  3117. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  3118. { method: 'POST' }
  3119. ),
  3120. // Print Control
  3121. stopPrint: (printerId: number) =>
  3122. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  3123. method: 'POST',
  3124. }),
  3125. pausePrint: (printerId: number) =>
  3126. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  3127. method: 'POST',
  3128. }),
  3129. resumePrint: (printerId: number) =>
  3130. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  3131. method: 'POST',
  3132. }),
  3133. clearPlate: (printerId: number) =>
  3134. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  3135. method: 'POST',
  3136. }),
  3137. // Get current print user (for reprint tracking - Issue #206)
  3138. getCurrentPrintUser: (printerId: number) =>
  3139. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  3140. // Print Speed Control
  3141. setPrintSpeed: (printerId: number, mode: number) =>
  3142. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  3143. method: 'POST',
  3144. }),
  3145. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  3146. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  3147. method: 'POST',
  3148. }),
  3149. // Bed (Z-axis) jog
  3150. bedJog: (printerId: number, distance: number, force: boolean = false) =>
  3151. request<{ success: boolean; message: string }>(
  3152. `/printers/${printerId}/bed-jog?distance=${distance}&force=${force}`,
  3153. { method: 'POST' }
  3154. ),
  3155. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  3156. request<{ success: boolean; message: string }>(
  3157. `/printers/${printerId}/home-axes?axes=${axes}`,
  3158. { method: 'POST' }
  3159. ),
  3160. // Chamber Light Control
  3161. setChamberLight: (printerId: number, on: boolean) =>
  3162. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  3163. method: 'POST',
  3164. }),
  3165. // AMS Drying Control
  3166. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  3167. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  3168. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  3169. { method: 'POST' }
  3170. ),
  3171. stopDrying: (printerId: number, amsId: number) =>
  3172. request<{ status: string; ams_id: number }>(
  3173. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  3174. { method: 'POST' }
  3175. ),
  3176. // Skip Objects
  3177. getPrintableObjects: (printerId: number) =>
  3178. request<{
  3179. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  3180. total: number;
  3181. skipped_count: number;
  3182. is_printing: boolean;
  3183. bbox_all: [number, number, number, number] | null;
  3184. }>(`/printers/${printerId}/print/objects`),
  3185. skipObjects: (printerId: number, objectIds: number[]) =>
  3186. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  3187. `/printers/${printerId}/print/skip-objects`,
  3188. {
  3189. method: 'POST',
  3190. body: JSON.stringify(objectIds),
  3191. }
  3192. ),
  3193. // HMS Errors
  3194. clearHMSErrors: (printerId: number) =>
  3195. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  3196. // AMS Control
  3197. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  3198. request<{ success: boolean; message: string }>(
  3199. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  3200. { method: 'POST' }
  3201. ),
  3202. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 254 for external spool.
  3203. loadAmsTray: (printerId: number, trayId: number) =>
  3204. request<{ success: boolean; message: string }>(
  3205. `/printers/${printerId}/ams/load?tray_id=${trayId}`,
  3206. { method: 'POST' }
  3207. ),
  3208. // Unload the currently loaded filament.
  3209. unloadAms: (printerId: number) =>
  3210. request<{ success: boolean; message: string }>(
  3211. `/printers/${printerId}/ams/unload`,
  3212. { method: 'POST' }
  3213. ),
  3214. // MQTT Debug Logging
  3215. enableMQTTLogging: (printerId: number) =>
  3216. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  3217. method: 'POST',
  3218. }),
  3219. disableMQTTLogging: (printerId: number) =>
  3220. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  3221. method: 'POST',
  3222. }),
  3223. getMQTTLogs: (printerId: number) =>
  3224. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  3225. clearMQTTLogs: (printerId: number) =>
  3226. request<{ status: string }>(`/printers/${printerId}/logging`, {
  3227. method: 'DELETE',
  3228. }),
  3229. // Printer File Manager
  3230. getPrinterFiles: (printerId: number, path = '/') =>
  3231. request<{
  3232. path: string;
  3233. files: Array<{
  3234. name: string;
  3235. is_directory: boolean;
  3236. size: number;
  3237. path: string;
  3238. mtime?: string;
  3239. }>;
  3240. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  3241. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  3242. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3243. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  3244. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  3245. getPrinterFilePlates: (printerId: number, path: string) =>
  3246. request<{
  3247. printer_id: number;
  3248. path: string;
  3249. filename: string;
  3250. plates: Array<{
  3251. index: number;
  3252. name: string | null;
  3253. objects: string[];
  3254. has_thumbnail: boolean;
  3255. thumbnail_url: string | null;
  3256. print_time_seconds: number | null;
  3257. filament_used_grams: number | null;
  3258. filaments: Array<{
  3259. slot_id: number;
  3260. type: string;
  3261. color: string;
  3262. used_grams: number;
  3263. used_meters: number;
  3264. }>;
  3265. }>;
  3266. is_multi_plate: boolean;
  3267. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  3268. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  3269. withStreamToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  3270. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  3271. const headers: Record<string, string> = {};
  3272. if (authToken) {
  3273. headers['Authorization'] = `Bearer ${authToken}`;
  3274. }
  3275. const response = await fetch(
  3276. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3277. { headers }
  3278. );
  3279. if (!response.ok) {
  3280. const error = await response.json().catch(() => ({}));
  3281. throw new Error(error.detail || `HTTP ${response.status}`);
  3282. }
  3283. const disposition = response.headers.get('Content-Disposition');
  3284. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  3285. const blob = await response.blob();
  3286. const url = window.URL.createObjectURL(blob);
  3287. const a = document.createElement('a');
  3288. a.href = url;
  3289. a.download = filename;
  3290. document.body.appendChild(a);
  3291. a.click();
  3292. document.body.removeChild(a);
  3293. window.URL.revokeObjectURL(url);
  3294. },
  3295. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  3296. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  3297. if (authToken) {
  3298. headers['Authorization'] = `Bearer ${authToken}`;
  3299. }
  3300. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  3301. method: 'POST',
  3302. headers,
  3303. body: JSON.stringify({ paths }),
  3304. });
  3305. if (!response.ok) {
  3306. const error = await response.json().catch(() => ({}));
  3307. throw new Error(error.detail || `HTTP ${response.status}`);
  3308. }
  3309. return response.blob();
  3310. },
  3311. deletePrinterFile: (printerId: number, path: string) =>
  3312. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  3313. method: 'DELETE',
  3314. }),
  3315. getPrinterStorage: (printerId: number) =>
  3316. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  3317. // Archives
  3318. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  3319. const params = new URLSearchParams();
  3320. if (printerId) params.set('printer_id', String(printerId));
  3321. if (projectId) params.set('project_id', String(projectId));
  3322. params.set('limit', String(limit));
  3323. params.set('offset', String(offset));
  3324. if (dateFrom) params.set('date_from', dateFrom);
  3325. if (dateTo) params.set('date_to', dateTo);
  3326. return request<Archive[]>(`/archives/?${params}`);
  3327. },
  3328. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  3329. const params = new URLSearchParams();
  3330. if (dateFrom) params.set('date_from', dateFrom);
  3331. if (dateTo) params.set('date_to', dateTo);
  3332. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  3333. const qs = params.toString();
  3334. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  3335. },
  3336. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  3337. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  3338. searchArchives: (query: string, options?: {
  3339. printerId?: number;
  3340. projectId?: number;
  3341. status?: string;
  3342. limit?: number;
  3343. offset?: number;
  3344. }) => {
  3345. const params = new URLSearchParams();
  3346. params.set('q', query);
  3347. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3348. if (options?.projectId) params.set('project_id', String(options.projectId));
  3349. if (options?.status) params.set('status', options.status);
  3350. if (options?.limit) params.set('limit', String(options.limit));
  3351. if (options?.offset) params.set('offset', String(options.offset));
  3352. return request<Archive[]>(`/archives/search?${params}`);
  3353. },
  3354. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  3355. updateArchive: (id: number, data: {
  3356. printer_id?: number | null;
  3357. project_id?: number | null;
  3358. print_name?: string;
  3359. is_favorite?: boolean;
  3360. tags?: string;
  3361. notes?: string;
  3362. cost?: number;
  3363. failure_reason?: string | null;
  3364. status?: string;
  3365. quantity?: number;
  3366. external_url?: string | null;
  3367. }) =>
  3368. request<Archive>(`/archives/${id}`, {
  3369. method: 'PATCH',
  3370. body: JSON.stringify(data),
  3371. }),
  3372. toggleFavorite: (id: number) =>
  3373. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  3374. // Soft-deletes by default (#1343): files removed from disk, row hidden
  3375. // from listings, but its filament / time / cost / energy contribution
  3376. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  3377. // row from statistics too.
  3378. deleteArchive: (id: number, purgeStats: boolean = false) =>
  3379. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  3380. // ========== Archive auto-purge (#1008 follow-up) ==========
  3381. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3382. request<ArchivePurgePreview>(
  3383. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  3384. ),
  3385. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  3386. // preserved, files removed from disk, row hidden via deleted_at. true matches
  3387. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  3388. // linked PrintLogEntry rows so the contribution drops from /stats too).
  3389. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3390. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  3391. method: 'POST',
  3392. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  3393. }),
  3394. getArchivePurgeSettings: () =>
  3395. request<ArchivePurgeSettings>('/archives/purge/settings'),
  3396. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  3397. request<ArchivePurgeSettings>('/archives/purge/settings', {
  3398. method: 'PUT',
  3399. body: JSON.stringify(body),
  3400. }),
  3401. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  3402. const params = new URLSearchParams();
  3403. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3404. if (options?.dateTo) params.set('date_to', options.dateTo);
  3405. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3406. const qs = params.toString();
  3407. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  3408. },
  3409. // Tag management
  3410. getTags: () => request<TagInfo[]>('/archives/tags'),
  3411. renameTag: (oldName: string, newName: string) =>
  3412. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  3413. method: 'PUT',
  3414. body: JSON.stringify({ new_name: newName }),
  3415. }),
  3416. deleteTag: (name: string) =>
  3417. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  3418. method: 'DELETE',
  3419. }),
  3420. recalculateCosts: () =>
  3421. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  3422. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  3423. const params = new URLSearchParams();
  3424. if (options?.days) params.set('days', String(options.days));
  3425. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3426. if (options?.dateTo) params.set('date_to', options.dateTo);
  3427. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3428. if (options?.projectId) params.set('project_id', String(options.projectId));
  3429. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3430. const qs = params.toString();
  3431. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  3432. },
  3433. compareArchives: (archiveIds: number[]) =>
  3434. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  3435. findSimilarArchives: (archiveId: number, limit = 10) =>
  3436. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  3437. exportArchives: async (options?: {
  3438. format?: 'csv' | 'xlsx';
  3439. fields?: string[];
  3440. printerId?: number;
  3441. projectId?: number;
  3442. status?: string;
  3443. dateFrom?: string;
  3444. dateTo?: string;
  3445. search?: string;
  3446. }): Promise<{ blob: Blob; filename: string }> => {
  3447. const params = new URLSearchParams();
  3448. if (options?.format) params.set('format', options.format);
  3449. if (options?.fields) params.set('fields', options.fields.join(','));
  3450. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3451. if (options?.projectId) params.set('project_id', String(options.projectId));
  3452. if (options?.status) params.set('status', options.status);
  3453. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3454. if (options?.dateTo) params.set('date_to', options.dateTo);
  3455. if (options?.search) params.set('search', options.search);
  3456. const headers: Record<string, string> = {};
  3457. if (authToken) {
  3458. headers['Authorization'] = `Bearer ${authToken}`;
  3459. }
  3460. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  3461. if (!response.ok) {
  3462. const error = await response.json().catch(() => ({}));
  3463. throw new Error(error.detail || `HTTP ${response.status}`);
  3464. }
  3465. const contentDisposition = response.headers.get('Content-Disposition');
  3466. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  3467. if (contentDisposition) {
  3468. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3469. if (match) filename = match[1];
  3470. }
  3471. const blob = await response.blob();
  3472. return { blob, filename };
  3473. },
  3474. exportStats: async (options?: {
  3475. format?: 'csv' | 'xlsx';
  3476. days?: number;
  3477. printerId?: number;
  3478. projectId?: number;
  3479. createdById?: number;
  3480. }): Promise<{ blob: Blob; filename: string }> => {
  3481. const params = new URLSearchParams();
  3482. if (options?.format) params.set('format', options.format);
  3483. if (options?.days) params.set('days', String(options.days));
  3484. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3485. if (options?.projectId) params.set('project_id', String(options.projectId));
  3486. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3487. const headers: Record<string, string> = {};
  3488. if (authToken) {
  3489. headers['Authorization'] = `Bearer ${authToken}`;
  3490. }
  3491. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  3492. if (!response.ok) {
  3493. const error = await response.json().catch(() => ({}));
  3494. throw new Error(error.detail || `HTTP ${response.status}`);
  3495. }
  3496. const contentDisposition = response.headers.get('Content-Disposition');
  3497. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  3498. if (contentDisposition) {
  3499. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3500. if (match) filename = match[1];
  3501. }
  3502. const blob = await response.blob();
  3503. return { blob, filename };
  3504. },
  3505. getArchiveDuplicates: (id: number) =>
  3506. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  3507. backfillContentHashes: () =>
  3508. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  3509. method: 'POST',
  3510. }),
  3511. getArchiveThumbnail: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  3512. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  3513. withStreamToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  3514. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  3515. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  3516. const headers: Record<string, string> = {};
  3517. if (authToken) {
  3518. headers['Authorization'] = `Bearer ${authToken}`;
  3519. }
  3520. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  3521. if (!response.ok) {
  3522. const error = await response.json().catch(() => ({}));
  3523. throw new Error(error.detail || `HTTP ${response.status}`);
  3524. }
  3525. const disposition = response.headers.get('Content-Disposition');
  3526. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  3527. const blob = await response.blob();
  3528. const url = window.URL.createObjectURL(blob);
  3529. const a = document.createElement('a');
  3530. a.href = url;
  3531. a.download = downloadFilename;
  3532. document.body.appendChild(a);
  3533. a.click();
  3534. document.body.removeChild(a);
  3535. window.URL.revokeObjectURL(url);
  3536. },
  3537. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  3538. getArchivePlatePreview: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/plate-preview`),
  3539. getArchiveTimelapse: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  3540. scanArchiveTimelapse: (id: number) =>
  3541. request<{
  3542. status: string;
  3543. message: string;
  3544. filename?: string;
  3545. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  3546. }>(`/archives/${id}/timelapse/scan`, {
  3547. method: 'POST',
  3548. }),
  3549. selectArchiveTimelapse: (id: number, filename: string) =>
  3550. request<{ status: string; message: string; filename: string }>(
  3551. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  3552. { method: 'POST' }
  3553. ),
  3554. deleteArchiveTimelapse: (id: number) =>
  3555. request<{ status: string }>(`/archives/${id}/timelapse`, {
  3556. method: 'DELETE',
  3557. }),
  3558. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3559. const formData = new FormData();
  3560. formData.append('file', file);
  3561. const headers: Record<string, string> = {};
  3562. if (authToken) {
  3563. headers['Authorization'] = `Bearer ${authToken}`;
  3564. }
  3565. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  3566. method: 'POST',
  3567. headers,
  3568. body: formData,
  3569. });
  3570. if (!response.ok) {
  3571. const error = await response.json().catch(() => ({}));
  3572. throw new Error(error.detail || `HTTP ${response.status}`);
  3573. }
  3574. return response.json();
  3575. },
  3576. // Timelapse Editor
  3577. getTimelapseInfo: (archiveId: number) =>
  3578. request<{
  3579. duration: number;
  3580. width: number;
  3581. height: number;
  3582. fps: number;
  3583. codec: string;
  3584. file_size: number;
  3585. has_audio: boolean;
  3586. }>(`/archives/${archiveId}/timelapse/info`),
  3587. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  3588. request<{
  3589. thumbnails: string[];
  3590. timestamps: number[];
  3591. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  3592. processTimelapse: async (
  3593. archiveId: number,
  3594. params: {
  3595. trimStart?: number;
  3596. trimEnd?: number;
  3597. speed?: number;
  3598. saveMode: 'replace' | 'new';
  3599. outputFilename?: string;
  3600. },
  3601. audioFile?: File
  3602. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  3603. const formData = new FormData();
  3604. formData.append('trim_start', String(params.trimStart ?? 0));
  3605. if (params.trimEnd !== undefined) {
  3606. formData.append('trim_end', String(params.trimEnd));
  3607. }
  3608. formData.append('speed', String(params.speed ?? 1));
  3609. formData.append('save_mode', params.saveMode);
  3610. if (params.outputFilename) {
  3611. formData.append('output_filename', params.outputFilename);
  3612. }
  3613. if (audioFile) {
  3614. formData.append('audio', audioFile);
  3615. }
  3616. const headers: Record<string, string> = {};
  3617. if (authToken) {
  3618. headers['Authorization'] = `Bearer ${authToken}`;
  3619. }
  3620. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  3621. method: 'POST',
  3622. headers,
  3623. body: formData,
  3624. });
  3625. if (!response.ok) {
  3626. const error = await response.json().catch(() => ({}));
  3627. throw new Error(error.detail || `HTTP ${response.status}`);
  3628. }
  3629. return response.json();
  3630. },
  3631. // Photos
  3632. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  3633. withStreamToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  3634. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  3635. const formData = new FormData();
  3636. formData.append('file', file);
  3637. const headers: Record<string, string> = {};
  3638. if (authToken) {
  3639. headers['Authorization'] = `Bearer ${authToken}`;
  3640. }
  3641. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  3642. headers,
  3643. method: 'POST',
  3644. body: formData,
  3645. });
  3646. if (!response.ok) {
  3647. const error = await response.json().catch(() => ({}));
  3648. throw new Error(error.detail || `HTTP ${response.status}`);
  3649. }
  3650. return response.json();
  3651. },
  3652. deleteArchivePhoto: (archiveId: number, filename: string) =>
  3653. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  3654. method: 'DELETE',
  3655. }),
  3656. // Source 3MF (original slicer project file)
  3657. getSource3mfDownloadUrl: (archiveId: number) =>
  3658. `${API_BASE}/archives/${archiveId}/source`,
  3659. downloadSource3mf: async (archiveId: number): Promise<void> => {
  3660. const headers: Record<string, string> = {};
  3661. if (authToken) {
  3662. headers['Authorization'] = `Bearer ${authToken}`;
  3663. }
  3664. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  3665. if (!response.ok) {
  3666. const error = await response.json().catch(() => ({}));
  3667. throw new Error(error.detail || `HTTP ${response.status}`);
  3668. }
  3669. const disposition = response.headers.get('Content-Disposition');
  3670. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  3671. const blob = await response.blob();
  3672. const url = window.URL.createObjectURL(blob);
  3673. const a = document.createElement('a');
  3674. a.href = url;
  3675. a.download = filename;
  3676. document.body.appendChild(a);
  3677. a.click();
  3678. document.body.removeChild(a);
  3679. window.URL.revokeObjectURL(url);
  3680. },
  3681. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  3682. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  3683. const safe = filename.replace(/[/\\?#]/g, '_');
  3684. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3685. },
  3686. createSourceSlicerToken: (archiveId: number) =>
  3687. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  3688. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3689. const safe = filename.replace(/[/\\?#]/g, '_');
  3690. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3691. },
  3692. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3693. const formData = new FormData();
  3694. formData.append('file', file);
  3695. const headers: Record<string, string> = {};
  3696. if (authToken) {
  3697. headers['Authorization'] = `Bearer ${authToken}`;
  3698. }
  3699. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  3700. method: 'POST',
  3701. headers,
  3702. body: formData,
  3703. });
  3704. if (!response.ok) {
  3705. const error = await response.json().catch(() => ({}));
  3706. throw new Error(error.detail || `HTTP ${response.status}`);
  3707. }
  3708. return response.json();
  3709. },
  3710. deleteSource3mf: (archiveId: number) =>
  3711. request<{ status: string }>(`/archives/${archiveId}/source`, {
  3712. method: 'DELETE',
  3713. }),
  3714. // F3D (Fusion 360 design file)
  3715. getF3dDownloadUrl: (archiveId: number) =>
  3716. `${API_BASE}/archives/${archiveId}/f3d`,
  3717. downloadF3d: async (archiveId: number): Promise<void> => {
  3718. const headers: Record<string, string> = {};
  3719. if (authToken) {
  3720. headers['Authorization'] = `Bearer ${authToken}`;
  3721. }
  3722. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  3723. if (!response.ok) {
  3724. const error = await response.json().catch(() => ({}));
  3725. throw new Error(error.detail || `HTTP ${response.status}`);
  3726. }
  3727. const disposition = response.headers.get('Content-Disposition');
  3728. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  3729. const blob = await response.blob();
  3730. const url = window.URL.createObjectURL(blob);
  3731. const a = document.createElement('a');
  3732. a.href = url;
  3733. a.download = filename;
  3734. document.body.appendChild(a);
  3735. a.click();
  3736. document.body.removeChild(a);
  3737. window.URL.revokeObjectURL(url);
  3738. },
  3739. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  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}/archives/${archiveId}/f3d`, {
  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. deleteF3d: (archiveId: number) =>
  3758. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  3759. method: 'DELETE',
  3760. }),
  3761. // QR Code
  3762. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  3763. withStreamToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  3764. getArchiveCapabilities: (id: number) =>
  3765. request<{
  3766. has_model: boolean;
  3767. has_gcode: boolean;
  3768. has_source: boolean;
  3769. build_volume: { x: number; y: number; z: number };
  3770. filament_colors: string[];
  3771. }>(`/archives/${id}/capabilities`),
  3772. // Project Page
  3773. getArchiveProjectPage: (id: number) =>
  3774. request<{
  3775. title: string | null;
  3776. description: string | null;
  3777. designer: string | null;
  3778. designer_user_id: string | null;
  3779. license: string | null;
  3780. copyright: string | null;
  3781. creation_date: string | null;
  3782. modification_date: string | null;
  3783. origin: string | null;
  3784. profile_title: string | null;
  3785. profile_description: string | null;
  3786. profile_cover: string | null;
  3787. profile_user_id: string | null;
  3788. profile_user_name: string | null;
  3789. design_model_id: string | null;
  3790. design_profile_id: string | null;
  3791. design_region: string | null;
  3792. model_pictures: Array<{ name: string; path: string; url: string }>;
  3793. profile_pictures: Array<{ name: string; path: string; url: string }>;
  3794. thumbnails: Array<{ name: string; path: string; url: string }>;
  3795. }>(`/archives/${id}/project-page`),
  3796. updateArchiveProjectPage: (id: number, data: {
  3797. title?: string;
  3798. description?: string;
  3799. designer?: string;
  3800. license?: string;
  3801. copyright?: string;
  3802. profile_title?: string;
  3803. profile_description?: string;
  3804. }) =>
  3805. request(`/archives/${id}/project-page`, {
  3806. method: 'PATCH',
  3807. body: JSON.stringify(data),
  3808. }),
  3809. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  3810. withStreamToken(`${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`),
  3811. getArchiveForSlicer: (id: number, filename: string) => {
  3812. const safe = filename.replace(/[/\\?#]/g, '_');
  3813. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3814. },
  3815. createArchiveSlicerToken: (archiveId: number) =>
  3816. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  3817. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3818. const safe = filename.replace(/[/\\?#]/g, '_');
  3819. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3820. },
  3821. getArchivePlates: (archiveId: number) =>
  3822. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  3823. getArchiveFilamentRequirements: (
  3824. archiveId: number,
  3825. plateId?: number,
  3826. requestId?: string,
  3827. // Optional bundle context: when supplied, the backend's preview slice
  3828. // (run for unsliced project files) uses slice_with_bundle so gram
  3829. // numbers reflect the same triplet the real print will use. All four
  3830. // fields must be set for the bundle path to engage; partial context
  3831. // falls back to the embedded-settings preview without erroring.
  3832. bundle?: {
  3833. bundle_id: string;
  3834. printer_name: string;
  3835. process_name: string;
  3836. filament_names: string[];
  3837. },
  3838. ) => {
  3839. const qs = new URLSearchParams();
  3840. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  3841. if (requestId) qs.set('request_id', requestId);
  3842. if (bundle) {
  3843. qs.set('bundle_id', bundle.bundle_id);
  3844. qs.set('printer_name', bundle.printer_name);
  3845. qs.set('process_name', bundle.process_name);
  3846. qs.set('filament_names', bundle.filament_names.join(';'));
  3847. }
  3848. return request<{
  3849. archive_id: number;
  3850. filename: string;
  3851. plate_id: number | null;
  3852. filaments: Array<{
  3853. slot_id: number;
  3854. type: string;
  3855. color: string;
  3856. used_grams: number;
  3857. used_meters: number;
  3858. used_in_plate?: boolean;
  3859. }>;
  3860. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  3861. },
  3862. reprintArchive: (
  3863. archiveId: number,
  3864. printerId: number,
  3865. options?: {
  3866. plate_id?: number;
  3867. plate_name?: string;
  3868. ams_mapping?: number[];
  3869. timelapse?: boolean;
  3870. bed_levelling?: boolean;
  3871. flow_cali?: boolean;
  3872. vibration_cali?: boolean;
  3873. layer_inspect?: boolean;
  3874. use_ams?: boolean;
  3875. }
  3876. ) =>
  3877. request<BackgroundDispatchResponse>(
  3878. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  3879. {
  3880. method: 'POST',
  3881. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  3882. body: options ? JSON.stringify(options) : undefined,
  3883. }
  3884. ),
  3885. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  3886. const formData = new FormData();
  3887. formData.append('file', file);
  3888. const url = printerId
  3889. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  3890. : `${API_BASE}/archives/upload`;
  3891. const headers: Record<string, string> = {};
  3892. if (authToken) {
  3893. headers['Authorization'] = `Bearer ${authToken}`;
  3894. }
  3895. const response = await fetch(url, {
  3896. method: 'POST',
  3897. headers,
  3898. body: formData,
  3899. });
  3900. if (!response.ok) {
  3901. const error = await response.json().catch(() => ({}));
  3902. throw new Error(error.detail || `HTTP ${response.status}`);
  3903. }
  3904. return response.json();
  3905. },
  3906. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  3907. const formData = new FormData();
  3908. files.forEach((file) => formData.append('files', file));
  3909. const url = printerId
  3910. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  3911. : `${API_BASE}/archives/upload-bulk`;
  3912. const headers: Record<string, string> = {};
  3913. if (authToken) {
  3914. headers['Authorization'] = `Bearer ${authToken}`;
  3915. }
  3916. const response = await fetch(url, {
  3917. method: 'POST',
  3918. headers,
  3919. body: formData,
  3920. });
  3921. if (!response.ok) {
  3922. const error = await response.json().catch(() => ({}));
  3923. throw new Error(error.detail || `HTTP ${response.status}`);
  3924. }
  3925. return response.json();
  3926. },
  3927. // Print Log
  3928. getPrintLog: (params?: {
  3929. search?: string;
  3930. printerId?: number;
  3931. username?: string;
  3932. status?: string;
  3933. dateFrom?: string;
  3934. dateTo?: string;
  3935. limit?: number;
  3936. offset?: number;
  3937. }) => {
  3938. const searchParams = new URLSearchParams();
  3939. if (params?.search) searchParams.set('search', params.search);
  3940. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  3941. if (params?.username) searchParams.set('created_by_username', params.username);
  3942. if (params?.status) searchParams.set('status', params.status);
  3943. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  3944. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  3945. if (params?.limit) searchParams.set('limit', String(params.limit));
  3946. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  3947. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  3948. },
  3949. getPrintLogThumbnail: (id: number) => withStreamToken(`${API_BASE}/print-log/${id}/thumbnail`),
  3950. clearPrintLog: () =>
  3951. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  3952. // Settings
  3953. getSettings: () => request<AppSettings>('/settings/'),
  3954. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  3955. // Public subset of settings for UI rendering — no settings:read required.
  3956. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  3957. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  3958. // backend/app/api/routes/settings.py.
  3959. getUiPreferences: () =>
  3960. request<{
  3961. require_plate_clear?: boolean;
  3962. check_printer_firmware?: boolean;
  3963. camera_view_mode?: 'window' | 'embedded';
  3964. time_format?: 'system' | '12h' | '24h';
  3965. date_format?: string;
  3966. drying_presets?: string;
  3967. ams_humidity_good?: number;
  3968. ams_humidity_fair?: number;
  3969. ams_temp_good?: number;
  3970. ams_temp_fair?: number;
  3971. bed_cooled_threshold?: number;
  3972. }>('/settings/ui-preferences'),
  3973. updateSettings: (data: AppSettingsUpdate) =>
  3974. request<AppSettings>('/settings/', {
  3975. method: 'PUT',
  3976. body: JSON.stringify(data),
  3977. }),
  3978. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  3979. resetSettings: () =>
  3980. request<AppSettings>('/settings/reset', { method: 'POST' }),
  3981. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  3982. // New simplified backup - complete database + all files
  3983. const url = `${API_BASE}/settings/backup`;
  3984. const headers: Record<string, string> = {};
  3985. if (authToken) {
  3986. headers['Authorization'] = `Bearer ${authToken}`;
  3987. }
  3988. const response = await fetch(url, { headers });
  3989. // Check for errors
  3990. if (!response.ok) {
  3991. const errorText = await response.text();
  3992. throw new Error(errorText || `Backup failed with status ${response.status}`);
  3993. }
  3994. // Get filename from Content-Disposition header
  3995. const contentDisposition = response.headers.get('Content-Disposition');
  3996. let filename = 'bambuddy-backup.zip';
  3997. if (contentDisposition) {
  3998. const match = contentDisposition.match(/filename=([^;]+)/);
  3999. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  4000. }
  4001. const blob = await response.blob();
  4002. return { blob, filename };
  4003. },
  4004. importBackup: async (file: File) => {
  4005. // New simplified restore - replaces database + all directories
  4006. const formData = new FormData();
  4007. formData.append('file', file);
  4008. const url = `${API_BASE}/settings/restore`;
  4009. const headers: Record<string, string> = {};
  4010. if (authToken) {
  4011. headers['Authorization'] = `Bearer ${authToken}`;
  4012. }
  4013. const response = await fetch(url, {
  4014. method: 'POST',
  4015. headers,
  4016. body: formData,
  4017. });
  4018. return response.json() as Promise<{
  4019. success: boolean;
  4020. message: string;
  4021. }>;
  4022. },
  4023. checkFfmpeg: () =>
  4024. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  4025. getNetworkInterfaces: () =>
  4026. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  4027. // Cloud
  4028. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  4029. cloudLogin: (email: string, password: string, region = 'global') =>
  4030. request<CloudLoginResponse>('/cloud/login', {
  4031. method: 'POST',
  4032. body: JSON.stringify({ email, password, region }),
  4033. }),
  4034. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  4035. request<CloudLoginResponse>('/cloud/verify', {
  4036. method: 'POST',
  4037. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  4038. }),
  4039. cloudSetToken: (access_token: string, region: string = 'global') =>
  4040. request<CloudAuthStatus>('/cloud/token', {
  4041. method: 'POST',
  4042. body: JSON.stringify({ access_token, region }),
  4043. }),
  4044. cloudLogout: () =>
  4045. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  4046. getCloudSettings: (version = '02.04.00.70') =>
  4047. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  4048. getBuiltinFilaments: () =>
  4049. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  4050. getFilamentIdMap: () =>
  4051. request<Record<string, string>>('/cloud/filament-id-map'),
  4052. // MakerWorld URL-paste import flow.
  4053. getMakerworldStatus: () =>
  4054. request<MakerworldStatus>('/makerworld/status'),
  4055. resolveMakerworldUrl: (url: string) =>
  4056. request<MakerworldResolvedModel>('/makerworld/resolve', {
  4057. method: 'POST',
  4058. body: JSON.stringify({ url }),
  4059. }),
  4060. getMakerworldRecentImports: (limit = 10) =>
  4061. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  4062. importMakerworldInstance: (
  4063. model_id: number,
  4064. instance_id: number | null,
  4065. profile_id?: number | null,
  4066. folder_id?: number | null,
  4067. ) =>
  4068. request<MakerworldImportResponse>('/makerworld/import', {
  4069. method: 'POST',
  4070. body: JSON.stringify({
  4071. model_id,
  4072. instance_id: instance_id ?? null,
  4073. profile_id: profile_id ?? null,
  4074. folder_id: folder_id ?? null,
  4075. }),
  4076. }),
  4077. getCloudSettingDetail: (settingId: string) =>
  4078. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  4079. createCloudSetting: (data: SlicerSettingCreate) =>
  4080. request<SlicerSettingDetail>('/cloud/settings', {
  4081. method: 'POST',
  4082. body: JSON.stringify(data),
  4083. }),
  4084. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  4085. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  4086. method: 'PUT',
  4087. body: JSON.stringify(data),
  4088. }),
  4089. deleteCloudSetting: (settingId: string) =>
  4090. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  4091. method: 'DELETE',
  4092. }),
  4093. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  4094. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  4095. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  4096. getAllCloudFields: () =>
  4097. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  4098. getFilamentInfo: (settingIds: string[]) =>
  4099. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  4100. method: 'POST',
  4101. body: JSON.stringify(settingIds),
  4102. }),
  4103. // Smart Plugs
  4104. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  4105. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  4106. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  4107. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  4108. createSmartPlug: (data: SmartPlugCreate) =>
  4109. request<SmartPlug>('/smart-plugs/', {
  4110. method: 'POST',
  4111. body: JSON.stringify(data),
  4112. }),
  4113. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  4114. request<SmartPlug>(`/smart-plugs/${id}`, {
  4115. method: 'PATCH',
  4116. body: JSON.stringify(data),
  4117. }),
  4118. deleteSmartPlug: (id: number) =>
  4119. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  4120. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  4121. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  4122. method: 'POST',
  4123. body: JSON.stringify({ action }),
  4124. }),
  4125. getSmartPlugStatus: (id: number) =>
  4126. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  4127. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  4128. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  4129. method: 'POST',
  4130. body: JSON.stringify({ ip_address, username, password }),
  4131. }),
  4132. // Tasmota Discovery (auto-detects network)
  4133. startTasmotaScan: () =>
  4134. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  4135. getTasmotaScanStatus: () =>
  4136. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  4137. stopTasmotaScan: () =>
  4138. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  4139. getDiscoveredTasmotaDevices: () =>
  4140. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  4141. // Home Assistant Integration
  4142. testHAConnection: (url: string, token: string) =>
  4143. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  4144. method: 'POST',
  4145. body: JSON.stringify({ url, token }),
  4146. }),
  4147. getHAEntities: (search?: string) => {
  4148. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  4149. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  4150. },
  4151. getHASensorEntities: () =>
  4152. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  4153. // REST smart plug
  4154. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null) =>
  4155. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  4156. method: 'POST',
  4157. body: JSON.stringify({ url, method, headers }),
  4158. }),
  4159. // Print Queue
  4160. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  4161. const params = new URLSearchParams();
  4162. if (printerId) params.set('printer_id', String(printerId));
  4163. if (status) params.set('status', status);
  4164. if (targetModel) params.set('target_model', targetModel);
  4165. return request<PrintQueueItem[]>(`/queue/?${params}`);
  4166. },
  4167. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  4168. addToQueue: (data: PrintQueueItemCreate) =>
  4169. request<PrintQueueItem>('/queue/', {
  4170. method: 'POST',
  4171. body: JSON.stringify(data),
  4172. }),
  4173. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  4174. request<PrintQueueItem>(`/queue/${id}`, {
  4175. method: 'PATCH',
  4176. body: JSON.stringify(data),
  4177. }),
  4178. removeFromQueue: (id: number) =>
  4179. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  4180. reorderQueue: (items: { id: number; position: number }[]) =>
  4181. request<{ message: string }>('/queue/reorder', {
  4182. method: 'POST',
  4183. body: JSON.stringify({ items }),
  4184. }),
  4185. cancelQueueItem: (id: number) =>
  4186. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  4187. stopQueueItem: (id: number) =>
  4188. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  4189. /**
  4190. * Start a staged queue item. The backend re-checks live filament deficit
  4191. * for the assigned spool and, when short, returns 409 with a structured
  4192. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  4193. * after the user confirms "Print Anyway" (#1496).
  4194. */
  4195. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  4196. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  4197. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  4198. },
  4199. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  4200. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  4201. method: 'PATCH',
  4202. body: JSON.stringify(data),
  4203. }),
  4204. // Batches
  4205. getBatches: (status?: string) => {
  4206. const params = status ? `?status=${status}` : '';
  4207. return request<PrintBatch[]>(`/queue/batches${params}`);
  4208. },
  4209. getBatch: (id: number) => request<PrintBatch>(`/queue/batches/${id}`),
  4210. cancelBatch: (id: number) =>
  4211. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  4212. // K-Profiles
  4213. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  4214. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  4215. setKProfile: (printerId: number, profile: KProfileCreate) =>
  4216. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4217. method: 'POST',
  4218. body: JSON.stringify(profile),
  4219. }),
  4220. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  4221. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4222. method: 'DELETE',
  4223. body: JSON.stringify(profile),
  4224. }),
  4225. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  4226. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  4227. method: 'POST',
  4228. body: JSON.stringify(profiles),
  4229. }),
  4230. // K-Profile Notes (stored locally, not on printer)
  4231. getKProfileNotes: (printerId: number) =>
  4232. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  4233. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  4234. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  4235. method: 'PUT',
  4236. body: JSON.stringify({ setting_id: settingId, note }),
  4237. }),
  4238. deleteKProfileNote: (printerId: number, settingId: string) =>
  4239. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  4240. method: 'DELETE',
  4241. }),
  4242. // Slot Preset Mappings
  4243. getSlotPresets: (printerId: number) =>
  4244. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  4245. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4246. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  4247. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  4248. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  4249. method: 'PUT',
  4250. }),
  4251. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4252. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  4253. method: 'DELETE',
  4254. }),
  4255. // AMS Labels (user-defined friendly names)
  4256. getAmsLabels: (printerId: number) =>
  4257. request<Record<number, string>>(`/printers/${printerId}/ams-labels`),
  4258. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  4259. request<{ ams_id: number; label: string }>(
  4260. `/printers/${printerId}/ams-labels/${amsId}`,
  4261. {
  4262. method: 'PUT',
  4263. body: JSON.stringify({ label, ams_serial: amsSerial }),
  4264. }
  4265. ),
  4266. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  4267. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  4268. method: 'DELETE',
  4269. }),
  4270. configureAmsSlot: (
  4271. printerId: number,
  4272. amsId: number,
  4273. trayId: number,
  4274. config: {
  4275. tray_info_idx: string;
  4276. tray_type: string;
  4277. tray_sub_brands: string;
  4278. tray_color: string;
  4279. nozzle_temp_min: number;
  4280. nozzle_temp_max: number;
  4281. cali_idx: number;
  4282. nozzle_diameter: string;
  4283. setting_id?: string;
  4284. kprofile_filament_id?: string;
  4285. kprofile_setting_id?: string;
  4286. k_value?: number;
  4287. }
  4288. ) => {
  4289. const params = new URLSearchParams({
  4290. tray_info_idx: config.tray_info_idx,
  4291. tray_type: config.tray_type,
  4292. tray_sub_brands: config.tray_sub_brands,
  4293. tray_color: config.tray_color,
  4294. nozzle_temp_min: config.nozzle_temp_min.toString(),
  4295. nozzle_temp_max: config.nozzle_temp_max.toString(),
  4296. cali_idx: config.cali_idx.toString(),
  4297. nozzle_diameter: config.nozzle_diameter,
  4298. });
  4299. if (config.setting_id) {
  4300. params.set('setting_id', config.setting_id);
  4301. }
  4302. if (config.kprofile_filament_id) {
  4303. params.set('kprofile_filament_id', config.kprofile_filament_id);
  4304. }
  4305. if (config.kprofile_setting_id) {
  4306. params.set('kprofile_setting_id', config.kprofile_setting_id);
  4307. }
  4308. if (config.k_value !== undefined && config.k_value > 0) {
  4309. params.set('k_value', config.k_value.toString());
  4310. }
  4311. return request<{ success: boolean; message: string }>(
  4312. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  4313. { method: 'POST' }
  4314. );
  4315. },
  4316. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  4317. request<{ success: boolean; message: string }>(
  4318. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  4319. { method: 'POST' }
  4320. ),
  4321. // Filament Catalog (material types with cost/temp data)
  4322. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  4323. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  4324. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  4325. // Notification Providers
  4326. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  4327. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  4328. createNotificationProvider: (data: NotificationProviderCreate) =>
  4329. request<NotificationProvider>('/notifications/', {
  4330. method: 'POST',
  4331. body: JSON.stringify(data),
  4332. }),
  4333. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  4334. request<NotificationProvider>(`/notifications/${id}`, {
  4335. method: 'PATCH',
  4336. body: JSON.stringify(data),
  4337. }),
  4338. deleteNotificationProvider: (id: number) =>
  4339. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  4340. testNotificationProvider: (id: number) =>
  4341. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  4342. testNotificationConfig: (data: NotificationTestRequest) =>
  4343. request<NotificationTestResponse>('/notifications/test-config', {
  4344. method: 'POST',
  4345. body: JSON.stringify(data),
  4346. }),
  4347. testAllNotificationProviders: () =>
  4348. request<{
  4349. tested: number;
  4350. success: number;
  4351. failed: number;
  4352. results: Array<{
  4353. provider_id: number;
  4354. provider_name: string;
  4355. provider_type: string;
  4356. success: boolean;
  4357. message: string;
  4358. }>;
  4359. }>('/notifications/test-all', { method: 'POST' }),
  4360. // Notification Templates
  4361. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  4362. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  4363. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  4364. request<NotificationTemplate>(`/notification-templates/${id}`, {
  4365. method: 'PUT',
  4366. body: JSON.stringify(data),
  4367. }),
  4368. resetNotificationTemplate: (id: number) =>
  4369. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  4370. method: 'POST',
  4371. }),
  4372. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  4373. previewTemplate: (data: TemplatePreviewRequest) =>
  4374. request<TemplatePreviewResponse>('/notification-templates/preview', {
  4375. method: 'POST',
  4376. body: JSON.stringify(data),
  4377. }),
  4378. // Notification Logs
  4379. getNotificationLogs: (params?: {
  4380. limit?: number;
  4381. offset?: number;
  4382. provider_id?: number;
  4383. event_type?: string;
  4384. success?: boolean;
  4385. days?: number;
  4386. }) => {
  4387. const searchParams = new URLSearchParams();
  4388. if (params?.limit) searchParams.set('limit', String(params.limit));
  4389. if (params?.offset) searchParams.set('offset', String(params.offset));
  4390. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  4391. if (params?.event_type) searchParams.set('event_type', params.event_type);
  4392. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  4393. if (params?.days) searchParams.set('days', String(params.days));
  4394. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  4395. },
  4396. getNotificationLogStats: (days = 7) =>
  4397. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  4398. clearNotificationLogs: (olderThanDays = 30) =>
  4399. request<{ deleted: number; message: string }>(
  4400. `/notifications/logs?older_than_days=${olderThanDays}`,
  4401. { method: 'DELETE' }
  4402. ),
  4403. // Spoolman Integration
  4404. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  4405. connectSpoolman: () =>
  4406. request<{ success: boolean; message: string }>('/spoolman/connect', {
  4407. method: 'POST',
  4408. }),
  4409. disconnectSpoolman: () =>
  4410. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  4411. method: 'POST',
  4412. }),
  4413. syncPrinterAms: (printerId: number) =>
  4414. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  4415. method: 'POST',
  4416. }),
  4417. syncAllPrintersAms: () =>
  4418. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  4419. method: 'POST',
  4420. }),
  4421. getSpoolmanSpools: () =>
  4422. request<{ spools: unknown[] }>('/spoolman/spools'),
  4423. /** @deprecated Use getSpoolmanInventoryFilaments() — this endpoint has no SSRF guard */
  4424. getSpoolmanFilaments: () =>
  4425. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  4426. getSpoolmanInventoryFilaments: () =>
  4427. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  4428. patchSpoolmanFilament: (
  4429. filamentId: number,
  4430. data: { name?: string; spool_weight?: number | null; keep_existing_spools?: boolean },
  4431. ) =>
  4432. request<SpoolmanFilamentEntry>(`/spoolman/inventory/filaments/${filamentId}`, {
  4433. method: 'PATCH',
  4434. body: JSON.stringify(data),
  4435. }),
  4436. getUnlinkedSpools: () =>
  4437. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  4438. getLinkedSpools: () =>
  4439. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  4440. linkSpool: (
  4441. spoolId: number,
  4442. context: {
  4443. spoolTag: string;
  4444. printerId: number;
  4445. amsId: number;
  4446. trayId: number;
  4447. }
  4448. ) =>
  4449. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  4450. method: 'POST',
  4451. body: JSON.stringify({
  4452. spool_tag: context.spoolTag,
  4453. printer_id: context.printerId,
  4454. ams_id: context.amsId,
  4455. tray_id: context.trayId,
  4456. }),
  4457. }),
  4458. unlinkSpool: (spoolId: number) =>
  4459. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  4460. method: 'POST',
  4461. }),
  4462. getSpoolmanSettings: () =>
  4463. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman'),
  4464. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; }) =>
  4465. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman', {
  4466. method: 'PUT',
  4467. body: JSON.stringify(data),
  4468. }),
  4469. // Inventory
  4470. getSpools: (includeArchived = false) =>
  4471. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  4472. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  4473. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4474. request<InventorySpool>('/inventory/spools', {
  4475. method: 'POST',
  4476. body: JSON.stringify(data),
  4477. }),
  4478. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  4479. request<InventorySpool[]>('/inventory/spools/bulk', {
  4480. method: 'POST',
  4481. body: JSON.stringify({ spool: data, quantity }),
  4482. }),
  4483. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  4484. request<InventorySpool>(`/inventory/spools/${id}`, {
  4485. method: 'PATCH',
  4486. body: JSON.stringify(data),
  4487. }),
  4488. deleteSpool: (id: number) =>
  4489. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  4490. archiveSpool: (id: number) =>
  4491. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  4492. restoreSpool: (id: number) =>
  4493. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  4494. resetSpoolUsage: (id: number) =>
  4495. request<InventorySpool>(`/inventory/spools/${id}/reset-usage`, { method: 'POST' }),
  4496. bulkResetSpoolUsage: (spoolIds: number[]) =>
  4497. request<{ reset: number }>(`/inventory/spools/reset-usage-bulk`, {
  4498. method: 'POST',
  4499. body: JSON.stringify({ spool_ids: spoolIds }),
  4500. }),
  4501. getSpoolKProfiles: (spoolId: number) =>
  4502. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  4503. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4504. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  4505. method: 'PUT',
  4506. body: JSON.stringify(profiles),
  4507. }),
  4508. getAssignments: (printerId?: number) =>
  4509. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  4510. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4511. request<SpoolAssignment>('/inventory/assignments', {
  4512. method: 'POST',
  4513. body: JSON.stringify(data),
  4514. }),
  4515. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  4516. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  4517. // ── Spool label printing (#809) ──────────────────────────────────────────
  4518. // Both endpoints return application/pdf. Frontend opens the resulting Blob
  4519. // in a new tab so the user can print or save from the browser's PDF viewer.
  4520. printSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate }): Promise<Blob> => {
  4521. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4522. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4523. const response = await fetch(`${API_BASE}/inventory/labels`, {
  4524. method: 'POST',
  4525. headers,
  4526. body: JSON.stringify(data),
  4527. });
  4528. if (!response.ok) {
  4529. const error = await response.json().catch(() => ({}));
  4530. throw new Error(error.detail || `HTTP ${response.status}`);
  4531. }
  4532. return response.blob();
  4533. },
  4534. printSpoolmanSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate }): Promise<Blob> => {
  4535. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4536. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4537. const response = await fetch(`${API_BASE}/spoolman/labels`, {
  4538. method: 'POST',
  4539. headers,
  4540. body: JSON.stringify(data),
  4541. });
  4542. if (!response.ok) {
  4543. const error = await response.json().catch(() => ({}));
  4544. throw new Error(error.detail || `HTTP ${response.status}`);
  4545. }
  4546. return response.blob();
  4547. },
  4548. getSpoolCatalog: () =>
  4549. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  4550. addCatalogEntry: (data: { name: string; weight: number }) =>
  4551. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  4552. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  4553. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4554. deleteCatalogEntry: (id: number) =>
  4555. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  4556. bulkDeleteCatalogEntries: (ids: number[]) =>
  4557. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4558. resetSpoolCatalog: () =>
  4559. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  4560. getColorCatalog: () =>
  4561. request<ColorCatalogEntry[]>('/inventory/colors'),
  4562. getColorNameMap: () =>
  4563. request<{ colors: Record<string, string> }>('/inventory/colors/map'),
  4564. addColorEntry: (data: {
  4565. manufacturer: string;
  4566. color_name: string;
  4567. hex_color: string;
  4568. material: string | null;
  4569. extra_colors?: string | null;
  4570. effect_type?: string | null;
  4571. }) =>
  4572. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  4573. updateColorEntry: (
  4574. id: number,
  4575. data: {
  4576. manufacturer: string;
  4577. color_name: string;
  4578. hex_color: string;
  4579. material: string | null;
  4580. extra_colors?: string | null;
  4581. effect_type?: string | null;
  4582. },
  4583. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4584. deleteColorEntry: (id: number) =>
  4585. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  4586. bulkDeleteColorEntries: (ids: number[]) =>
  4587. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4588. resetColorCatalog: () =>
  4589. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  4590. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  4591. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  4592. searchColors: (manufacturer?: string, material?: string) =>
  4593. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  4594. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  4595. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  4596. method: 'PATCH',
  4597. body: JSON.stringify(data),
  4598. }),
  4599. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  4600. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  4601. getAllUsageHistory: (limit = 100, printerId?: number) =>
  4602. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  4603. clearSpoolUsageHistory: (spoolId: number) =>
  4604. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  4605. syncWeightsFromAms: () =>
  4606. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  4607. getSkuSettings: () =>
  4608. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  4609. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  4610. request<FilamentSkuSettings>('/inventory/sku-settings', {
  4611. method: 'POST',
  4612. body: JSON.stringify(data),
  4613. }),
  4614. getShoppingList: () =>
  4615. request<ShoppingListItem[]>('/inventory/shopping-list'),
  4616. addToShoppingList: (data: ShoppingListItemCreate) =>
  4617. request<ShoppingListItem>('/inventory/shopping-list', {
  4618. method: 'POST',
  4619. body: JSON.stringify(data),
  4620. }),
  4621. removeFromShoppingList: (id: number) =>
  4622. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  4623. clearShoppingList: () =>
  4624. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  4625. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  4626. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  4627. method: 'PATCH',
  4628. body: JSON.stringify({ status }),
  4629. }),
  4630. getFilamentPresets: () =>
  4631. request<SlicerSetting[]>('/cloud/filaments'),
  4632. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  4633. getSpoolmanInventorySpools: (includeArchived = false) =>
  4634. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  4635. getSpoolmanInventorySpool: (id: number) =>
  4636. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  4637. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4638. request<InventorySpool>('/spoolman/inventory/spools', {
  4639. method: 'POST',
  4640. body: JSON.stringify(data),
  4641. }),
  4642. bulkCreateSpoolmanInventorySpools: (
  4643. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  4644. quantity: number,
  4645. ) =>
  4646. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  4647. method: 'POST',
  4648. body: JSON.stringify({ spool: data, quantity }),
  4649. }),
  4650. updateSpoolmanInventorySpool: (
  4651. id: number,
  4652. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  4653. ) =>
  4654. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  4655. method: 'PATCH',
  4656. body: JSON.stringify(data),
  4657. }),
  4658. deleteSpoolmanInventorySpool: (id: number) =>
  4659. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  4660. archiveSpoolmanInventorySpool: (id: number) =>
  4661. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  4662. restoreSpoolmanInventorySpool: (id: number) =>
  4663. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  4664. resetSpoolmanInventorySpoolUsage: (id: number) =>
  4665. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-usage`, { method: 'POST' }),
  4666. bulkResetSpoolmanInventorySpoolUsage: (spoolIds: number[]) =>
  4667. request<{ reset: number }>(`/spoolman/inventory/spools/reset-usage-bulk`, {
  4668. method: 'POST',
  4669. body: JSON.stringify({ spool_ids: spoolIds }),
  4670. }),
  4671. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  4672. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  4673. method: 'PATCH',
  4674. body: JSON.stringify(data),
  4675. }),
  4676. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  4677. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  4678. method: 'PATCH',
  4679. body: JSON.stringify({ weight_grams: weightGrams }),
  4680. }),
  4681. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4682. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  4683. method: 'POST',
  4684. body: JSON.stringify(data),
  4685. }),
  4686. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  4687. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  4688. getSpoolmanSlotAssignment: (printerId: number, amsId: number, trayId: number) =>
  4689. request<InventorySpool | null>(
  4690. `/spoolman/inventory/slot-assignments?printer_id=${printerId}&ams_id=${amsId}&tray_id=${trayId}`,
  4691. ),
  4692. getSpoolmanSlotAssignments: (printerId?: number) =>
  4693. request<Array<{
  4694. printer_id: number;
  4695. printer_name: string | null;
  4696. ams_id: number;
  4697. tray_id: number;
  4698. spoolman_spool_id: number;
  4699. ams_label: string | null;
  4700. }>>(
  4701. printerId !== undefined
  4702. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  4703. : '/spoolman/inventory/slot-assignments/all',
  4704. ),
  4705. syncSpoolmanAmsWeights: () =>
  4706. request<{ synced: number; skipped: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  4707. getSpoolmanKProfiles: (spoolId: number) =>
  4708. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`),
  4709. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4710. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  4711. method: 'PUT',
  4712. body: JSON.stringify(profiles),
  4713. }),
  4714. // Updates
  4715. getVersion: () => request<VersionInfo>('/updates/version'),
  4716. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  4717. applyUpdate: () =>
  4718. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean }>('/updates/apply', {
  4719. method: 'POST',
  4720. }),
  4721. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  4722. // Maintenance
  4723. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  4724. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  4725. request<MaintenanceType>('/maintenance/types', {
  4726. method: 'POST',
  4727. body: JSON.stringify(data),
  4728. }),
  4729. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  4730. request<MaintenanceType>(`/maintenance/types/${id}`, {
  4731. method: 'PATCH',
  4732. body: JSON.stringify(data),
  4733. }),
  4734. deleteMaintenanceType: (id: number) =>
  4735. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  4736. restoreDefaultMaintenanceTypes: () =>
  4737. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  4738. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  4739. getPrinterMaintenance: (printerId: number) =>
  4740. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  4741. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  4742. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  4743. method: 'PATCH',
  4744. body: JSON.stringify(data),
  4745. }),
  4746. performMaintenance: (itemId: number, notes?: string) =>
  4747. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  4748. method: 'POST',
  4749. body: JSON.stringify({ notes }),
  4750. }),
  4751. getMaintenanceHistory: (itemId: number) =>
  4752. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  4753. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  4754. setPrinterHours: (printerId: number, totalHours: number) =>
  4755. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  4756. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  4757. { method: 'PATCH' }
  4758. ),
  4759. assignMaintenanceType: (printerId: number, typeId: number) =>
  4760. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  4761. method: 'POST',
  4762. }),
  4763. removeMaintenanceItem: (itemId: number) =>
  4764. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  4765. method: 'DELETE',
  4766. }),
  4767. // Camera
  4768. getCameraStreamToken: () =>
  4769. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  4770. // Long-lived camera-stream tokens (#1108)
  4771. createLongLivedCameraToken: (payload: { name: string; expires_in_days: number }) =>
  4772. request<LongLivedCameraToken>('/auth/tokens', {
  4773. method: 'POST',
  4774. body: JSON.stringify({ ...payload, scope: 'camera_stream' }),
  4775. }),
  4776. listMyLongLivedCameraTokens: () =>
  4777. request<LongLivedCameraToken[]>('/auth/tokens'),
  4778. listAllLongLivedCameraTokens: () =>
  4779. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  4780. listLongLivedCameraTokensForUser: (userId: number) =>
  4781. request<LongLivedCameraToken[]>(`/auth/tokens?user_id=${userId}`),
  4782. revokeLongLivedCameraToken: (tokenId: number) =>
  4783. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  4784. getCameraStreamUrl: (printerId: number, fps = 10) =>
  4785. withStreamToken(`${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`),
  4786. getCameraSnapshotUrl: (printerId: number) =>
  4787. withStreamToken(`${API_BASE}/printers/${printerId}/camera/snapshot`),
  4788. testCameraConnection: (printerId: number) =>
  4789. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  4790. getCameraStatus: (printerId: number) =>
  4791. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  4792. diagnoseCamera: (printerId: number) =>
  4793. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  4794. diagnosePrinter: (printerId: number) =>
  4795. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  4796. diagnoseConnection: (body: {
  4797. ip_address: string;
  4798. serial_number?: string;
  4799. access_code?: string;
  4800. }) =>
  4801. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  4802. method: 'POST',
  4803. body: JSON.stringify(body),
  4804. }),
  4805. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  4806. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  4807. const params = new URLSearchParams();
  4808. // Only forward use_external when the caller explicitly sets it. Omitted →
  4809. // backend derives the default from the printer's external_camera_enabled
  4810. // setting so calibration and runtime checks use the same camera (#1359).
  4811. if (options?.useExternal !== undefined) {
  4812. params.set('use_external', String(options.useExternal));
  4813. }
  4814. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  4815. return request<PlateDetectionResult>(
  4816. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  4817. );
  4818. },
  4819. getPlateDetectionStatus: (printerId: number) => {
  4820. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  4821. `/printers/${printerId}/camera/plate-detection/status`
  4822. );
  4823. },
  4824. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  4825. const params = new URLSearchParams();
  4826. if (options?.label) params.set('label', options.label);
  4827. if (options?.useExternal !== undefined) {
  4828. params.set('use_external', String(options.useExternal));
  4829. }
  4830. return request<CalibrationResult & { index: number }>(
  4831. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  4832. { method: 'POST' }
  4833. );
  4834. },
  4835. deletePlateCalibration: (printerId: number) => {
  4836. return request<CalibrationResult>(
  4837. `/printers/${printerId}/camera/plate-detection/calibrate`,
  4838. { method: 'DELETE' }
  4839. );
  4840. },
  4841. getPlateReferences: (printerId: number) => {
  4842. return request<{
  4843. references: PlateReference[];
  4844. max_references: number;
  4845. }>(`/printers/${printerId}/camera/plate-detection/references`);
  4846. },
  4847. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  4848. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  4849. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  4850. const params = new URLSearchParams();
  4851. params.set('label', label);
  4852. return request<{ success: boolean; index: number; label: string }>(
  4853. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  4854. { method: 'PUT' }
  4855. );
  4856. },
  4857. deletePlateReference: (printerId: number, index: number) => {
  4858. return request<{ success: boolean; message: string }>(
  4859. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  4860. { method: 'DELETE' }
  4861. );
  4862. },
  4863. // External Links
  4864. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  4865. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  4866. createExternalLink: (data: ExternalLinkCreate) =>
  4867. request<ExternalLink>('/external-links/', {
  4868. method: 'POST',
  4869. body: JSON.stringify(data),
  4870. }),
  4871. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  4872. request<ExternalLink>(`/external-links/${id}`, {
  4873. method: 'PATCH',
  4874. body: JSON.stringify(data),
  4875. }),
  4876. deleteExternalLink: (id: number) =>
  4877. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  4878. reorderExternalLinks: (ids: number[]) =>
  4879. request<ExternalLink[]>('/external-links/reorder', {
  4880. method: 'PUT',
  4881. body: JSON.stringify({ ids }),
  4882. }),
  4883. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  4884. const formData = new FormData();
  4885. formData.append('file', file);
  4886. const headers: Record<string, string> = {};
  4887. if (authToken) {
  4888. headers['Authorization'] = `Bearer ${authToken}`;
  4889. }
  4890. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  4891. method: 'POST',
  4892. headers,
  4893. body: formData,
  4894. });
  4895. if (!response.ok) {
  4896. const error = await response.json().catch(() => ({}));
  4897. throw new Error(error.detail || `HTTP ${response.status}`);
  4898. }
  4899. return response.json();
  4900. },
  4901. deleteExternalLinkIcon: (id: number) =>
  4902. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  4903. getExternalLinkIconUrl: (id: number) => withStreamToken(`${API_BASE}/external-links/${id}/icon`),
  4904. // Projects
  4905. getProjects: (status?: string) => {
  4906. const params = new URLSearchParams();
  4907. if (status) params.set('status', status);
  4908. return request<ProjectListItem[]>(`/projects/?${params}`);
  4909. },
  4910. getProject: (id: number) => request<Project>(`/projects/${id}`),
  4911. createProject: (data: ProjectCreate) =>
  4912. request<Project>('/projects/', {
  4913. method: 'POST',
  4914. body: JSON.stringify(data),
  4915. }),
  4916. updateProject: (id: number, data: ProjectUpdate) =>
  4917. request<Project>(`/projects/${id}`, {
  4918. method: 'PATCH',
  4919. body: JSON.stringify(data),
  4920. }),
  4921. deleteProject: (id: number) =>
  4922. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  4923. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  4924. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  4925. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  4926. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  4927. method: 'POST',
  4928. body: JSON.stringify({ archive_ids: archiveIds }),
  4929. }),
  4930. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  4931. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  4932. method: 'POST',
  4933. body: JSON.stringify({ archive_ids: archiveIds }),
  4934. }),
  4935. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  4936. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  4937. method: 'POST',
  4938. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  4939. }),
  4940. // Project Attachments
  4941. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  4942. status: string;
  4943. filename: string;
  4944. original_name: string;
  4945. attachments: ProjectAttachment[];
  4946. }> => {
  4947. const formData = new FormData();
  4948. formData.append('file', file);
  4949. const headers: Record<string, string> = {};
  4950. if (authToken) {
  4951. headers['Authorization'] = `Bearer ${authToken}`;
  4952. }
  4953. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  4954. method: 'POST',
  4955. headers,
  4956. body: formData,
  4957. });
  4958. if (!response.ok) {
  4959. const error = await response.json().catch(() => ({}));
  4960. throw new Error(error.detail || `HTTP ${response.status}`);
  4961. }
  4962. return response.json();
  4963. },
  4964. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  4965. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  4966. deleteProjectAttachment: (projectId: number, filename: string) =>
  4967. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  4968. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  4969. { method: 'DELETE' }
  4970. ),
  4971. // #1155: Cover image
  4972. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  4973. // append the stream-token query string the same way archive thumbnails do.
  4974. getProjectCoverImageUrl: (projectId: number) =>
  4975. withStreamToken(`${API_BASE}/projects/${projectId}/cover-image`),
  4976. uploadProjectCoverImage: async (
  4977. projectId: number,
  4978. file: File
  4979. ): Promise<{ status: string; filename: string; size: number }> => {
  4980. const formData = new FormData();
  4981. formData.append('file', file);
  4982. const headers: Record<string, string> = {};
  4983. if (authToken) {
  4984. headers['Authorization'] = `Bearer ${authToken}`;
  4985. }
  4986. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  4987. method: 'POST',
  4988. headers,
  4989. body: formData,
  4990. });
  4991. if (!response.ok) {
  4992. const error = await response.json().catch(() => ({}));
  4993. throw new Error(error.detail || `HTTP ${response.status}`);
  4994. }
  4995. return response.json();
  4996. },
  4997. deleteProjectCoverImage: (projectId: number) =>
  4998. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  4999. // BOM (Bill of Materials)
  5000. getProjectBOM: (projectId: number) =>
  5001. request<BOMItem[]>(`/projects/${projectId}/bom`),
  5002. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  5003. request<BOMItem>(`/projects/${projectId}/bom`, {
  5004. method: 'POST',
  5005. body: JSON.stringify(data),
  5006. }),
  5007. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  5008. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  5009. method: 'PATCH',
  5010. body: JSON.stringify(data),
  5011. }),
  5012. deleteBOMItem: (projectId: number, itemId: number) =>
  5013. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  5014. method: 'DELETE',
  5015. }),
  5016. // Templates
  5017. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  5018. createTemplateFromProject: (projectId: number) =>
  5019. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  5020. createProjectFromTemplate: (templateId: number, name?: string) =>
  5021. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  5022. method: 'POST',
  5023. }),
  5024. // Timeline
  5025. getProjectTimeline: (projectId: number, limit = 50) =>
  5026. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  5027. // Project Export/Import
  5028. exportProjectJson: (projectId: number) =>
  5029. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  5030. importProject: (data: ProjectImport) =>
  5031. request<Project>('/projects/import', {
  5032. method: 'POST',
  5033. body: JSON.stringify(data),
  5034. }),
  5035. importProjectFile: async (file: File): Promise<Project> => {
  5036. const formData = new FormData();
  5037. formData.append('file', file);
  5038. const headers: Record<string, string> = {};
  5039. if (authToken) {
  5040. headers['Authorization'] = `Bearer ${authToken}`;
  5041. }
  5042. const response = await fetch(`${API_BASE}/projects/import/file`, {
  5043. method: 'POST',
  5044. headers,
  5045. body: formData,
  5046. });
  5047. if (!response.ok) {
  5048. const error = await response.json().catch(() => ({}));
  5049. throw new Error(error.detail || `HTTP ${response.status}`);
  5050. }
  5051. return response.json();
  5052. },
  5053. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  5054. const headers: Record<string, string> = {};
  5055. if (authToken) {
  5056. headers['Authorization'] = `Bearer ${authToken}`;
  5057. }
  5058. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  5059. headers,
  5060. });
  5061. if (!response.ok) {
  5062. const error = await response.json().catch(() => ({}));
  5063. throw new Error(error.detail || `HTTP ${response.status}`);
  5064. }
  5065. const contentDisposition = response.headers.get('Content-Disposition');
  5066. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  5067. const blob = await response.blob();
  5068. return { blob, filename };
  5069. },
  5070. // API Keys
  5071. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  5072. createAPIKey: (data: APIKeyCreate) =>
  5073. request<APIKeyCreateResponse>('/api-keys/', {
  5074. method: 'POST',
  5075. body: JSON.stringify(data),
  5076. }),
  5077. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  5078. request<APIKey>(`/api-keys/${id}`, {
  5079. method: 'PATCH',
  5080. body: JSON.stringify(data),
  5081. }),
  5082. deleteAPIKey: (id: number) =>
  5083. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  5084. // AMS History
  5085. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  5086. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  5087. // System Info
  5088. getSystemInfo: () => request<SystemInfo>('/system/info'),
  5089. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  5090. getStorageUsage: (options?: { refresh?: boolean }) => {
  5091. const params = new URLSearchParams();
  5092. if (options?.refresh) {
  5093. params.set('refresh', 'true');
  5094. }
  5095. const query = params.toString();
  5096. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  5097. },
  5098. // Library (File Manager)
  5099. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  5100. createLibraryFolder: (data: LibraryFolderCreate) =>
  5101. request<LibraryFolder>('/library/folders', {
  5102. method: 'POST',
  5103. body: JSON.stringify(data),
  5104. }),
  5105. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  5106. request<LibraryFolder>(`/library/folders/${id}`, {
  5107. method: 'PUT',
  5108. body: JSON.stringify(data),
  5109. }),
  5110. deleteLibraryFolder: (id: number) =>
  5111. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  5112. createExternalFolder: (data: ExternalFolderCreate) =>
  5113. request<LibraryFolder>('/library/folders/external', {
  5114. method: 'POST',
  5115. body: JSON.stringify(data),
  5116. }),
  5117. scanExternalFolder: (folderId: number) =>
  5118. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  5119. method: 'POST',
  5120. }),
  5121. getLibraryFoldersByProject: (projectId: number) =>
  5122. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  5123. getLibraryFoldersByArchive: (archiveId: number) =>
  5124. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  5125. getLibraryFiles: (folderId?: number | null, includeRoot = true, projectId?: number) => {
  5126. const params = new URLSearchParams();
  5127. if (folderId !== undefined && folderId !== null) {
  5128. params.set('folder_id', String(folderId));
  5129. }
  5130. if (projectId !== undefined) {
  5131. params.set('project_id', String(projectId));
  5132. }
  5133. params.set('include_root', String(includeRoot));
  5134. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  5135. },
  5136. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  5137. uploadLibraryFile: async (
  5138. file: File,
  5139. folderId?: number | null,
  5140. generateStlThumbnails: boolean = true
  5141. ): Promise<LibraryFileUploadResponse> => {
  5142. const formData = new FormData();
  5143. formData.append('file', file);
  5144. const params = new URLSearchParams();
  5145. if (folderId) params.set('folder_id', String(folderId));
  5146. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5147. const headers: Record<string, string> = {};
  5148. if (authToken) {
  5149. headers['Authorization'] = `Bearer ${authToken}`;
  5150. }
  5151. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  5152. method: 'POST',
  5153. headers,
  5154. body: formData,
  5155. });
  5156. if (!response.ok) {
  5157. const error = await response.json().catch(() => ({}));
  5158. throw new Error(error.detail || `HTTP ${response.status}`);
  5159. }
  5160. return response.json();
  5161. },
  5162. extractZipFile: async (
  5163. file: File,
  5164. folderId?: number | null,
  5165. preserveStructure: boolean = true,
  5166. createFolderFromZip: boolean = false,
  5167. generateStlThumbnails: boolean = true
  5168. ): Promise<ZipExtractResponse> => {
  5169. const formData = new FormData();
  5170. formData.append('file', file);
  5171. const params = new URLSearchParams();
  5172. if (folderId) params.set('folder_id', String(folderId));
  5173. params.set('preserve_structure', String(preserveStructure));
  5174. params.set('create_folder_from_zip', String(createFolderFromZip));
  5175. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5176. const headers: Record<string, string> = {};
  5177. if (authToken) {
  5178. headers['Authorization'] = `Bearer ${authToken}`;
  5179. }
  5180. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  5181. method: 'POST',
  5182. headers,
  5183. body: formData,
  5184. });
  5185. if (!response.ok) {
  5186. const error = await response.json().catch(() => ({}));
  5187. throw new Error(error.detail || `HTTP ${response.status}`);
  5188. }
  5189. return response.json();
  5190. },
  5191. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  5192. request<LibraryFile>(`/library/files/${id}`, {
  5193. method: 'PUT',
  5194. body: JSON.stringify(data),
  5195. }),
  5196. deleteLibraryFile: (id: number) =>
  5197. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  5198. // ========== Library Trash (#1008) ==========
  5199. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5200. request<LibraryPurgePreview>(
  5201. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  5202. ),
  5203. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5204. request<{ moved_to_trash: number }>('/library/purge', {
  5205. method: 'POST',
  5206. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  5207. }),
  5208. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  5209. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  5210. restoreLibraryTrash: (fileId: number) =>
  5211. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  5212. hardDeleteLibraryTrash: (fileId: number) =>
  5213. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  5214. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  5215. getLibraryTrashSettings: () =>
  5216. request<LibraryTrashSettings>('/library/trash/settings'),
  5217. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  5218. request<LibraryTrashSettings>('/library/trash/settings', {
  5219. method: 'PUT',
  5220. body: JSON.stringify(body),
  5221. }),
  5222. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  5223. createLibrarySlicerToken: (fileId: number) =>
  5224. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  5225. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  5226. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  5227. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  5228. const headers: Record<string, string> = {};
  5229. if (authToken) {
  5230. headers['Authorization'] = `Bearer ${authToken}`;
  5231. }
  5232. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  5233. if (!response.ok) {
  5234. const error = await response.json().catch(() => ({}));
  5235. throw new Error(error.detail || `HTTP ${response.status}`);
  5236. }
  5237. const disposition = response.headers.get('Content-Disposition');
  5238. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  5239. const blob = await response.blob();
  5240. const url = window.URL.createObjectURL(blob);
  5241. const a = document.createElement('a');
  5242. a.href = url;
  5243. a.download = downloadFilename;
  5244. document.body.appendChild(a);
  5245. a.click();
  5246. document.body.removeChild(a);
  5247. window.URL.revokeObjectURL(url);
  5248. },
  5249. getLibraryFileThumbnailUrl: (id: number) => withStreamToken(`${API_BASE}/library/files/${id}/thumbnail`),
  5250. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  5251. withStreamToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  5252. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  5253. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  5254. request<{ status: string; moved: number }>('/library/files/move', {
  5255. method: 'POST',
  5256. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  5257. }),
  5258. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  5259. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  5260. method: 'POST',
  5261. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  5262. }),
  5263. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  5264. batchGenerateStlThumbnails: (options: {
  5265. file_ids?: number[];
  5266. folder_id?: number;
  5267. all_missing?: boolean;
  5268. }) =>
  5269. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  5270. method: 'POST',
  5271. body: JSON.stringify(options),
  5272. }),
  5273. addLibraryFilesToQueue: (fileIds: number[]) =>
  5274. request<AddToQueueResponse>('/library/files/add-to-queue', {
  5275. method: 'POST',
  5276. body: JSON.stringify({ file_ids: fileIds }),
  5277. }),
  5278. printLibraryFile: (
  5279. fileId: number,
  5280. printerId: number,
  5281. options?: {
  5282. plate_id?: number;
  5283. plate_name?: string;
  5284. ams_mapping?: number[];
  5285. bed_levelling?: boolean;
  5286. flow_cali?: boolean;
  5287. vibration_cali?: boolean;
  5288. layer_inspect?: boolean;
  5289. timelapse?: boolean;
  5290. use_ams?: boolean;
  5291. project_id?: number;
  5292. cleanup_library_after_dispatch?: boolean;
  5293. }
  5294. ) =>
  5295. request<BackgroundDispatchResponse>(
  5296. `/library/files/${fileId}/print?printer_id=${printerId}`,
  5297. {
  5298. method: 'POST',
  5299. body: options ? JSON.stringify(options) : undefined,
  5300. }
  5301. ),
  5302. cancelBackgroundDispatchJob: (jobId: number) =>
  5303. request<{
  5304. status: 'cancelled' | 'cancelling';
  5305. job_id: number;
  5306. source_name: string;
  5307. printer_id: number;
  5308. printer_name: string;
  5309. }>(`/background-dispatch/${jobId}`, {
  5310. method: 'DELETE',
  5311. }),
  5312. getLibraryFilePlates: (fileId: number) =>
  5313. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  5314. getLibraryFileFilamentRequirements: (
  5315. fileId: number,
  5316. plateId?: number,
  5317. requestId?: string,
  5318. // Optional bundle context — see getArchiveFilamentRequirements above
  5319. // for the contract. Same shape so callers can share a builder helper.
  5320. bundle?: {
  5321. bundle_id: string;
  5322. printer_name: string;
  5323. process_name: string;
  5324. filament_names: string[];
  5325. },
  5326. ) => {
  5327. const qs = new URLSearchParams();
  5328. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5329. if (requestId) qs.set('request_id', requestId);
  5330. if (bundle) {
  5331. qs.set('bundle_id', bundle.bundle_id);
  5332. qs.set('printer_name', bundle.printer_name);
  5333. qs.set('process_name', bundle.process_name);
  5334. qs.set('filament_names', bundle.filament_names.join(';'));
  5335. }
  5336. return request<{
  5337. file_id: number;
  5338. filename: string;
  5339. filaments: Array<{
  5340. slot_id: number;
  5341. type: string;
  5342. color: string;
  5343. used_grams: number;
  5344. used_meters: number;
  5345. used_in_plate?: boolean;
  5346. }>;
  5347. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5348. },
  5349. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  5350. * proxy. Used by the SliceModal's filament-discovery path so the inline
  5351. * spinner + persistent toast can show "Generating G-code (45%)" while
  5352. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  5353. * have an entry — early race window — or it expired) so the poller
  5354. * can keep trying. */
  5355. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  5356. try {
  5357. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  5358. } catch {
  5359. return null;
  5360. }
  5361. },
  5362. // GitHub Backup
  5363. getGitHubBackupConfig: () =>
  5364. request<GitHubBackupConfig | null>('/github-backup/config'),
  5365. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  5366. request<GitHubBackupConfig>('/github-backup/config', {
  5367. method: 'POST',
  5368. body: JSON.stringify(config),
  5369. }),
  5370. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  5371. request<GitHubBackupConfig>('/github-backup/config', {
  5372. method: 'PATCH',
  5373. body: JSON.stringify(config),
  5374. }),
  5375. deleteGitHubBackupConfig: () =>
  5376. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  5377. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  5378. request<GitHubTestConnectionResponse>(
  5379. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}&provider=${encodeURIComponent(provider)}`,
  5380. { method: 'POST' }
  5381. ),
  5382. testGitHubStoredConnection: () =>
  5383. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  5384. triggerGitHubBackup: () =>
  5385. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  5386. getGitHubBackupStatus: () =>
  5387. request<GitHubBackupStatus>('/github-backup/status'),
  5388. getGitHubBackupLogs: (limit: number = 50) =>
  5389. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  5390. clearGitHubBackupLogs: (keepLast: number = 10) =>
  5391. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  5392. // Scheduled local backups
  5393. getLocalBackupStatus: () =>
  5394. request<LocalBackupStatus>('/local-backup/status'),
  5395. triggerLocalBackup: () =>
  5396. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  5397. getLocalBackups: () =>
  5398. request<LocalBackupFile[]>('/local-backup/backups'),
  5399. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  5400. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  5401. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5402. });
  5403. if (!response.ok) throw new Error('Download failed');
  5404. const blob = await response.blob();
  5405. return { blob, filename };
  5406. },
  5407. restoreLocalBackup: (filename: string) =>
  5408. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  5409. deleteLocalBackup: (filename: string) =>
  5410. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  5411. // Obico AI failure detection
  5412. getObicoStatus: () =>
  5413. request<ObicoStatus>('/obico/status'),
  5414. testObicoConnection: (url: string) =>
  5415. request<ObicoTestConnection>('/obico/test-connection', {
  5416. method: 'POST',
  5417. body: JSON.stringify({ url }),
  5418. }),
  5419. // Slicer API — slice in the background. Both endpoints return 202 + a
  5420. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  5421. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  5422. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  5423. method: 'POST',
  5424. body: JSON.stringify(body),
  5425. }),
  5426. sliceArchive: (archiveId: number, body: SliceRequest) =>
  5427. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  5428. method: 'POST',
  5429. body: JSON.stringify(body),
  5430. }),
  5431. getSliceJob: (jobId: number) =>
  5432. request<SliceJobState>(`/slice-jobs/${jobId}`),
  5433. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  5434. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  5435. // backend/app/api/routes/slicer_presets.py for the priority rules.
  5436. getSlicerPresets: () =>
  5437. request<UnifiedPresetsResponse>('/slicer/presets'),
  5438. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  5439. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  5440. // SliceModal uses this to classify cloud / standard presets by their
  5441. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  5442. getSlicerPrinterModels: () =>
  5443. request<Record<string, string>>('/slicer/printer-models'),
  5444. // Slicer Bundles (.bbscfg) — Printer Preset Bundles imported from BambuStudio.
  5445. // Settings → Slicer Bundles uploads/lists/deletes; the SliceModal picks
  5446. // presets by name from a chosen bundle (separate follow-up).
  5447. listSlicerBundles: () =>
  5448. request<SlicerBundle[]>('/slicer/bundles'),
  5449. importSlicerBundle: (file: File) => {
  5450. // The /slicer/bundles upload accepts multipart with field name "file"
  5451. // (matches the FastAPI route's UploadFile parameter). Bypass `request`
  5452. // because it always JSON-stringifies the body — multipart needs the
  5453. // browser to set the boundary in the Content-Type header.
  5454. const fd = new FormData();
  5455. fd.append('file', file);
  5456. return fetch(`${API_BASE}/slicer/bundles`, {
  5457. method: 'POST',
  5458. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5459. body: fd,
  5460. }).then(async (res) => {
  5461. if (!res.ok) {
  5462. const err = await res.json().catch(() => ({}));
  5463. throw new Error(err.detail || `HTTP ${res.status}`);
  5464. }
  5465. return res.json() as Promise<SlicerBundle>;
  5466. });
  5467. },
  5468. deleteSlicerBundle: (bundleId: string) =>
  5469. request<void>(`/slicer/bundles/${encodeURIComponent(bundleId)}`, {
  5470. method: 'DELETE',
  5471. }),
  5472. // Local Presets (OrcaSlicer imports)
  5473. getLocalPresets: () =>
  5474. request<LocalPresetsResponse>('/local-presets/'),
  5475. getLocalPresetDetail: (id: number) =>
  5476. request<LocalPresetDetail>(`/local-presets/${id}`),
  5477. importLocalPresets: (formData: FormData) =>
  5478. fetch(`${API_BASE}/local-presets/import`, {
  5479. method: 'POST',
  5480. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5481. body: formData,
  5482. }).then(async (res) => {
  5483. if (!res.ok) {
  5484. const err = await res.json().catch(() => ({}));
  5485. throw new Error(err.detail || `HTTP ${res.status}`);
  5486. }
  5487. return res.json() as Promise<ImportResponse>;
  5488. }),
  5489. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  5490. request<LocalPreset>('/local-presets/', {
  5491. method: 'POST',
  5492. body: JSON.stringify(data),
  5493. }),
  5494. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  5495. request<LocalPreset>(`/local-presets/${id}`, {
  5496. method: 'PUT',
  5497. body: JSON.stringify(data),
  5498. }),
  5499. deleteLocalPreset: (id: number) =>
  5500. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  5501. refreshBaseProfileCache: () =>
  5502. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  5503. };
  5504. // AMS History types
  5505. export interface AMSHistoryPoint {
  5506. recorded_at: string;
  5507. humidity: number | null;
  5508. humidity_raw: number | null;
  5509. temperature: number | null;
  5510. }
  5511. export interface AMSHistoryResponse {
  5512. printer_id: number;
  5513. ams_id: number;
  5514. data: AMSHistoryPoint[];
  5515. min_humidity: number | null;
  5516. max_humidity: number | null;
  5517. avg_humidity: number | null;
  5518. min_temperature: number | null;
  5519. max_temperature: number | null;
  5520. avg_temperature: number | null;
  5521. }
  5522. // System Info types
  5523. export interface SystemInfo {
  5524. app: {
  5525. version: string;
  5526. base_dir: string;
  5527. archive_dir: string;
  5528. };
  5529. database: {
  5530. engine: string;
  5531. version: string;
  5532. archives: number;
  5533. archives_completed: number;
  5534. archives_failed: number;
  5535. archives_printing: number;
  5536. printers: number;
  5537. filaments: number;
  5538. projects: number;
  5539. smart_plugs: number;
  5540. total_print_time_seconds: number;
  5541. total_print_time_formatted: string;
  5542. total_filament_grams: number;
  5543. total_filament_kg: number;
  5544. };
  5545. printers: {
  5546. total: number;
  5547. connected: number;
  5548. connected_list: Array<{
  5549. id: number;
  5550. name: string;
  5551. state: string;
  5552. model: string;
  5553. }>;
  5554. };
  5555. storage: {
  5556. archive_size_bytes: number;
  5557. archive_size_formatted: string;
  5558. database_size_bytes: number;
  5559. database_size_formatted: string;
  5560. disk_total_bytes: number;
  5561. disk_total_formatted: string;
  5562. disk_used_bytes: number;
  5563. disk_used_formatted: string;
  5564. disk_free_bytes: number;
  5565. disk_free_formatted: string;
  5566. disk_percent_used: number;
  5567. };
  5568. system: {
  5569. platform: string;
  5570. platform_release: string;
  5571. platform_version: string;
  5572. architecture: string;
  5573. hostname: string;
  5574. python_version: string;
  5575. uptime_seconds: number;
  5576. uptime_formatted: string;
  5577. boot_time: string;
  5578. };
  5579. memory: {
  5580. total_bytes: number;
  5581. total_formatted: string;
  5582. available_bytes: number;
  5583. available_formatted: string;
  5584. used_bytes: number;
  5585. used_formatted: string;
  5586. percent_used: number;
  5587. };
  5588. cpu: {
  5589. count: number;
  5590. count_logical: number;
  5591. percent: number;
  5592. };
  5593. }
  5594. export interface StorageUsageCategory {
  5595. key: string;
  5596. label: string;
  5597. bytes: number;
  5598. formatted: string;
  5599. percent_of_total: number;
  5600. }
  5601. export interface StorageUsageOtherItem {
  5602. bucket: string;
  5603. label: string;
  5604. kind: 'system' | 'data';
  5605. deletable: boolean;
  5606. bytes: number;
  5607. formatted: string;
  5608. percent_of_total: number;
  5609. }
  5610. export interface StorageUsageResponse {
  5611. roots: string[];
  5612. total_bytes: number;
  5613. total_formatted: string;
  5614. categories: StorageUsageCategory[];
  5615. other_breakdown: StorageUsageOtherItem[];
  5616. scan_errors: number;
  5617. generated_at: string;
  5618. cache: {
  5619. hit: boolean;
  5620. age_seconds: number;
  5621. max_age_seconds: number;
  5622. };
  5623. }
  5624. // Library (File Manager) types
  5625. export interface LibraryFolderTree {
  5626. id: number;
  5627. name: string;
  5628. parent_id: number | null;
  5629. project_id: number | null;
  5630. archive_id: number | null;
  5631. project_name: string | null;
  5632. archive_name: string | null;
  5633. is_external: boolean;
  5634. external_path: string | null;
  5635. external_readonly: boolean;
  5636. file_count: number;
  5637. children: LibraryFolderTree[];
  5638. }
  5639. export interface LibraryFolder {
  5640. id: number;
  5641. name: string;
  5642. parent_id: number | null;
  5643. project_id: number | null;
  5644. archive_id: number | null;
  5645. project_name: string | null;
  5646. archive_name: string | null;
  5647. is_external: boolean;
  5648. external_path: string | null;
  5649. external_readonly: boolean;
  5650. external_show_hidden: boolean;
  5651. file_count: number;
  5652. created_at: string;
  5653. updated_at: string;
  5654. }
  5655. export interface LibraryFolderCreate {
  5656. name: string;
  5657. parent_id?: number | null;
  5658. project_id?: number | null;
  5659. archive_id?: number | null;
  5660. }
  5661. export interface ExternalFolderCreate {
  5662. name: string;
  5663. external_path: string;
  5664. readonly?: boolean;
  5665. show_hidden?: boolean;
  5666. parent_id?: number | null;
  5667. }
  5668. export interface LibraryFolderUpdate {
  5669. name?: string;
  5670. parent_id?: number | null;
  5671. project_id?: number | null; // 0 to unlink
  5672. archive_id?: number | null; // 0 to unlink
  5673. }
  5674. export interface LibraryFileDuplicate {
  5675. id: number;
  5676. filename: string;
  5677. folder_id: number | null;
  5678. folder_name: string | null;
  5679. created_at: string;
  5680. }
  5681. export interface LibraryFile {
  5682. id: number;
  5683. folder_id: number | null;
  5684. folder_name: string | null;
  5685. project_id: number | null;
  5686. project_name: string | null;
  5687. is_external: boolean;
  5688. filename: string;
  5689. file_path: string;
  5690. file_type: string;
  5691. file_size: number;
  5692. file_hash: string | null;
  5693. thumbnail_path: string | null;
  5694. metadata: Record<string, unknown> | null;
  5695. print_count: number;
  5696. last_printed_at: string | null;
  5697. notes: string | null;
  5698. duplicates: LibraryFileDuplicate[] | null;
  5699. duplicate_count: number;
  5700. // User tracking (Issue #206)
  5701. created_by_id: number | null;
  5702. created_by_username: string | null;
  5703. created_at: string;
  5704. updated_at: string;
  5705. // Metadata fields
  5706. print_name: string | null;
  5707. print_time_seconds: number | null;
  5708. filament_used_grams: number | null;
  5709. sliced_for_model: string | null;
  5710. }
  5711. export interface LibraryFileListItem {
  5712. id: number;
  5713. folder_id: number | null;
  5714. is_external: boolean;
  5715. filename: string;
  5716. file_type: string;
  5717. file_size: number;
  5718. thumbnail_path: string | null;
  5719. print_count: number;
  5720. duplicate_count: number;
  5721. // User tracking (Issue #206)
  5722. created_by_id: number | null;
  5723. created_by_username: string | null;
  5724. created_at: string;
  5725. print_name: string | null;
  5726. print_time_seconds: number | null;
  5727. filament_used_grams: number | null;
  5728. sliced_for_model: string | null;
  5729. }
  5730. export interface LibraryFileUpdate {
  5731. filename?: string;
  5732. folder_id?: number | null;
  5733. project_id?: number | null;
  5734. notes?: string | null;
  5735. }
  5736. // Library trash (#1008)
  5737. export interface LibraryTrashItem {
  5738. id: number;
  5739. filename: string;
  5740. file_size: number;
  5741. thumbnail_path: string | null;
  5742. folder_id: number | null;
  5743. folder_name: string | null;
  5744. created_by_id: number | null;
  5745. created_by_username: string | null;
  5746. deleted_at: string;
  5747. auto_purge_at: string;
  5748. }
  5749. export interface LibraryTrashListResponse {
  5750. items: LibraryTrashItem[];
  5751. total: number;
  5752. retention_days: number;
  5753. }
  5754. export interface LibraryPurgePreview {
  5755. count: number;
  5756. total_bytes: number;
  5757. sample_filenames: string[];
  5758. older_than_days: number;
  5759. include_never_printed: boolean;
  5760. }
  5761. export interface LibraryTrashSettings {
  5762. retention_days: number;
  5763. auto_purge_enabled: boolean;
  5764. auto_purge_days: number;
  5765. auto_purge_include_never_printed: boolean;
  5766. }
  5767. export interface ArchivePurgePreview {
  5768. count: number;
  5769. total_bytes: number;
  5770. sample_filenames: string[];
  5771. older_than_days: number;
  5772. }
  5773. export interface ArchivePurgeSettings {
  5774. enabled: boolean;
  5775. days: number;
  5776. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  5777. // contribution drops from Quick Stats too. Default false — soft-delete,
  5778. // Quick Stats preserved.
  5779. purge_stats: boolean;
  5780. }
  5781. export interface LibraryFileUploadResponse {
  5782. id: number;
  5783. filename: string;
  5784. file_type: string;
  5785. file_size: number;
  5786. thumbnail_path: string | null;
  5787. duplicate_of: number | null;
  5788. metadata: Record<string, unknown> | null;
  5789. }
  5790. export interface LibraryStats {
  5791. total_files: number;
  5792. total_folders: number;
  5793. total_size_bytes: number;
  5794. files_by_type: Record<string, number>;
  5795. total_prints: number;
  5796. disk_free_bytes: number;
  5797. disk_total_bytes: number;
  5798. disk_used_bytes: number;
  5799. }
  5800. export interface ZipExtractResult {
  5801. filename: string;
  5802. file_id: number;
  5803. folder_id: number | null;
  5804. }
  5805. export interface ZipExtractError {
  5806. filename: string;
  5807. error: string;
  5808. }
  5809. export interface ZipExtractResponse {
  5810. extracted: number;
  5811. folders_created: number;
  5812. files: ZipExtractResult[];
  5813. errors: ZipExtractError[];
  5814. }
  5815. // STL Thumbnail Generation types
  5816. export interface BatchThumbnailResult {
  5817. file_id: number;
  5818. filename: string;
  5819. success: boolean;
  5820. error?: string | null;
  5821. }
  5822. export interface BatchThumbnailResponse {
  5823. processed: number;
  5824. succeeded: number;
  5825. failed: number;
  5826. results: BatchThumbnailResult[];
  5827. }
  5828. // Library Queue types
  5829. export interface AddToQueueResult {
  5830. file_id: number;
  5831. filename: string;
  5832. queue_item_id: number;
  5833. archive_id: number;
  5834. }
  5835. export interface AddToQueueError {
  5836. file_id: number;
  5837. filename: string;
  5838. error: string;
  5839. }
  5840. export interface AddToQueueResponse {
  5841. added: AddToQueueResult[];
  5842. errors: AddToQueueError[];
  5843. }
  5844. // Discovery types
  5845. export interface DiscoveredPrinter {
  5846. serial: string;
  5847. name: string;
  5848. ip_address: string;
  5849. model: string | null;
  5850. discovered_at: string | null;
  5851. }
  5852. export interface DiscoveryStatus {
  5853. running: boolean;
  5854. }
  5855. export interface DiscoveryInfo {
  5856. is_docker: boolean;
  5857. ssdp_running: boolean;
  5858. scan_running: boolean;
  5859. subnets: string[];
  5860. }
  5861. export interface SubnetScanStatus {
  5862. running: boolean;
  5863. scanned: number;
  5864. total: number;
  5865. }
  5866. // Discovery API
  5867. export const discoveryApi = {
  5868. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  5869. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  5870. startDiscovery: (duration: number = 10) =>
  5871. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  5872. stopDiscovery: () =>
  5873. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  5874. getDiscoveredPrinters: () =>
  5875. request<DiscoveredPrinter[]>('/discovery/printers'),
  5876. // Subnet scanning (for Docker environments)
  5877. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  5878. request<SubnetScanStatus>('/discovery/scan', {
  5879. method: 'POST',
  5880. body: JSON.stringify({ subnet, timeout }),
  5881. }),
  5882. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  5883. stopSubnetScan: () =>
  5884. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  5885. };
  5886. // Virtual Printer types
  5887. export type VirtualPrinterMode = 'immediate' | 'queue' | 'review' | 'print_queue' | 'proxy'; // 'queue' is legacy, normalized to 'review'
  5888. export interface VirtualPrinterProxyStatus {
  5889. running: boolean;
  5890. target_host: string;
  5891. ftp_port: number;
  5892. mqtt_port: number;
  5893. ftp_connections: number;
  5894. mqtt_connections: number;
  5895. }
  5896. export interface VirtualPrinterStatus {
  5897. enabled: boolean;
  5898. running: boolean;
  5899. mode: VirtualPrinterMode;
  5900. name: string;
  5901. serial: string;
  5902. model: string;
  5903. model_name: string;
  5904. pending_files: number;
  5905. target_printer_ip?: string; // For proxy mode
  5906. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  5907. }
  5908. export interface VirtualPrinterSettings {
  5909. enabled: boolean;
  5910. access_code_set: boolean;
  5911. mode: VirtualPrinterMode;
  5912. model: string;
  5913. target_printer_id: number | null; // For proxy mode
  5914. remote_interface_ip: string | null; // For SSDP proxy across networks
  5915. tailscale_disabled: boolean;
  5916. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  5917. status: VirtualPrinterStatus;
  5918. }
  5919. export interface NetworkInterface {
  5920. name: string;
  5921. ip: string;
  5922. netmask: string;
  5923. subnet: string;
  5924. is_alias?: boolean;
  5925. label?: string;
  5926. }
  5927. export interface VirtualPrinterModels {
  5928. models: Record<string, string>; // SSDP code -> display name
  5929. default: string;
  5930. }
  5931. export interface PendingUpload {
  5932. id: number;
  5933. filename: string;
  5934. // Resolved name the review card should show — mirrors what archive_print
  5935. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  5936. // back to the stripped filename stem when the 3MF has no embedded title or
  5937. // the operator has chosen the "filename" archive-name source.
  5938. display_name: string;
  5939. file_size: number;
  5940. source_ip: string | null;
  5941. status: string;
  5942. tags: string | null;
  5943. notes: string | null;
  5944. project_id: number | null;
  5945. uploaded_at: string;
  5946. }
  5947. // Virtual Printer API
  5948. export const virtualPrinterApi = {
  5949. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  5950. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  5951. updateSettings: (data: {
  5952. enabled?: boolean;
  5953. access_code?: string;
  5954. mode?: 'immediate' | 'review' | 'print_queue' | 'proxy';
  5955. model?: string;
  5956. target_printer_id?: number;
  5957. remote_interface_ip?: string;
  5958. tailscale_disabled?: boolean;
  5959. archive_name_source?: 'metadata' | 'filename';
  5960. }) => {
  5961. const params = new URLSearchParams();
  5962. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  5963. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  5964. if (data.mode !== undefined) params.set('mode', data.mode);
  5965. if (data.model !== undefined) params.set('model', data.model);
  5966. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  5967. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  5968. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  5969. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  5970. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  5971. method: 'PUT',
  5972. });
  5973. },
  5974. };
  5975. // Multi Virtual Printer API
  5976. export interface VirtualPrinterConfig {
  5977. id: number;
  5978. name: string;
  5979. enabled: boolean;
  5980. mode: VirtualPrinterMode;
  5981. model: string | null;
  5982. model_name: string | null;
  5983. access_code_set: boolean;
  5984. serial: string;
  5985. target_printer_id: number | null;
  5986. auto_dispatch: boolean;
  5987. queue_force_color_match: boolean;
  5988. tailscale_disabled: boolean;
  5989. bind_ip: string | null;
  5990. remote_interface_ip: string | null;
  5991. position: number;
  5992. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  5993. }
  5994. export interface VirtualPrinterListResponse {
  5995. printers: VirtualPrinterConfig[];
  5996. models: Record<string, string>;
  5997. }
  5998. export const multiVirtualPrinterApi = {
  5999. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  6000. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  6001. create: (data: {
  6002. name?: string;
  6003. enabled?: boolean;
  6004. mode?: string;
  6005. model?: string;
  6006. access_code?: string;
  6007. target_printer_id?: number;
  6008. auto_dispatch?: boolean;
  6009. queue_force_color_match?: boolean;
  6010. bind_ip?: string;
  6011. remote_interface_ip?: string;
  6012. }) =>
  6013. request<VirtualPrinterConfig>('/virtual-printers', {
  6014. method: 'POST',
  6015. body: JSON.stringify(data),
  6016. }),
  6017. update: (id: number, data: {
  6018. name?: string;
  6019. enabled?: boolean;
  6020. mode?: string;
  6021. model?: string;
  6022. access_code?: string;
  6023. target_printer_id?: number;
  6024. auto_dispatch?: boolean;
  6025. queue_force_color_match?: boolean;
  6026. tailscale_disabled?: boolean;
  6027. bind_ip?: string;
  6028. remote_interface_ip?: string;
  6029. }) =>
  6030. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  6031. method: 'PUT',
  6032. body: JSON.stringify(data),
  6033. }),
  6034. remove: (id: number) =>
  6035. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  6036. method: 'DELETE',
  6037. }),
  6038. getTailscaleStatus: () =>
  6039. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  6040. getCaCertificate: () =>
  6041. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  6042. diagnose: (id: number) =>
  6043. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  6044. };
  6045. /** The shared CA certificate every virtual printer presents — imported once
  6046. * into the slicer's trust store. Only the public certificate is returned. */
  6047. export interface VPCaCertificate {
  6048. pem: string;
  6049. fingerprint_sha256: string;
  6050. not_valid_after: string;
  6051. }
  6052. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  6053. export interface VPDiagnosticCheck {
  6054. id:
  6055. | 'enabled'
  6056. | 'running'
  6057. | 'bind_interface'
  6058. | 'access_code'
  6059. | 'target_printer'
  6060. | 'port_ftps'
  6061. | 'port_mqtt'
  6062. | 'port_bind'
  6063. | 'certificate';
  6064. status: VPDiagnosticStatus;
  6065. params: Record<string, string | number>;
  6066. }
  6067. export interface VPDiagnosticResult {
  6068. vp_id: number;
  6069. vp_name: string;
  6070. mode: string;
  6071. overall: 'ok' | 'warnings' | 'problems';
  6072. checks: VPDiagnosticCheck[];
  6073. }
  6074. export interface TailscaleStatusResponse {
  6075. available: boolean;
  6076. fqdn: string;
  6077. hostname: string;
  6078. tailnet_name: string;
  6079. tailscale_ips: string[];
  6080. error: string | null;
  6081. }
  6082. // Pending Uploads API
  6083. export const pendingUploadsApi = {
  6084. list: () => request<PendingUpload[]>('/pending-uploads/'),
  6085. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  6086. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  6087. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  6088. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  6089. method: 'POST',
  6090. body: JSON.stringify(data || {}),
  6091. }),
  6092. discard: (id: number) =>
  6093. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  6094. archiveAll: () =>
  6095. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  6096. discardAll: () =>
  6097. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  6098. };
  6099. // Firmware API Types
  6100. export interface AvailableFirmwareVersion {
  6101. version: string;
  6102. file_available: boolean;
  6103. download_url: string | null;
  6104. release_notes: string | null;
  6105. release_time: string | null;
  6106. }
  6107. export interface FirmwareUpdateInfo {
  6108. printer_id: number;
  6109. printer_name: string;
  6110. model: string | null;
  6111. current_version: string | null;
  6112. latest_version: string | null;
  6113. update_available: boolean;
  6114. download_url: string | null;
  6115. release_notes: string | null;
  6116. available_versions: AvailableFirmwareVersion[];
  6117. }
  6118. export interface FirmwareUploadPrepare {
  6119. can_proceed: boolean;
  6120. sd_card_present: boolean;
  6121. sd_card_free_space: number;
  6122. firmware_size: number;
  6123. space_sufficient: boolean;
  6124. update_available: boolean;
  6125. current_version: string | null;
  6126. latest_version: string | null;
  6127. target_version: string | null;
  6128. firmware_filename: string | null;
  6129. errors: string[];
  6130. }
  6131. export interface FirmwareUploadStatus {
  6132. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  6133. progress: number;
  6134. message: string;
  6135. error: string | null;
  6136. firmware_filename: string | null;
  6137. firmware_version: string | null;
  6138. }
  6139. // Firmware API
  6140. export const firmwareApi = {
  6141. checkUpdates: () =>
  6142. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  6143. checkPrinterUpdate: (printerId: number) =>
  6144. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  6145. prepareUpload: (printerId: number, version?: string) =>
  6146. request<FirmwareUploadPrepare>(
  6147. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  6148. ),
  6149. startUpload: (printerId: number, version?: string) =>
  6150. request<{ started: boolean; message: string }>(
  6151. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  6152. { method: 'POST' },
  6153. ),
  6154. getUploadStatus: (printerId: number) =>
  6155. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  6156. };
  6157. // Support types
  6158. export interface DebugLoggingState {
  6159. enabled: boolean;
  6160. enabled_at: string | null;
  6161. duration_seconds: number | null;
  6162. }
  6163. export interface LogEntry {
  6164. timestamp: string;
  6165. level: string;
  6166. logger_name: string;
  6167. message: string;
  6168. }
  6169. export interface LogsResponse {
  6170. entries: LogEntry[];
  6171. total_in_file: number;
  6172. filtered_count: number;
  6173. }
  6174. // Support API
  6175. export const supportApi = {
  6176. getDebugLoggingState: () =>
  6177. request<DebugLoggingState>('/support/debug-logging'),
  6178. setDebugLogging: (enabled: boolean) =>
  6179. request<DebugLoggingState>('/support/debug-logging', {
  6180. method: 'POST',
  6181. body: JSON.stringify({ enabled }),
  6182. }),
  6183. downloadSupportBundle: async () => {
  6184. const headers: Record<string, string> = {};
  6185. if (authToken) {
  6186. headers['Authorization'] = `Bearer ${authToken}`;
  6187. }
  6188. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  6189. if (!response.ok) {
  6190. const error = await response.json().catch(() => ({}));
  6191. throw new Error(error.detail || `HTTP ${response.status}`);
  6192. }
  6193. // Get filename from Content-Disposition header or use default
  6194. const disposition = response.headers.get('Content-Disposition');
  6195. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  6196. // Download the blob
  6197. const blob = await response.blob();
  6198. const url = window.URL.createObjectURL(blob);
  6199. const a = document.createElement('a');
  6200. a.href = url;
  6201. a.download = filename;
  6202. document.body.appendChild(a);
  6203. a.click();
  6204. document.body.removeChild(a);
  6205. window.URL.revokeObjectURL(url);
  6206. },
  6207. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  6208. const searchParams = new URLSearchParams();
  6209. if (params?.limit) searchParams.set('limit', params.limit.toString());
  6210. if (params?.level) searchParams.set('level', params.level);
  6211. if (params?.search) searchParams.set('search', params.search);
  6212. const query = searchParams.toString();
  6213. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  6214. },
  6215. clearLogs: () =>
  6216. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  6217. };
  6218. // SpoolBuddy types
  6219. export interface SpoolBuddyDevice {
  6220. id: number;
  6221. device_id: string;
  6222. hostname: string;
  6223. ip_address: string;
  6224. backend_url?: string | null;
  6225. firmware_version: string | null;
  6226. has_nfc: boolean;
  6227. has_scale: boolean;
  6228. tare_offset: number;
  6229. calibration_factor: number;
  6230. nfc_reader_type: string | null;
  6231. nfc_connection: string | null;
  6232. display_brightness: number;
  6233. display_blank_timeout: number;
  6234. has_backlight: boolean;
  6235. last_calibrated_at: string | null;
  6236. last_seen: string | null;
  6237. pending_command: string | null;
  6238. nfc_ok: boolean;
  6239. scale_ok: boolean;
  6240. uptime_s: number;
  6241. update_status: string | null;
  6242. update_message: string | null;
  6243. system_stats: {
  6244. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  6245. cpu_temp_c?: number;
  6246. cpu_count?: number;
  6247. load_avg?: number[];
  6248. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  6249. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  6250. system_uptime_s?: number;
  6251. } | null;
  6252. online: boolean;
  6253. }
  6254. export interface DaemonUpdateCheck {
  6255. current_version: string;
  6256. latest_version: string | null;
  6257. update_available: boolean;
  6258. }
  6259. // SpoolBuddy API
  6260. export const spoolbuddyApi = {
  6261. getDevices: () =>
  6262. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  6263. deleteDevice: (deviceId: string) =>
  6264. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  6265. method: 'DELETE',
  6266. }),
  6267. tare: (deviceId: string) =>
  6268. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  6269. method: 'POST',
  6270. body: '{}',
  6271. }),
  6272. getCalibration: (deviceId: string) =>
  6273. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration`),
  6274. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  6275. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  6276. method: 'POST',
  6277. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  6278. }),
  6279. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  6280. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  6281. method: 'POST',
  6282. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  6283. }),
  6284. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  6285. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  6286. method: 'PUT',
  6287. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  6288. }),
  6289. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  6290. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  6291. method: 'POST',
  6292. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  6293. }),
  6294. checkDaemonUpdate: (deviceId: string) =>
  6295. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  6296. triggerUpdate: (deviceId: string) =>
  6297. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  6298. method: 'POST',
  6299. body: '{}',
  6300. }),
  6301. getSSHPublicKey: () =>
  6302. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  6303. writeTag: (deviceId: string, spoolId: number) =>
  6304. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  6305. method: 'POST',
  6306. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  6307. }),
  6308. cancelWrite: (deviceId: string) =>
  6309. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  6310. method: 'POST',
  6311. body: '{}',
  6312. }),
  6313. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  6314. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  6315. method: 'POST',
  6316. body: JSON.stringify({ command }),
  6317. }),
  6318. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  6319. request<{ status: string; diagnostic: string; message: string }>(
  6320. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  6321. { method: 'POST', body: '{}' }
  6322. ),
  6323. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  6324. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  6325. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  6326. { method: 'GET' }
  6327. ),
  6328. };
  6329. export interface BugReportRequest {
  6330. description: string;
  6331. email?: string;
  6332. screenshot_base64?: string;
  6333. include_support_info?: boolean;
  6334. debug_logs?: string;
  6335. }
  6336. export interface BugReportResponse {
  6337. success: boolean;
  6338. message: string;
  6339. issue_url?: string;
  6340. issue_number?: number;
  6341. }
  6342. export const bugReportApi = {
  6343. submit: (data: BugReportRequest) =>
  6344. request<BugReportResponse>('/bug-report/submit', {
  6345. method: 'POST',
  6346. body: JSON.stringify(data),
  6347. }),
  6348. startLogging: () =>
  6349. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  6350. method: 'POST',
  6351. }),
  6352. stopLogging: (wasDebug: boolean) =>
  6353. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  6354. method: 'POST',
  6355. }),
  6356. };