client.ts 258 KB

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