client.ts 239 KB

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