client.ts 338 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface Printer {
  395. id: number;
  396. name: string;
  397. serial_number: string;
  398. ip_address: string;
  399. // Optional because the backend only returns access_code when the caller has
  400. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  401. // API keys receive a Printer without this field.
  402. access_code?: string;
  403. model: string | null;
  404. location: string | null; // Group/location name
  405. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  406. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  407. // flow type is a real choice. Derived from the model, not the nozzle count —
  408. // only the A-series has a single variant.
  409. supports_nozzle_flow_type: boolean;
  410. is_active: boolean;
  411. auto_archive: boolean;
  412. external_camera_url: string | null;
  413. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  414. external_camera_enabled: boolean;
  415. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  416. camera_rotation: number; // 0, 90, 180, 270 degrees
  417. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  418. plate_detection_enabled: boolean; // Check plate before print
  419. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  420. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  421. created_at: string;
  422. updated_at: string;
  423. }
  424. export interface HMSError {
  425. code: string;
  426. attr: number; // Attribute value for constructing wiki URL
  427. module: number;
  428. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  429. // 3 notification, 0 invalid (#2728).
  430. severity: number;
  431. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  432. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  433. // Canonical hex identifier the firmware matches against — 8 chars for
  434. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  435. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  436. // identifier into the silent-rejection short code (#1830).
  437. full_code?: string;
  438. // The backend's catalogue sentence for this fault (#2926), from the table
  439. // generated out of Bambu Studio for this printer model (#2728). English only.
  440. // Null when Bambu publishes no text for the code. The frontend has no table of
  441. // its own: this field decides both the text and whether the fault counts.
  442. description?: string | null;
  443. }
  444. export interface HMSActionBody {
  445. print_error: string; // HMS error code (e.g. "05000070")
  446. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  447. job_id: string | null; // Optional job ID for context (if applicable)
  448. }
  449. export interface AMSTray {
  450. id: number;
  451. tray_color: string | null;
  452. tray_type: string | null;
  453. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  454. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  455. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  456. remain: number;
  457. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  458. cali_idx: number | null; // Calibration index for K-profile lookup
  459. tag_uid: string | null; // RFID tag UID (any tag)
  460. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  461. nozzle_temp_min: number | null; // Min nozzle temperature
  462. nozzle_temp_max: number | null; // Max nozzle temperature
  463. drying_temp: number | null; // RFID-recommended drying temp
  464. drying_time: number | null; // RFID-recommended drying time (hours)
  465. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  466. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  467. }
  468. export interface AMSUnit {
  469. id: number;
  470. humidity: number | null;
  471. temp: number | null;
  472. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  473. tray: AMSTray[];
  474. serial_number: string; // AMS unit serial number (from MQTT sn field)
  475. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  476. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  477. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  478. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  479. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  480. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  481. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  482. dry_filament: string | null; // Active-cycle filament name we sent
  483. module_type: string; // "ams", "ams_f1", "n3f", "n3s"
  484. }
  485. export interface ScheduledDrying {
  486. id: number;
  487. printer_id: number;
  488. ams_id: number;
  489. temp: number;
  490. duration_hours: number;
  491. filament: string;
  492. rotate_tray: boolean;
  493. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  494. status: string;
  495. waiting_reason: string | null;
  496. error_message: string | null;
  497. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  498. // rows that failed before codes existed, which show error_message instead.
  499. error_code?: string | null;
  500. created_at: string;
  501. started_at: string | null;
  502. completed_at: string | null;
  503. }
  504. export interface NozzleInfo {
  505. // Two vocabularies live in this field, by printer generation. Legacy
  506. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  507. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  508. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  509. // latter and treats anything else as "unknown", which is what makes the
  510. // material spelling harmless here.
  511. nozzle_type: string;
  512. nozzle_diameter: string; // e.g., "0.4"
  513. }
  514. export interface NozzleRackSlot {
  515. id: number;
  516. nozzle_type: string;
  517. nozzle_diameter: string;
  518. wear: number | null;
  519. stat: number | null; // Nozzle status (e.g. mounted/docked)
  520. max_temp: number;
  521. serial_number: string;
  522. filament_color: string; // RGBA hex ("00000000" = no filament)
  523. filament_id: string;
  524. filament_type: string; // Material type (e.g. "PLA", "PETG")
  525. }
  526. export interface PrintOptions {
  527. // Core AI detectors
  528. spaghetti_detector: boolean;
  529. print_halt: boolean;
  530. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  531. first_layer_inspector: boolean;
  532. printing_monitor: boolean;
  533. buildplate_marker_detector: boolean;
  534. allow_skip_parts: boolean;
  535. // Additional AI detectors (decoded from cfg bitmask)
  536. nozzle_clumping_detector: boolean;
  537. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  538. pileup_detector: boolean;
  539. pileup_sensitivity: string; // "low", "medium", "high"
  540. airprint_detector: boolean;
  541. airprint_sensitivity: string; // "low", "medium", "high"
  542. auto_recovery_step_loss: boolean;
  543. filament_tangle_detect: boolean;
  544. }
  545. export interface FilaSwitchState {
  546. installed: boolean;
  547. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  548. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  549. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  550. // 0xE when unset. Neither array says which inlet is currently routed to which
  551. // outlet — that pairing is not reported. For per-AMS side information use
  552. // PrinterStatus.ams_switch_inlet instead.
  553. in_slots: number[];
  554. out_extruders: number[];
  555. stat: number;
  556. info: number;
  557. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  558. // the switch cannot route a load anywhere and the printer has to be set up
  559. // first ("Manual AMS Setup" on its screen).
  560. ready: boolean;
  561. }
  562. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  563. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  564. // tray_now cannot answer this — it is one value for the whole printer, so on a
  565. // dual-nozzle machine it names only one of the two loaded hotends.
  566. export interface ExtruderSlot {
  567. ams_id: number | null;
  568. slot_id: number | null;
  569. has_filament: boolean;
  570. }
  571. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  572. export type FtsInlet = 'A' | 'B';
  573. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  574. export interface UsbCamera {
  575. device: string;
  576. name: string;
  577. capabilities: string[];
  578. driver?: string;
  579. formats?: string[];
  580. }
  581. export interface PrinterStatus {
  582. id: number;
  583. name: string;
  584. connected: boolean;
  585. state: string | null;
  586. current_print: string | null;
  587. subtask_name: string | null;
  588. current_archive_id: number | null;
  589. current_plate_id: number | null;
  590. gcode_file: string | null;
  591. progress: number | null;
  592. remaining_time: number | null;
  593. layer_num: number | null;
  594. total_layers: number | null;
  595. temperatures: {
  596. bed?: number;
  597. bed_target?: number;
  598. bed_heating?: boolean; // Actual heater state from MQTT
  599. nozzle?: number;
  600. nozzle_target?: number;
  601. nozzle_heating?: boolean; // Actual heater state from MQTT
  602. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  603. nozzle_2_target?: number;
  604. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  605. chamber?: number;
  606. chamber_target?: number;
  607. chamber_heating?: boolean; // Actual heater state from MQTT
  608. } | null;
  609. cover_url: string | null;
  610. hms_errors: HMSError[];
  611. // Live updates send null when no AMS is attached; the REST status sends [].
  612. ams: AMSUnit[] | null;
  613. ams_exists: boolean;
  614. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  615. store_to_sdcard: boolean; // Store sent files on SD card
  616. timelapse: boolean; // Timelapse recording active
  617. ipcam: boolean; // Live view enabled
  618. wifi_signal: number | null; // WiFi signal strength in dBm
  619. wired_network: boolean; // Ethernet connection detected
  620. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  621. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  622. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  623. // utils/amsHelpers rather than indexing it directly.
  624. nozzles: NozzleInfo[];
  625. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  626. print_options: PrintOptions | null; // AI detection and print options
  627. // Calibration stage tracking
  628. stg_cur: number; // Current stage number (-1 = not calibrating)
  629. stg_cur_name: string | null; // Human-readable current stage name
  630. stg: number[]; // List of stage numbers in calibration sequence
  631. // Air conditioning mode (0=cooling, 1=heating)
  632. airduct_mode: number;
  633. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  634. speed_level: number;
  635. // Chamber light on/off
  636. chamber_light: boolean;
  637. // Active extruder for dual nozzle (0=right, 1=left)
  638. active_extruder: number;
  639. // AMS mapping - which AMS is connected to which nozzle
  640. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  641. ams_mapping: number[];
  642. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  643. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  644. // Note: JSON keys are always strings
  645. ams_extruder_map: Record<string, number>;
  646. // Filament Track Switch accessory — null when not installed. When present,
  647. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  648. // either extruder, so per-extruder slot filtering must be skipped.
  649. fila_switch: FilaSwitchState | null;
  650. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  651. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  652. // an entry here reaches BOTH nozzles through the switch, which is why it has
  653. // no ams_extruder_map entry and must not be badged left or right.
  654. ams_switch_inlet: Record<string, FtsInlet>;
  655. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  656. // Empty on printers that don't report it (everything but the H2/X2 series).
  657. extruder_slots: Record<string, ExtruderSlot>;
  658. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  659. tray_now: number;
  660. // The trays this print has drawn from, in order: [global tray ID, layer of the
  661. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  662. // switched to (AMS Filament Backup). Reset at the start of each print.
  663. tray_change_log?: [number, number][];
  664. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  665. // Global tray IDs (ams_id*4+slot, 128-135 = AMS-HT, 254 = external), matching
  666. // the same numbering as tray_now so the AMS graphic can highlight them.
  667. // expected_tray = the slot the firmware now expects filament in (null = idle,
  668. // not paused, or unresolvable → "check the printer").
  669. // previous_tray = the slot that ran out (null = unknown).
  670. expected_tray: number | null;
  671. previous_tray: number | null;
  672. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  673. ams_status_main: number;
  674. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  675. ams_status_sub: number;
  676. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  677. mc_print_sub_stage: number;
  678. // Timestamp of last AMS data update (for RFID refresh detection)
  679. last_ams_update: number;
  680. // Number of printable objects in current print (for skip objects feature)
  681. printable_objects_count: number;
  682. // The next pause the slicer put into the running print (#2984). minutes is
  683. // null while the printer reports no time left yet.
  684. next_pause?: { layer: number; minutes: number | null } | null;
  685. // Fan speeds (0-100 percentage, null if not available for this model)
  686. cooling_fan_speed: number | null; // Part cooling fan
  687. big_fan1_speed: number | null; // Auxiliary fan
  688. big_fan2_speed: number | null; // Chamber/exhaust fan
  689. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  690. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  691. // null = not installed / not reported by this model.
  692. left_aux_fan_speed: number | null;
  693. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  694. exhaust_fan_present: boolean;
  695. firmware_version: string | null; // Firmware version from MQTT
  696. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  697. developer_mode: boolean | null;
  698. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  699. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  700. ams_filament_backup: boolean | null;
  701. // Queue: printer is awaiting user ack that the build plate was cleared after a
  702. // finished/failed print. Persisted across restarts (#961).
  703. awaiting_plate_clear: boolean;
  704. // AMS drying support
  705. supports_drying: boolean;
  706. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  707. drying_screen_only?: boolean;
  708. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  709. supports_chamber_heater?: boolean;
  710. }
  711. export interface PrinterCreate {
  712. name: string;
  713. serial_number: string;
  714. ip_address: string;
  715. access_code: string;
  716. model?: string;
  717. location?: string | null;
  718. auto_archive?: boolean;
  719. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  720. // scheduler, metrics and the print picker on this; toggling via PATCH
  721. // /printers/{id} disconnects or reconnects MQTT accordingly.
  722. is_active?: boolean;
  723. external_camera_url?: string | null;
  724. external_camera_type?: string | null;
  725. external_camera_enabled?: boolean;
  726. external_camera_snapshot_url?: string | null;
  727. camera_rotation?: number;
  728. camera_light_auto?: boolean;
  729. plate_detection_enabled?: boolean;
  730. plate_detection_roi?: PlateDetectionROI;
  731. wear_cost_per_hour?: number | null;
  732. }
  733. // Plate Detection
  734. export interface PlateDetectionROI {
  735. x: number; // X start % (0.0-1.0)
  736. y: number; // Y start % (0.0-1.0)
  737. w: number; // Width % (0.0-1.0)
  738. h: number; // Height % (0.0-1.0)
  739. }
  740. export interface PlateDetectionResult {
  741. is_empty: boolean;
  742. confidence: number;
  743. difference_percent: number;
  744. message: string;
  745. has_debug_image: boolean;
  746. debug_image_url?: string;
  747. needs_calibration: boolean;
  748. light_warning?: boolean;
  749. reference_count?: number;
  750. max_references?: number;
  751. roi?: PlateDetectionROI;
  752. }
  753. export interface PlateDetectionStatus {
  754. available: boolean;
  755. calibrated: boolean;
  756. reference_count: number;
  757. max_references: number;
  758. message: string;
  759. }
  760. export interface CalibrationResult {
  761. success: boolean;
  762. message: string;
  763. }
  764. export interface PlateReference {
  765. index: number;
  766. label: string;
  767. timestamp: string;
  768. has_image: boolean;
  769. thumbnail_url: string;
  770. }
  771. // Archive types
  772. export interface ArchiveDuplicate {
  773. id: number;
  774. print_name: string | null;
  775. created_at: string;
  776. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  777. }
  778. export interface ArchivePrinterMediaFile {
  779. name: string;
  780. path: string;
  781. size: number;
  782. mtime: string | null;
  783. kind: 'timelapse' | 'ipcam';
  784. }
  785. export interface ArchivePrinterMedia {
  786. archive_id: number;
  787. printer_id: number | null;
  788. local_timelapse: { name: string; size: number } | null;
  789. remote_files: ArchivePrinterMediaFile[];
  790. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  791. }
  792. /** A timelapse editor re-encode, run in the background. */
  793. export interface TimelapseJob {
  794. status: 'running' | 'completed' | 'failed' | 'cancelled';
  795. /** Share done, 0 to 1; null before ffmpeg's first report. */
  796. progress: number | null;
  797. output_path: string | null;
  798. message: string | null;
  799. error: string | null;
  800. }
  801. /** How a post-print outcome verdict reached the archive (#1898). */
  802. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  803. export interface Archive {
  804. id: number;
  805. printer_id: number | null;
  806. project_id: number | null;
  807. project_name: string | null;
  808. filename: string;
  809. file_path: string;
  810. file_size: number;
  811. content_hash: string | null;
  812. thumbnail_path: string | null;
  813. timelapse_path: string | null;
  814. source_3mf_path: string | null;
  815. f3d_path: string | null;
  816. duplicates: ArchiveDuplicate[] | null;
  817. duplicate_count: number;
  818. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  819. original_archive_id: number | null; // ID of the first/original archive
  820. object_count: number | null;
  821. print_name: string | null;
  822. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  823. print_time_seconds: number | null;
  824. actual_time_seconds: number | null; // Computed from started_at/completed_at
  825. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  826. filament_used_grams: number | null;
  827. filament_type: string | null;
  828. filament_color: string | null;
  829. layer_height: number | null;
  830. total_layers: number | null;
  831. nozzle_diameter: number | null;
  832. bed_temperature: number | null;
  833. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  834. nozzle_temperature: number | null;
  835. sliced_for_model: string | null; // Printer model this file was sliced for
  836. status: string;
  837. started_at: string | null;
  838. completed_at: string | null;
  839. extra_data: Record<string, unknown> | null;
  840. makerworld_url: string | null;
  841. designer: string | null;
  842. external_url: string | null;
  843. is_favorite: boolean;
  844. tags: string | null;
  845. notes: string | null;
  846. cost: number | null;
  847. photos: string[] | null;
  848. failure_reason: string | null;
  849. // Post-print outcome confirmation (#1898)
  850. user_verdict: 'good' | 'reject' | null;
  851. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  852. // handler (#3046) and is labelled here so it reads correctly once that lands.
  853. user_verdict_source: VerdictSource | null;
  854. user_verdict_at: string | null;
  855. confirm_requested: boolean;
  856. quantity: number;
  857. energy_kwh: number | null;
  858. energy_cost: number | null;
  859. wear_cost: number | null; // Printer wear (#694)
  860. created_at: string;
  861. // User tracking (Issue #206)
  862. created_by_id: number | null;
  863. created_by_username: string | null;
  864. // Per-archive run aggregates from PrintLogEntry (#1378)
  865. run_count: number;
  866. last_run_at: string | null;
  867. total_filament_actual_grams: number | null;
  868. successful_run_count: number;
  869. failed_run_count: number;
  870. }
  871. export interface ArchiveSlim {
  872. printer_id: number | null;
  873. print_name: string | null;
  874. print_time_seconds: number | null;
  875. actual_time_seconds: number | null;
  876. filament_used_grams: number | null;
  877. filament_type: string | null;
  878. filament_color: string | null;
  879. status: string;
  880. started_at: string | null;
  881. completed_at: string | null;
  882. cost: number | null;
  883. energy_kwh: number | null;
  884. energy_cost: number | null;
  885. wear_cost: number | null; // Printer wear (#694)
  886. quantity: number;
  887. created_at: string;
  888. }
  889. export interface PrintLogEntry {
  890. id: number;
  891. archive_id: number | null;
  892. print_name: string | null;
  893. printer_name: string | null;
  894. printer_id: number | null;
  895. status: string;
  896. started_at: string | null;
  897. completed_at: string | null;
  898. duration_seconds: number | null;
  899. filament_type: string | null;
  900. filament_color: string | null;
  901. filament_used_grams: number | null;
  902. cost: number | null;
  903. energy_kwh: number | null;
  904. energy_cost: number | null;
  905. wear_cost: number | null; // Printer wear (#694)
  906. failure_reason: string | null;
  907. thumbnail_path: string | null;
  908. created_by_id: number | null;
  909. created_by_username: string | null;
  910. created_at: string;
  911. }
  912. export interface PrintLogResponse {
  913. items: PrintLogEntry[];
  914. total: number;
  915. }
  916. export interface ArchiveStats {
  917. total_prints: number;
  918. successful_prints: number;
  919. failed_prints: number;
  920. cancelled_prints: number;
  921. total_print_time_hours: number;
  922. total_filament_grams: number;
  923. total_cost: number;
  924. prints_by_filament_type: Record<string, number>;
  925. prints_by_printer: Record<string, number>;
  926. // Name each printer id was last recorded under in the print log, so history
  927. // belonging to a deleted printer keeps its label.
  928. printer_names?: Record<string, string>;
  929. average_time_accuracy: number | null;
  930. time_accuracy_by_printer: Record<string, number> | null;
  931. total_energy_kwh: number;
  932. total_energy_cost: number;
  933. total_wear_cost: number; // Printer wear (#694)
  934. // True when a date-filtered total-consumption query is running on incomplete
  935. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  936. // a baseline). UI should explain why the number may undercount.
  937. energy_data_warming_up?: boolean;
  938. }
  939. export interface TagInfo {
  940. name: string;
  941. count: number;
  942. }
  943. export interface FailureAnalysis {
  944. period_days: number;
  945. total_prints: number;
  946. failed_prints: number;
  947. failure_rate: number;
  948. // Quality dimension (#1898): completed prints the user rejected. Optional
  949. // so a frontend build against an older backend degrades gracefully.
  950. rejected_prints?: number;
  951. yield_rate?: number;
  952. rejects_by_reason?: Record<string, number>;
  953. failures_by_reason: Record<string, number>;
  954. failures_by_filament: Record<string, number>;
  955. failures_by_printer: Record<string, number>;
  956. failures_by_hour: Record<number, number>;
  957. recent_failures: Array<{
  958. id: number;
  959. print_name: string;
  960. failure_reason: string | null;
  961. filament_type: string | null;
  962. printer_id: number | null;
  963. created_at: string | null;
  964. }>;
  965. trend: Array<{
  966. week_start: string;
  967. total_prints: number;
  968. failed_prints: number;
  969. failure_rate: number;
  970. }>;
  971. }
  972. /**
  973. * Send the browser's zone with calendar dates: the server reads a date as a
  974. * day in it, else in its own TZ, which shifted every day for a browser away
  975. * from the server (DB-C12). Only when a date is set.
  976. */
  977. function addDayZone(params: URLSearchParams): void {
  978. if (!params.has('date_from') && !params.has('date_to')) return;
  979. try {
  980. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  981. if (zone) params.set('tz', zone);
  982. } catch {
  983. // No Intl zone: the server's TZ applies.
  984. }
  985. }
  986. export interface BulkUploadResult {
  987. uploaded: number;
  988. failed: number;
  989. /** `index` is the file's position in the request. */
  990. results: Array<{ index: number; filename: string; id: number; status: string }>;
  991. errors: Array<{ index: number; filename: string; error: string }>;
  992. }
  993. // Archive Comparison types
  994. export interface ComparisonArchiveInfo {
  995. id: number;
  996. print_name: string;
  997. status: string;
  998. created_at: string | null;
  999. printer_id: number | null;
  1000. project_name: string | null;
  1001. }
  1002. export interface ComparisonField {
  1003. field: string;
  1004. label: string;
  1005. unit: string | null;
  1006. values: (string | number | null)[];
  1007. raw_values: (string | number | null)[];
  1008. has_difference: boolean;
  1009. }
  1010. export interface SuccessCorrelationInsight {
  1011. field: string;
  1012. label: string;
  1013. insight: string;
  1014. success_avg?: number;
  1015. failed_avg?: number;
  1016. success_values?: string[];
  1017. failed_values?: string[];
  1018. }
  1019. export interface SuccessCorrelation {
  1020. has_both_outcomes: boolean;
  1021. message?: string;
  1022. successful_count?: number;
  1023. failed_count?: number;
  1024. insights?: SuccessCorrelationInsight[];
  1025. }
  1026. export interface ArchiveComparison {
  1027. archives: ComparisonArchiveInfo[];
  1028. comparison: ComparisonField[];
  1029. differences: ComparisonField[];
  1030. success_correlation: SuccessCorrelation;
  1031. }
  1032. // Project types
  1033. export interface ProjectStats {
  1034. total_archives: number;
  1035. total_items: number; // Sum of quantities (total items printed)
  1036. completed_prints: number; // Sum of quantities for completed prints (parts)
  1037. failed_prints: number;
  1038. queued_prints: number;
  1039. in_progress_prints: number;
  1040. total_print_time_hours: number;
  1041. total_filament_grams: number;
  1042. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1043. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1044. estimated_cost: number;
  1045. total_energy_kwh: number;
  1046. total_energy_cost: number;
  1047. total_wear_cost: number; // Printer wear (#694)
  1048. remaining_prints: number | null; // Remaining plates
  1049. remaining_parts: number | null; // Remaining parts
  1050. bom_total_items: number;
  1051. bom_completed_items: number;
  1052. bom_cost: number;
  1053. }
  1054. // A sub-project as listed on its parent's page. The figures cover the child's
  1055. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1056. // parent's own prints (#1264).
  1057. export interface ProjectChildPreview {
  1058. id: number;
  1059. name: string;
  1060. color: string | null;
  1061. status: string;
  1062. progress_percent: number | null;
  1063. descendant_count: number;
  1064. total_archives: number;
  1065. completed_prints: number;
  1066. total_print_time_hours: number;
  1067. total_filament_grams: number;
  1068. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1069. }
  1070. export interface Project {
  1071. id: number;
  1072. name: string;
  1073. description: string | null;
  1074. color: string | null;
  1075. status: string; // active, completed, archived
  1076. target_count: number | null; // Target number of plates/print jobs
  1077. target_parts_count: number | null; // Target number of parts/objects
  1078. target_sets: number | null; // Copies-per-file target (#1897)
  1079. notes: string | null;
  1080. attachments: ProjectAttachment[] | null;
  1081. tags: string | null;
  1082. due_date: string | null;
  1083. priority: string; // low, normal, high, urgent
  1084. budget: number | null;
  1085. is_template: boolean;
  1086. template_source_id: number | null;
  1087. parent_id: number | null;
  1088. parent_name: string | null;
  1089. children: ProjectChildPreview[];
  1090. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1091. created_at: string;
  1092. updated_at: string;
  1093. stats?: ProjectStats;
  1094. // This project's numbers combined with every sub-project's. Null when there
  1095. // are none, since it would only repeat `stats` (#1264).
  1096. rollup_stats?: ProjectStats | null;
  1097. url: string | null; // External link rendered next to project name on the card (#1155)
  1098. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1099. }
  1100. export interface ProjectAttachment {
  1101. filename: string;
  1102. original_name: string;
  1103. size: number;
  1104. uploaded_at: string;
  1105. }
  1106. // Completed-run count for one library file inside a project (#1897)
  1107. export interface ProjectFileProgress {
  1108. file_id: number;
  1109. completed_count: number;
  1110. }
  1111. export interface ArchivePreview {
  1112. id: number;
  1113. print_name: string | null;
  1114. thumbnail_path: string | null;
  1115. status: string;
  1116. filament_type: string | null;
  1117. filament_color: string | null;
  1118. }
  1119. export interface ProjectListItem {
  1120. id: number;
  1121. name: string;
  1122. description: string | null;
  1123. color: string | null;
  1124. status: string;
  1125. target_count: number | null; // Target number of plates/print jobs
  1126. target_parts_count: number | null; // Target number of parts/objects
  1127. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1128. budget: number | null;
  1129. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1130. due_date: string | null; // #2536
  1131. priority: string; // #2536
  1132. created_at: string;
  1133. archive_count: number; // Number of print jobs (plates)
  1134. total_items: number; // Sum of quantities (total items printed, including failed)
  1135. completed_count: number; // Sum of quantities for completed prints only (parts)
  1136. failed_count: number; // Sum of quantities for failed prints
  1137. queue_count: number;
  1138. progress_percent: number | null; // Plates progress
  1139. parent_id: number | null; // #1264 — set when this is a sub-project
  1140. child_count: number; // #1264 — direct sub-projects only
  1141. archives: ArchivePreview[];
  1142. url: string | null; // #1155
  1143. cover_image_filename: string | null; // #1155
  1144. }
  1145. export interface ProjectCreate {
  1146. name: string;
  1147. description?: string;
  1148. color?: string;
  1149. target_count?: number;
  1150. target_parts_count?: number;
  1151. target_sets?: number;
  1152. notes?: string;
  1153. tags?: string;
  1154. due_date?: string;
  1155. priority?: string;
  1156. budget?: number | null;
  1157. parent_id?: number;
  1158. url?: string | null; // #1155
  1159. }
  1160. export interface ProjectUpdate {
  1161. name?: string;
  1162. description?: string;
  1163. color?: string;
  1164. status?: string;
  1165. target_count?: number;
  1166. target_parts_count?: number;
  1167. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1168. notes?: string;
  1169. tags?: string | null; // #2536 — explicit null clears the tags
  1170. due_date?: string | null; // #2536 — explicit null clears the due date
  1171. priority?: string;
  1172. budget?: number | null;
  1173. parent_id?: number;
  1174. url?: string | null; // #1155 — explicit null clears the URL
  1175. }
  1176. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1177. export interface BOMItem {
  1178. id: number;
  1179. project_id: number;
  1180. name: string;
  1181. quantity_needed: number;
  1182. quantity_acquired: number;
  1183. unit_price: number | null;
  1184. sourcing_url: string | null;
  1185. archive_id: number | null;
  1186. archive_name: string | null;
  1187. stl_filename: string | null;
  1188. remarks: string | null;
  1189. sort_order: number;
  1190. is_complete: boolean;
  1191. created_at: string;
  1192. updated_at: string;
  1193. }
  1194. export interface BOMItemCreate {
  1195. name: string;
  1196. quantity_needed?: number;
  1197. unit_price?: number;
  1198. sourcing_url?: string;
  1199. archive_id?: number;
  1200. stl_filename?: string;
  1201. remarks?: string;
  1202. }
  1203. export interface BOMItemUpdate {
  1204. name?: string;
  1205. quantity_needed?: number;
  1206. quantity_acquired?: number;
  1207. unit_price?: number;
  1208. sourcing_url?: string;
  1209. archive_id?: number;
  1210. stl_filename?: string;
  1211. remarks?: string;
  1212. }
  1213. // Project Export/Import Types
  1214. export interface BOMItemExport {
  1215. name: string;
  1216. quantity_needed: number;
  1217. quantity_acquired: number;
  1218. unit_price: number | null;
  1219. sourcing_url: string | null;
  1220. stl_filename: string | null;
  1221. remarks: string | null;
  1222. }
  1223. export interface LinkedFolderExport {
  1224. name: string;
  1225. }
  1226. export interface ProjectExport {
  1227. name: string;
  1228. description: string | null;
  1229. color: string | null;
  1230. status: string;
  1231. target_count: number | null;
  1232. target_parts_count: number | null;
  1233. target_sets: number | null; // #1897
  1234. notes: string | null;
  1235. tags: string | null;
  1236. due_date: string | null;
  1237. priority: string;
  1238. budget: number | null;
  1239. bom_items: BOMItemExport[];
  1240. linked_folders: LinkedFolderExport[];
  1241. }
  1242. export interface ProjectImport {
  1243. name: string;
  1244. description?: string;
  1245. color?: string;
  1246. status?: string;
  1247. target_count?: number;
  1248. target_parts_count?: number;
  1249. target_sets?: number; // #1897
  1250. notes?: string;
  1251. tags?: string;
  1252. due_date?: string;
  1253. priority?: string;
  1254. budget?: number | null;
  1255. bom_items?: BOMItemExport[];
  1256. linked_folders?: LinkedFolderExport[];
  1257. }
  1258. // Timeline Types
  1259. export interface TimelineEvent {
  1260. event_type: string;
  1261. timestamp: string;
  1262. title: string;
  1263. description: string | null;
  1264. metadata: Record<string, unknown> | null;
  1265. }
  1266. // API Key types
  1267. export interface APIKey {
  1268. id: number;
  1269. name: string;
  1270. key_prefix: string;
  1271. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1272. can_queue: boolean;
  1273. can_control_printer: boolean;
  1274. can_read_status: boolean;
  1275. can_manage_library: boolean;
  1276. can_manage_inventory: boolean;
  1277. can_manage_maintenance: boolean;
  1278. can_manage_archives: boolean;
  1279. can_manage_projects: boolean;
  1280. can_access_cloud: boolean;
  1281. can_update_energy_cost: boolean;
  1282. can_send_notifications: boolean;
  1283. printer_ids: number[] | null;
  1284. enabled: boolean;
  1285. last_used: string | null;
  1286. created_at: string;
  1287. expires_at: string | null;
  1288. }
  1289. export interface APIKeyCreate {
  1290. name: string;
  1291. can_queue?: boolean;
  1292. can_control_printer?: boolean;
  1293. can_read_status?: boolean;
  1294. can_manage_library?: boolean;
  1295. can_manage_inventory?: boolean;
  1296. can_manage_maintenance?: boolean;
  1297. can_manage_archives?: boolean;
  1298. can_manage_projects?: boolean;
  1299. can_access_cloud?: boolean;
  1300. can_update_energy_cost?: boolean;
  1301. can_send_notifications?: boolean;
  1302. printer_ids?: number[] | null;
  1303. expires_at?: string | null;
  1304. }
  1305. export interface APIKeyCreateResponse extends APIKey {
  1306. key: string; // Full key, only shown on creation
  1307. }
  1308. /**
  1309. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1310. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1311. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1312. */
  1313. export type CalibrationMode = 'off' | 'on' | 'auto';
  1314. // Settings types
  1315. export interface AppSettings {
  1316. auto_archive: boolean;
  1317. save_thumbnails: boolean;
  1318. capture_finish_photo: boolean;
  1319. finish_photo_restore_plate: boolean;
  1320. default_filament_cost: number;
  1321. currency: string;
  1322. energy_cost_per_kwh: number;
  1323. energy_tracking_mode: 'print' | 'total';
  1324. // Where the electricity price comes from (#1251). With 'homeassistant',
  1325. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1326. energy_price_source: 'fixed' | 'homeassistant';
  1327. energy_price_ha_entity: string;
  1328. check_updates: boolean;
  1329. check_printer_firmware: boolean;
  1330. include_beta_updates: boolean;
  1331. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1332. announcements_enabled?: boolean;
  1333. announcements_all_users?: boolean;
  1334. // #1589: false hides the local username/password form on the login page;
  1335. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1336. // true so the env-var recovery path is visible to the SPA.
  1337. local_login_enabled: boolean;
  1338. language: string;
  1339. notification_language: string;
  1340. // AMS threshold settings
  1341. ams_humidity_good: number; // <= this is green
  1342. ams_humidity_fair: number; // <= this is orange, > is red
  1343. ams_temp_good: number; // <= this is green/blue
  1344. ams_temp_fair: number; // <= this is orange, > is red
  1345. // Separate from the display band (#2905). null = unset, which the backend
  1346. // resolves to ams_temp_fair so existing installs are unaffected.
  1347. ams_temp_alarm: number | null;
  1348. ams_history_retention_days: number; // days to keep AMS sensor history
  1349. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1350. // Queue auto-drying settings
  1351. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1352. queue_drying_block: boolean; // Block queue until drying completes
  1353. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1354. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1355. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1356. drying_presets: string; // JSON blob of drying presets per filament type
  1357. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1358. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1359. // Scheduled local backup
  1360. local_backup_enabled: boolean;
  1361. local_backup_schedule: string;
  1362. local_backup_time: string;
  1363. local_backup_retention: number;
  1364. local_backup_path: string;
  1365. // Print modal settings
  1366. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1367. // Date/time format settings
  1368. date_format: 'system' | 'us' | 'eu' | 'iso';
  1369. time_format: 'system' | '12h' | '24h';
  1370. // Filament tracking
  1371. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1372. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1373. spoolman_enabled: boolean; // True when the user has switched filament tracking to Spoolman; backend includes this in the /settings/ response even though earlier consumers read it from the dedicated /settings/spoolman endpoint as a string
  1374. auto_add_unknown_rfid: boolean; // When false, the backend skips auto-creating inventory spools for unknown RFID tags and instead broadcasts an unknown_tag event for the confirmation modal
  1375. spoolman_url: string;
  1376. // Default printer
  1377. default_printer_id: number | null;
  1378. pipeline_max_copies: number;
  1379. // Dark mode theme settings
  1380. dark_style: 'classic' | 'glow' | 'vibrant';
  1381. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1382. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1383. // Light mode theme settings
  1384. light_style: 'classic' | 'glow' | 'vibrant';
  1385. light_background: 'neutral' | 'warm' | 'cool';
  1386. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1387. // FTP retry settings
  1388. ftp_retry_enabled: boolean;
  1389. ftp_retry_count: number;
  1390. ftp_retry_delay: number;
  1391. ftp_timeout: number;
  1392. // MQTT relay settings
  1393. mqtt_enabled: boolean;
  1394. mqtt_broker: string;
  1395. mqtt_port: number;
  1396. mqtt_username: string;
  1397. mqtt_password: string;
  1398. mqtt_topic_prefix: string;
  1399. mqtt_use_tls: boolean;
  1400. // External URL for notifications
  1401. external_url: string;
  1402. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1403. docker_compose_dir: string;
  1404. // Home Assistant integration
  1405. ha_enabled: boolean;
  1406. ha_url: string;
  1407. ha_token: string;
  1408. ha_url_from_env: boolean;
  1409. ha_token_from_env: boolean;
  1410. ha_env_managed: boolean;
  1411. // File Manager / Library settings
  1412. library_disk_warning_gb: number;
  1413. // Camera view settings
  1414. camera_view_mode: 'window' | 'embedded';
  1415. // Chamber light while the camera is in use (#1655)
  1416. camera_light_mode: 'off' | 'all' | 'selected';
  1417. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1418. // Preferred slicer (server-side API / sidecar)
  1419. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1420. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1421. // preferred_slicer so existing installs behave identically.
  1422. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1423. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1424. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1425. slice_engine: 'sidecar' | 'browser';
  1426. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1427. use_slicer_api: boolean;
  1428. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1429. orcaslicer_api_url: string;
  1430. bambu_studio_api_url: string;
  1431. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1432. // stalls, not total slicing time — a model that keeps reporting progress
  1433. // runs to completion however long it takes.
  1434. slicer_stall_timeout_minutes: number;
  1435. // Prometheus metrics
  1436. prometheus_enabled: boolean;
  1437. prometheus_token: string;
  1438. // Bed cooled threshold
  1439. bed_cooled_threshold: number;
  1440. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1441. pause_warning_minutes: number;
  1442. // Inventory low stock threshold
  1443. low_stock_threshold: number;
  1444. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1445. session_max_hours: number;
  1446. // User email notifications toggle
  1447. user_notifications_enabled: boolean;
  1448. // Default print options
  1449. default_bed_levelling: CalibrationMode;
  1450. default_flow_cali: CalibrationMode;
  1451. default_vibration_cali: boolean;
  1452. default_layer_inspect: boolean;
  1453. default_timelapse: boolean;
  1454. default_nozzle_offset_cali: CalibrationMode;
  1455. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1456. default_confirm_outcome: boolean;
  1457. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1458. confirm_outcome_external_prints: boolean;
  1459. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1460. confirm_default_good_on_plate_clear: boolean;
  1461. // Staggered batch start defaults
  1462. stagger_group_size: number;
  1463. stagger_interval_minutes: number;
  1464. // Finance budget reset window
  1465. billing_enabled: boolean;
  1466. printer_kill_switch_enabled: boolean;
  1467. finance_budget_reset_day: number;
  1468. finance_budget_reset_timezone: string;
  1469. // Plate-clear confirmation
  1470. require_plate_clear: boolean;
  1471. // Shortest job first scheduling
  1472. queue_shortest_first: boolean;
  1473. // How many printers the queue may upload to at once (#2555). 1 restores the
  1474. // old strictly-serial behaviour, where every printer waited out every other
  1475. // printer's transfer.
  1476. queue_max_concurrent_uploads: number;
  1477. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1478. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1479. // flip the decision per print. Chamber target derives from the loaded AMS
  1480. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1481. // across loaded slots); the per-item override field bypasses derivation.
  1482. preheat_enabled: boolean;
  1483. preheat_filament_targets: string;
  1484. preheat_max_wait_seconds: number;
  1485. preheat_soak_seconds: number;
  1486. queue_keep_bed_warm: boolean;
  1487. queue_keep_warm_bed_temp: number;
  1488. queue_keep_warm_max_minutes: number;
  1489. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1490. // Empty string = use built-in defaults.
  1491. nozzle_temp_presets: string;
  1492. bed_temp_presets: string;
  1493. chamber_temp_presets: string;
  1494. fan_speed_presets: string;
  1495. // Default sidebar order (admin-set for all users)
  1496. default_sidebar_order: string;
  1497. // LDAP authentication
  1498. ldap_enabled: boolean;
  1499. ldap_server_url: string;
  1500. ldap_bind_dn: string;
  1501. ldap_bind_password: string;
  1502. ldap_search_base: string;
  1503. ldap_user_filter: string;
  1504. ldap_security: string;
  1505. ldap_group_mapping: string;
  1506. ldap_auto_provision: boolean;
  1507. ldap_default_group: string;
  1508. obico_enabled: boolean;
  1509. obico_ml_url: string;
  1510. bambuddy_internal_url: string;
  1511. obico_ml_token: string;
  1512. obico_sensitivity: 'low' | 'medium' | 'high';
  1513. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1514. obico_poll_interval: number;
  1515. obico_enabled_printers: string;
  1516. // Inventory forecasting global lead time
  1517. forecast_global_lead_time_days: number;
  1518. location_sensor_poll_interval: number;
  1519. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1520. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1521. // Server-backed so two admins seed the same alert rules and a restore
  1522. // brings them back; see utils/locationSensorDefaults.ts.
  1523. location_sensor_alert_defaults: string;
  1524. }
  1525. export type AppSettingsUpdate = Partial<AppSettings>;
  1526. // Settings as a page sees them: everything from GET /settings for a user who
  1527. // may read it, otherwise the subset /settings/ui-preferences and
  1528. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1529. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1530. // MQTT relay status
  1531. export interface MQTTStatus {
  1532. enabled: boolean;
  1533. connected: boolean;
  1534. broker: string;
  1535. port: number;
  1536. topic_prefix: string;
  1537. }
  1538. // Cloud types
  1539. export interface CloudAuthStatus {
  1540. is_authenticated: boolean;
  1541. email: string | null;
  1542. region?: 'global' | 'china' | null;
  1543. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1544. sign_in_expired?: boolean;
  1545. }
  1546. export interface CloudLoginResponse {
  1547. success: boolean;
  1548. needs_verification: boolean;
  1549. message: string;
  1550. verification_type?: 'email' | 'totp' | null;
  1551. tfa_key?: string | null;
  1552. /**
  1553. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1554. * layer is challenging this network and no credential will be accepted until
  1555. * it clears — the UI must explain that in place rather than toast `message`.
  1556. */
  1557. reason?: 'captcha' | string | null;
  1558. }
  1559. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1560. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1561. // flow is paste-based rather than callback-based.
  1562. export interface OrcaDeviceStartResponse {
  1563. user_code: string;
  1564. verification_uri: string;
  1565. verification_uri_complete: string;
  1566. interval: number;
  1567. expires_in: number;
  1568. }
  1569. export type OrcaDevicePollStatus =
  1570. | 'authorization_pending'
  1571. | 'slow_down'
  1572. | 'access_denied'
  1573. | 'expired_token'
  1574. | 'complete';
  1575. export interface OrcaDevicePollResponse {
  1576. status: OrcaDevicePollStatus;
  1577. connected: boolean;
  1578. email: string | null;
  1579. user_id: string | null;
  1580. }
  1581. export interface OrcaAuthStatusResponse {
  1582. connected: boolean;
  1583. email: string | null;
  1584. user_id: string | null;
  1585. }
  1586. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1587. // so the frontend can use the same visual components for both surfaces (cards,
  1588. // grouped sections, filter bar). Backend handles the source-specific
  1589. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1590. export interface OrcaProfileMeta {
  1591. setting_id: string;
  1592. name: string;
  1593. type: string;
  1594. version: string | null;
  1595. user_id: string | null;
  1596. updated_time: string | null;
  1597. is_custom: boolean;
  1598. }
  1599. export interface OrcaProfileListResponse {
  1600. filament: OrcaProfileMeta[];
  1601. printer: OrcaProfileMeta[];
  1602. process: OrcaProfileMeta[];
  1603. }
  1604. export interface OrcaProfileDetail {
  1605. setting_id: string;
  1606. name: string;
  1607. type: string;
  1608. version: string | null;
  1609. base_id: string | null;
  1610. update_time: string | null;
  1611. setting: Record<string, unknown>;
  1612. }
  1613. // MakerWorld integration. Full metadata/instance shapes come back as
  1614. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1615. // pass them through verbatim rather than maintaining a brittle mirror.
  1616. export interface MakerworldStatus {
  1617. has_cloud_token: boolean;
  1618. can_download: boolean;
  1619. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1620. sign_in_expired?: boolean;
  1621. }
  1622. export interface MakerworldResolvedModel {
  1623. model_id: number;
  1624. profile_id: number | null;
  1625. design: Record<string, unknown>;
  1626. instances: Array<Record<string, unknown>>;
  1627. already_imported_library_ids: number[];
  1628. }
  1629. export interface MakerworldImportResponse {
  1630. library_file_id: number;
  1631. filename: string;
  1632. folder_id: number | null;
  1633. profile_id: number | null;
  1634. was_existing: boolean;
  1635. }
  1636. export interface MakerworldRecentImport {
  1637. library_file_id: number;
  1638. filename: string;
  1639. folder_id: number | null;
  1640. thumbnail_path: string | null;
  1641. source_url: string | null;
  1642. created_at: string;
  1643. }
  1644. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1645. // searched, with single files imported into the library.
  1646. export interface ManyfoldConfig {
  1647. url: string;
  1648. client_id: string;
  1649. /** The secret itself is never returned. */
  1650. has_client_secret: boolean;
  1651. configured: boolean;
  1652. }
  1653. export interface ManyfoldConfigInput {
  1654. url: string;
  1655. client_id: string;
  1656. /** Empty or left out keeps the stored secret. */
  1657. client_secret?: string;
  1658. }
  1659. export interface ManyfoldStatus {
  1660. configured: boolean;
  1661. url: string;
  1662. }
  1663. export interface ManyfoldModelSummary {
  1664. id: string;
  1665. name: string;
  1666. }
  1667. export interface ManyfoldModelList {
  1668. total: number;
  1669. page: number;
  1670. has_next: boolean;
  1671. has_previous: boolean;
  1672. models: ManyfoldModelSummary[];
  1673. }
  1674. export interface ManyfoldFile {
  1675. id: string;
  1676. name: string;
  1677. mime: string;
  1678. importable: boolean;
  1679. /** Set while the file imported earlier is still in the library. */
  1680. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1681. }
  1682. export interface ManyfoldModel {
  1683. id: string;
  1684. name: string;
  1685. caption: string | null;
  1686. description: string | null;
  1687. license: string | null;
  1688. tags: string[];
  1689. url: string;
  1690. has_preview: boolean;
  1691. files: ManyfoldFile[];
  1692. }
  1693. export interface ManyfoldImportResponse {
  1694. library_file_id: number;
  1695. filename: string;
  1696. folder_id: number | null;
  1697. was_existing: boolean;
  1698. }
  1699. export interface SlicerSetting {
  1700. setting_id: string;
  1701. name: string;
  1702. type: string;
  1703. version: string | null;
  1704. user_id: string | null;
  1705. updated_time: string | null;
  1706. is_custom: boolean;
  1707. }
  1708. export interface SpoolCatalogEntry {
  1709. id: number;
  1710. name: string;
  1711. weight: number;
  1712. is_default: boolean;
  1713. }
  1714. export interface StorageLocation {
  1715. id: number;
  1716. name: string;
  1717. identifier: string | null;
  1718. spool_count: number;
  1719. created_at: string;
  1720. updated_at: string;
  1721. }
  1722. export interface ColorCatalogEntry {
  1723. id: number;
  1724. manufacturer: string;
  1725. color_name: string;
  1726. hex_color: string;
  1727. material: string | null;
  1728. is_default: boolean;
  1729. // #1154: optional multi-colour gradient stops + visual effect.
  1730. extra_colors?: string | null;
  1731. effect_type?: string | null;
  1732. }
  1733. export interface SlicerSettingsResponse {
  1734. filament: SlicerSetting[];
  1735. printer: SlicerSetting[];
  1736. process: SlicerSetting[];
  1737. }
  1738. export interface SlicerSettingDetail {
  1739. message?: string | null;
  1740. code?: string | null;
  1741. error?: string | null;
  1742. public: boolean;
  1743. version?: string | null;
  1744. type: string;
  1745. name: string;
  1746. update_time?: string | null;
  1747. nickname?: string | null;
  1748. base_id?: string | null;
  1749. setting: Record<string, unknown>;
  1750. filament_id?: string | null;
  1751. setting_id?: string | null;
  1752. }
  1753. export interface SlicerSettingCreate {
  1754. type: string; // 'filament', 'print', or 'printer'
  1755. name: string;
  1756. base_id: string;
  1757. setting: Record<string, unknown>;
  1758. }
  1759. export interface SlicerSettingUpdate {
  1760. name?: string;
  1761. setting?: Record<string, unknown>;
  1762. }
  1763. export interface SlicerSettingDeleteResponse {
  1764. success: boolean;
  1765. message: string;
  1766. }
  1767. // Built-in filament fallback (static table from backend)
  1768. export interface BuiltinFilament {
  1769. filament_id: string;
  1770. name: string;
  1771. }
  1772. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1773. //
  1774. // Two preset shapes are accepted per slot:
  1775. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1776. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1777. // across cloud / local / standard tiers. Source-aware refs win when both
  1778. // are present in the same payload.
  1779. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1780. export interface PresetRef {
  1781. source: PresetSource;
  1782. id: string;
  1783. }
  1784. /**
  1785. * Why a preset's effective values are unavailable.
  1786. *
  1787. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1788. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1789. * on, so a user can perfectly well be running a current Bambuddy against a
  1790. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1791. * beats a generic "could not read the values".
  1792. */
  1793. export type SlicerPresetValuesReason =
  1794. | 'ok'
  1795. | 'sidecar_outdated'
  1796. | 'sidecar_unavailable'
  1797. | 'not_configured'
  1798. | 'preset_unresolved';
  1799. export interface SlicerPresetValues {
  1800. /** False when the sidecar could not supply values; `values` is then empty. */
  1801. resolved: boolean;
  1802. /** Flattened key -> value map, in the string forms a process preset stores. */
  1803. values: Record<string, string | string[]>;
  1804. reason: SlicerPresetValuesReason;
  1805. }
  1806. export interface SliceRequest {
  1807. printer_preset_id?: number;
  1808. process_preset_id?: number;
  1809. filament_preset_id?: number;
  1810. printer_preset?: PresetRef;
  1811. process_preset?: PresetRef;
  1812. filament_preset?: PresetRef;
  1813. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1814. // preferred over the singular `filament_preset` when both are sent; the
  1815. // backend validator promotes a singular into a one-element list when this
  1816. // is omitted, so legacy single-color clients keep working unchanged.
  1817. filament_presets?: PresetRef[];
  1818. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1819. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1820. // *preset* -- it is a per-project property -- so without this every sliced
  1821. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1822. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1823. // any position hands that slot back to the backend's fallback chain (the
  1824. // preset's own default_filament_colour, then the source plate's colour).
  1825. filament_colours?: string[];
  1826. plate?: number;
  1827. export_3mf?: boolean;
  1828. // Build-plate override (#1337). When omitted, the slicer uses the process
  1829. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1830. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1831. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1832. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1833. bed_type?: string | null;
  1834. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1835. // project_settings.config (the designer's own wall count, infill, etc.)
  1836. // instead of the picked profile triplet. The preset refs above are still
  1837. // required by the backend validator but go unused on this path.
  1838. use_embedded_settings?: boolean;
  1839. // Process settings the user edited in the slice modal's settings panel,
  1840. // already serialised into the string forms a process preset stores ("1" for
  1841. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1842. // onto the resolved process JSON after the designer's carried tweaks, so an
  1843. // explicit choice here wins. Omitted when the panel is untouched.
  1844. process_overrides?: Record<string, string | string[]>;
  1845. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1846. // file flags as changed from the system preset, not values.
  1847. design_overrides?: string[];
  1848. // Layout passes the slicer runs before slicing (#2548), both off by
  1849. // default because they move or rotate the objects the user laid out.
  1850. // Unlike the fields above these are CLI actions rather than profile
  1851. // values, so they apply on the embedded-settings path too.
  1852. auto_orient?: boolean;
  1853. auto_arrange?: boolean;
  1854. }
  1855. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1856. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1857. export interface UnifiedPreset {
  1858. id: string;
  1859. name: string;
  1860. source: PresetSource;
  1861. // Populated for the filament slot only — used by the SliceModal multi-color
  1862. // pre-pick to score presets against each plate slot's required (type,
  1863. // colour). Optional because the bundled / standard tier rarely carries a
  1864. // colour (colour is a runtime spool attribute on Bambu) and older API
  1865. // responses pre-date these fields entirely.
  1866. filament_type?: string | null;
  1867. filament_colour?: string | null;
  1868. // Printer-preset names a process / filament preset declares itself
  1869. // compatible with. Populated for the local tier (the slicer's own
  1870. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1871. // the process / filament dropdowns by the selected printer using this when
  1872. // present (#1325).
  1873. compatible_printers?: string[] | null;
  1874. // Printer presets only: the preset it was saved from, for the local and
  1875. // OrcaSlicer Cloud tiers (#3250).
  1876. inherits?: string | null;
  1877. }
  1878. export interface UnifiedPresetsBySlot {
  1879. printer: UnifiedPreset[];
  1880. process: UnifiedPreset[];
  1881. filament: UnifiedPreset[];
  1882. }
  1883. // What is loaded in each connected printer, for the SliceModal's
  1884. // "only connected printers" / "only loaded spools" filters (#3172).
  1885. export interface LoadedSpoolPreset {
  1886. preset_id: string;
  1887. preset_name: string;
  1888. preset_source: string;
  1889. tray_info_idx?: string | null;
  1890. }
  1891. export interface LoadedSpoolTray {
  1892. ams_id: number;
  1893. tray_id: number;
  1894. tray_type: string | null;
  1895. tray_sub_brands: string | null;
  1896. tray_color: string | null;
  1897. tray_info_idx: string | null;
  1898. exists: boolean | null;
  1899. state: number | null;
  1900. saved_preset: LoadedSpoolPreset | null;
  1901. }
  1902. export interface LoadedSpoolUnit {
  1903. id: number;
  1904. is_ams_ht: boolean;
  1905. trays: LoadedSpoolTray[];
  1906. }
  1907. export interface LoadedSpoolPrinter {
  1908. id: number;
  1909. name: string;
  1910. model: string | null;
  1911. ams: LoadedSpoolUnit[];
  1912. // Holders with a spool in them; external_holders counts all of them (two
  1913. // on a dual-nozzle printer, labelled left and right).
  1914. external: LoadedSpoolTray[];
  1915. external_holders: number;
  1916. }
  1917. export interface LoadedSpoolsResponse {
  1918. printers: LoadedSpoolPrinter[];
  1919. }
  1920. export interface UnifiedPresetsResponse {
  1921. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1922. // dedup — every tier surfaces its full list so the user can pick from
  1923. // any source. The order drives auto-pick + visual group rendering only.
  1924. orca_cloud: UnifiedPresetsBySlot;
  1925. cloud: UnifiedPresetsBySlot;
  1926. local: UnifiedPresetsBySlot;
  1927. standard: UnifiedPresetsBySlot;
  1928. cloud_status: SlicerCloudStatus;
  1929. orca_cloud_status: SlicerCloudStatus;
  1930. }
  1931. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  1932. // can apply in one click. PR A surfaces only the bundle; target_* and
  1933. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  1934. // them (they come alive in PR B / PR C).
  1935. export interface SlicerPipeline {
  1936. id: number;
  1937. name: string;
  1938. description: string | null;
  1939. printer_preset: PresetRef;
  1940. process_preset: PresetRef;
  1941. filament_presets: PresetRef[];
  1942. bed_type: string | null;
  1943. target_kind: 'specific_printer' | 'printer_class';
  1944. target_printer_id: number | null;
  1945. target_model_class: string | null;
  1946. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1947. created_by: number | null;
  1948. created_at: string;
  1949. updated_at: string;
  1950. }
  1951. export interface SlicerPipelineCreateRequest {
  1952. name: string;
  1953. description?: string | null;
  1954. printer_preset: PresetRef;
  1955. process_preset: PresetRef;
  1956. filament_presets: PresetRef[];
  1957. bed_type?: string | null;
  1958. }
  1959. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  1960. target_kind?: 'specific_printer' | 'printer_class';
  1961. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  1962. // to null. Use null in TypeScript for the same intent.
  1963. target_printer_id?: number | null;
  1964. target_model_class?: string | null;
  1965. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1966. };
  1967. export interface SlicerPipelinesListResponse {
  1968. pipelines: SlicerPipeline[];
  1969. }
  1970. // Slicer Pipeline runs (#1425 PR B + PR C)
  1971. export type PipelineEligibilityKind =
  1972. | 'printer_not_set'
  1973. | 'printer_not_found'
  1974. | 'printer_disabled'
  1975. | 'printer_offline'
  1976. | 'filament_type_mismatch'
  1977. | 'filament_color_mismatch'
  1978. | 'ams_slot_missing'
  1979. | 'filament_unverified'
  1980. | 'no_class_matches'
  1981. | 'class_not_set';
  1982. export interface PipelineEligibilityIssue {
  1983. kind: PipelineEligibilityKind;
  1984. slot_index: number | null;
  1985. expected: string | null;
  1986. actual: string | null;
  1987. }
  1988. export interface PipelinePerPrinterReport {
  1989. printer_id: number;
  1990. printer_name: string;
  1991. ok: boolean;
  1992. issues: PipelineEligibilityIssue[];
  1993. }
  1994. export interface PipelineEligibilityReport {
  1995. ok: boolean;
  1996. target_kind: 'specific_printer' | 'printer_class';
  1997. target_printer_id: number | null;
  1998. target_printer_name: string | null;
  1999. target_model_class: string | null;
  2000. issues: PipelineEligibilityIssue[];
  2001. printer_reports: PipelinePerPrinterReport[];
  2002. }
  2003. export interface PipelineJob {
  2004. id: number;
  2005. pipeline_run_id: number;
  2006. copy_index: number;
  2007. assigned_printer_id: number | null;
  2008. assigned_printer_name: string | null;
  2009. queue_entry_id: number | null;
  2010. status:
  2011. | 'pending'
  2012. | 'awaiting_printer'
  2013. | 'queued'
  2014. | 'printing'
  2015. | 'completed'
  2016. | 'failed'
  2017. | 'cancelled'
  2018. | 'unknown';
  2019. error_message: string | null;
  2020. dispatched_at: string | null;
  2021. completed_at: string | null;
  2022. }
  2023. export interface PipelineRun {
  2024. id: number;
  2025. pipeline_id: number | null;
  2026. pipeline_name: string | null;
  2027. source_library_file_id: number | null;
  2028. source_archive_id: number | null;
  2029. source_filename: string | null;
  2030. parent_run_id: number | null;
  2031. copies: number;
  2032. copies_completed: number;
  2033. copies_failed: number;
  2034. copies_cancelled: number;
  2035. copies_in_progress: number;
  2036. status:
  2037. | 'queued'
  2038. | 'slicing'
  2039. | 'dispatching'
  2040. | 'in_progress'
  2041. | 'completed'
  2042. | 'failed'
  2043. | 'partial_failure'
  2044. | 'cancelled';
  2045. slice_job_id: number | null;
  2046. sliced_library_file_id: number | null;
  2047. eligibility_overridden: boolean;
  2048. error_message: string | null;
  2049. created_by: number | null;
  2050. created_at: string;
  2051. started_at: string | null;
  2052. completed_at: string | null;
  2053. jobs: PipelineJob[];
  2054. target_kind: 'specific_printer' | 'printer_class' | null;
  2055. target_printer_id: number | null;
  2056. target_model_class: string | null;
  2057. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2058. }
  2059. export interface PipelineRunListResponse {
  2060. runs: PipelineRun[];
  2061. total: number;
  2062. }
  2063. export interface SliceResponse {
  2064. library_file_id: number;
  2065. name: string;
  2066. print_time_seconds: number;
  2067. filament_used_g: number;
  2068. filament_used_mm: number;
  2069. used_embedded_settings: boolean;
  2070. /** Why the result could not be written to the external folder the source
  2071. * lives in, and so went to managed storage instead. Null on every normal
  2072. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2073. * with no signal is what made #2810 invisible from the UI. */
  2074. external_write_fallback?: string | null;
  2075. }
  2076. export interface SliceArchiveResponse {
  2077. archive_id: number;
  2078. name: string;
  2079. print_time_seconds: number;
  2080. filament_used_g: number;
  2081. filament_used_mm: number;
  2082. used_embedded_settings: boolean;
  2083. }
  2084. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2085. // the frontend polls /slice-jobs/{id} until status is terminal.
  2086. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2087. export interface SliceJobEnqueueResponse {
  2088. job_id: number;
  2089. status: SliceJobStatus;
  2090. status_url: string;
  2091. }
  2092. export interface SliceJobProgress {
  2093. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2094. stage: string;
  2095. total_percent: number;
  2096. plate_percent: number;
  2097. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2098. plate_index: number;
  2099. plate_count: number;
  2100. updated_at: number;
  2101. /** When the backend is in the cross-class slice-all loop (#1493), each
  2102. * per-plate sub-slice's progress is augmented with the loop position
  2103. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2104. * fields are absent on a single-plate slice. */
  2105. multi_plate_index?: number;
  2106. multi_plate_count?: number;
  2107. }
  2108. export interface SliceJobState {
  2109. job_id: number;
  2110. status: SliceJobStatus;
  2111. kind: 'library_file' | 'archive';
  2112. source_id: number;
  2113. source_name: string;
  2114. created_at: string;
  2115. started_at: string | null;
  2116. completed_at: string | null;
  2117. /** Live progress fed by the sidecar's --pipe channel; null until the
  2118. * slicer emits its first frame (early "Initializing" phase) or when
  2119. * the sidecar doesn't support progress. */
  2120. progress: SliceJobProgress | null;
  2121. result?: SliceResponse | SliceArchiveResponse;
  2122. error_status?: number;
  2123. error_detail?: string;
  2124. }
  2125. // Local preset types (OrcaSlicer imports)
  2126. export interface LocalPreset {
  2127. id: number;
  2128. name: string;
  2129. preset_type: string;
  2130. source: string;
  2131. filament_type: string | null;
  2132. filament_vendor: string | null;
  2133. nozzle_temp_min: number | null;
  2134. nozzle_temp_max: number | null;
  2135. pressure_advance: string | null;
  2136. default_filament_colour: string | null;
  2137. filament_cost: string | null;
  2138. filament_density: string | null;
  2139. compatible_printers: string | null;
  2140. inherits: string | null;
  2141. version: string | null;
  2142. created_at: string;
  2143. updated_at: string;
  2144. }
  2145. export interface LocalPresetDetail extends LocalPreset {
  2146. setting: Record<string, unknown>;
  2147. }
  2148. export interface LocalPresetsResponse {
  2149. filament: LocalPreset[];
  2150. printer: LocalPreset[];
  2151. process: LocalPreset[];
  2152. }
  2153. export interface ImportResponse {
  2154. success: boolean;
  2155. imported: number;
  2156. skipped: number;
  2157. errors: string[];
  2158. }
  2159. export interface FieldOption {
  2160. value: string;
  2161. label: string;
  2162. }
  2163. export interface FieldDefinition {
  2164. key: string;
  2165. label: string;
  2166. type: 'text' | 'number' | 'boolean' | 'select';
  2167. category: string;
  2168. description?: string;
  2169. options?: FieldOption[];
  2170. unit?: string;
  2171. min?: number;
  2172. max?: number;
  2173. step?: number;
  2174. }
  2175. export interface FieldDefinitionsResponse {
  2176. version: string;
  2177. description: string;
  2178. fields: FieldDefinition[];
  2179. }
  2180. export interface CloudDevice {
  2181. dev_id: string;
  2182. name: string;
  2183. dev_model_name: string | null;
  2184. dev_product_name: string | null;
  2185. online: boolean;
  2186. }
  2187. // Smart Plug types
  2188. export interface SmartPlug {
  2189. id: number;
  2190. name: string;
  2191. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2192. ip_address: string | null; // Required for Tasmota
  2193. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2194. // Home Assistant energy sensor entities (optional)
  2195. ha_power_entity: string | null;
  2196. ha_energy_today_entity: string | null;
  2197. ha_energy_total_entity: string | null;
  2198. // MQTT fields (required when plug_type="mqtt")
  2199. // Legacy field - kept for backward compatibility
  2200. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2201. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2202. // Power monitoring
  2203. mqtt_power_topic: string | null; // Topic for power data
  2204. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2205. mqtt_power_multiplier: number; // Unit conversion for power
  2206. // Energy monitoring
  2207. mqtt_energy_topic: string | null; // Topic for energy data
  2208. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2209. mqtt_energy_multiplier: number; // Unit conversion for energy
  2210. // State monitoring
  2211. mqtt_state_topic: string | null; // Topic for state data
  2212. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2213. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2214. // REST/Webhook fields (required when plug_type="rest")
  2215. rest_on_url: string | null;
  2216. rest_on_body: string | null;
  2217. rest_off_url: string | null;
  2218. rest_off_body: string | null;
  2219. rest_method: string | null;
  2220. rest_headers: string | null;
  2221. rest_status_url: string | null;
  2222. rest_status_path: string | null;
  2223. rest_status_on_value: string | null;
  2224. rest_power_url: string | null;
  2225. rest_power_path: string | null;
  2226. rest_power_multiplier: number;
  2227. rest_energy_url: string | null;
  2228. rest_energy_path: string | null;
  2229. rest_energy_multiplier: number;
  2230. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2231. // this; Today and Yesterday are derived from its hourly snapshots.
  2232. rest_energy_total_path: string | null;
  2233. rest_energy_total_multiplier: number;
  2234. printer_id: number | null;
  2235. // #2629: only a plug that really feeds the printer may mark it offline when
  2236. // switched off. Accessory plugs follow the print cycle without powering it.
  2237. controls_printer_power: boolean;
  2238. enabled: boolean;
  2239. auto_on: boolean;
  2240. auto_off: boolean;
  2241. auto_off_persistent: boolean;
  2242. off_delay_mode: 'time' | 'temperature';
  2243. off_delay_minutes: number;
  2244. off_temp_threshold: number;
  2245. // #1349: auto-off after AMS drying completes.
  2246. auto_off_after_drying: boolean;
  2247. off_delay_after_drying_minutes: number;
  2248. username: string | null;
  2249. password: string | null;
  2250. // Power alerts
  2251. power_alert_enabled: boolean;
  2252. power_alert_high: number | null;
  2253. power_alert_low: number | null;
  2254. power_alert_last_triggered: string | null;
  2255. // Schedule
  2256. schedule_enabled: boolean;
  2257. schedule_on_time: string | null;
  2258. schedule_off_time: string | null;
  2259. // Visibility options
  2260. show_in_switchbar: boolean;
  2261. show_on_printer_card: boolean; // For scripts: show on printer card
  2262. // Status
  2263. last_state: string | null;
  2264. last_checked: string | null;
  2265. auto_off_executed: boolean; // True when auto-off was triggered after print
  2266. created_at: string;
  2267. updated_at: string;
  2268. }
  2269. export interface SmartPlugCreate {
  2270. name: string;
  2271. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2272. ip_address?: string | null; // Required for Tasmota
  2273. ha_entity_id?: string | null; // Required for Home Assistant
  2274. // Home Assistant energy sensor entities (optional)
  2275. ha_power_entity?: string | null;
  2276. ha_energy_today_entity?: string | null;
  2277. ha_energy_total_entity?: string | null;
  2278. // MQTT fields (required when plug_type="mqtt")
  2279. // Legacy fields - kept for backward compatibility
  2280. mqtt_topic?: string | null;
  2281. mqtt_multiplier?: number;
  2282. // Power monitoring
  2283. mqtt_power_topic?: string | null;
  2284. mqtt_power_path?: string | null;
  2285. mqtt_power_multiplier?: number;
  2286. // Energy monitoring
  2287. mqtt_energy_topic?: string | null;
  2288. mqtt_energy_path?: string | null;
  2289. mqtt_energy_multiplier?: number;
  2290. // State monitoring
  2291. mqtt_state_topic?: string | null;
  2292. mqtt_state_path?: string | null;
  2293. mqtt_state_on_value?: string | null;
  2294. // REST fields
  2295. rest_on_url?: string | null;
  2296. rest_on_body?: string | null;
  2297. rest_off_url?: string | null;
  2298. rest_off_body?: string | null;
  2299. rest_method?: string | null;
  2300. rest_headers?: string | null;
  2301. rest_status_url?: string | null;
  2302. rest_status_path?: string | null;
  2303. rest_status_on_value?: string | null;
  2304. rest_power_url?: string | null;
  2305. rest_power_path?: string | null;
  2306. rest_power_multiplier?: number;
  2307. rest_energy_url?: string | null;
  2308. rest_energy_path?: string | null;
  2309. rest_energy_multiplier?: number;
  2310. rest_energy_total_path?: string | null;
  2311. rest_energy_total_multiplier?: number;
  2312. printer_id?: number | null;
  2313. // #2629
  2314. controls_printer_power?: boolean;
  2315. enabled?: boolean;
  2316. auto_on?: boolean;
  2317. auto_off?: boolean;
  2318. auto_off_persistent?: boolean;
  2319. off_delay_mode?: 'time' | 'temperature';
  2320. off_delay_minutes?: number;
  2321. off_temp_threshold?: number;
  2322. // #1349
  2323. auto_off_after_drying?: boolean;
  2324. off_delay_after_drying_minutes?: number;
  2325. username?: string | null;
  2326. password?: string | null;
  2327. // Power alerts
  2328. power_alert_enabled?: boolean;
  2329. power_alert_high?: number | null;
  2330. power_alert_low?: number | null;
  2331. // Schedule
  2332. schedule_enabled?: boolean;
  2333. schedule_on_time?: string | null;
  2334. schedule_off_time?: string | null;
  2335. // Visibility options
  2336. show_in_switchbar?: boolean;
  2337. show_on_printer_card?: boolean;
  2338. }
  2339. export interface SmartPlugUpdate {
  2340. name?: string;
  2341. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2342. ip_address?: string | null;
  2343. ha_entity_id?: string | null;
  2344. // Home Assistant energy sensor entities (optional)
  2345. ha_power_entity?: string | null;
  2346. ha_energy_today_entity?: string | null;
  2347. ha_energy_total_entity?: string | null;
  2348. // MQTT fields (legacy)
  2349. mqtt_topic?: string | null;
  2350. mqtt_multiplier?: number;
  2351. // MQTT power fields
  2352. mqtt_power_topic?: string | null;
  2353. mqtt_power_path?: string | null;
  2354. mqtt_power_multiplier?: number;
  2355. // MQTT energy fields
  2356. mqtt_energy_topic?: string | null;
  2357. mqtt_energy_path?: string | null;
  2358. mqtt_energy_multiplier?: number;
  2359. // MQTT state fields
  2360. mqtt_state_topic?: string | null;
  2361. mqtt_state_path?: string | null;
  2362. mqtt_state_on_value?: string | null;
  2363. // REST fields
  2364. rest_on_url?: string | null;
  2365. rest_on_body?: string | null;
  2366. rest_off_url?: string | null;
  2367. rest_off_body?: string | null;
  2368. rest_method?: string | null;
  2369. rest_headers?: string | null;
  2370. rest_status_url?: string | null;
  2371. rest_status_path?: string | null;
  2372. rest_status_on_value?: string | null;
  2373. rest_power_url?: string | null;
  2374. rest_power_path?: string | null;
  2375. rest_power_multiplier?: number;
  2376. rest_energy_url?: string | null;
  2377. rest_energy_path?: string | null;
  2378. rest_energy_multiplier?: number;
  2379. rest_energy_total_path?: string | null;
  2380. rest_energy_total_multiplier?: number;
  2381. printer_id?: number | null;
  2382. // #2629
  2383. controls_printer_power?: boolean;
  2384. enabled?: boolean;
  2385. auto_on?: boolean;
  2386. auto_off?: boolean;
  2387. auto_off_persistent?: boolean;
  2388. off_delay_mode?: 'time' | 'temperature';
  2389. off_delay_minutes?: number;
  2390. off_temp_threshold?: number;
  2391. // #1349
  2392. auto_off_after_drying?: boolean;
  2393. off_delay_after_drying_minutes?: number;
  2394. username?: string | null;
  2395. password?: string | null;
  2396. // Power alerts
  2397. power_alert_enabled?: boolean;
  2398. power_alert_high?: number | null;
  2399. power_alert_low?: number | null;
  2400. // Schedule
  2401. schedule_enabled?: boolean;
  2402. schedule_on_time?: string | null;
  2403. schedule_off_time?: string | null;
  2404. // Visibility options
  2405. show_in_switchbar?: boolean;
  2406. show_on_printer_card?: boolean;
  2407. }
  2408. // Home Assistant entity for smart plug selection
  2409. export interface HAEntity {
  2410. entity_id: string;
  2411. friendly_name: string;
  2412. state: string | null;
  2413. domain: string; // "switch", "light", "input_boolean", "script"
  2414. }
  2415. // Home Assistant sensor entity for energy monitoring
  2416. export interface HASensorEntity {
  2417. entity_id: string;
  2418. friendly_name: string;
  2419. state: string | null;
  2420. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2421. }
  2422. export interface HATestConnectionResult {
  2423. success: boolean;
  2424. message: string | null;
  2425. error: string | null;
  2426. }
  2427. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2428. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2429. export interface PrinterHASensor {
  2430. id: number;
  2431. printer_id: number;
  2432. name: string;
  2433. entity_id: string;
  2434. kind: 'binary' | 'numeric';
  2435. device_class: string | null; // HA's own class: "door", "temperature", ...
  2436. unit: string | null; // numeric sensors only
  2437. // What counts as needing attention. Binary sensors use alert_state, numeric
  2438. // ones the thresholds; all null means the sensor is display-only.
  2439. alert_state: 'on' | 'off' | null;
  2440. alert_above: number | null;
  2441. alert_below: number | null;
  2442. block_print: boolean; // hold the printer's queue while alerting
  2443. notify_on_alert: boolean;
  2444. show_on_printer_card: boolean;
  2445. sort_order: number;
  2446. last_state: string | null;
  2447. last_changed: string | null;
  2448. last_checked: string | null;
  2449. created_at: string;
  2450. updated_at: string;
  2451. }
  2452. export interface PrinterHASensorReading {
  2453. id: number;
  2454. name: string;
  2455. entity_id: string;
  2456. kind: 'binary' | 'numeric';
  2457. device_class: string | null;
  2458. unit: string | null;
  2459. state: string | null; // null when unreadable or not yet polled
  2460. value: number | null; // numeric sensors only
  2461. alerting: boolean;
  2462. block_print: boolean;
  2463. reachable: boolean;
  2464. last_changed: string | null;
  2465. }
  2466. export interface PrinterHASensorCreate {
  2467. printer_id: number;
  2468. name: string;
  2469. entity_id: string;
  2470. kind: 'binary' | 'numeric';
  2471. device_class?: string | null;
  2472. unit?: string | null;
  2473. alert_state?: 'on' | 'off' | null;
  2474. alert_above?: number | null;
  2475. alert_below?: number | null;
  2476. block_print?: boolean;
  2477. notify_on_alert?: boolean;
  2478. show_on_printer_card?: boolean;
  2479. sort_order?: number;
  2480. }
  2481. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2482. export interface LocationHASensor {
  2483. id: number;
  2484. location_id: number;
  2485. name: string;
  2486. entity_id: string;
  2487. kind: 'binary' | 'numeric';
  2488. device_class: string | null;
  2489. unit: string | null;
  2490. alert_state: 'on' | 'off' | null;
  2491. alert_above: number | null;
  2492. alert_below: number | null;
  2493. notify_on_alert: boolean;
  2494. show_on_card: boolean;
  2495. sort_order: number;
  2496. last_state: string | null;
  2497. last_changed: string | null;
  2498. last_checked: string | null;
  2499. created_at: string;
  2500. updated_at: string;
  2501. }
  2502. export interface LocationHASensorReading {
  2503. id: number;
  2504. name: string;
  2505. entity_id: string;
  2506. kind: 'binary' | 'numeric';
  2507. device_class: string | null;
  2508. unit: string | null;
  2509. state: string | null;
  2510. value: number | null;
  2511. alerting: boolean;
  2512. reachable: boolean;
  2513. alert_state: string | null;
  2514. alert_above: number | null;
  2515. alert_below: number | null;
  2516. last_changed: string | null;
  2517. show_on_card: boolean;
  2518. }
  2519. export interface LocationHASensorCreate {
  2520. location_id: number;
  2521. name: string;
  2522. entity_id: string;
  2523. kind: 'binary' | 'numeric';
  2524. device_class?: string | null;
  2525. unit?: string | null;
  2526. alert_state?: 'on' | 'off' | null;
  2527. alert_above?: number | null;
  2528. alert_below?: number | null;
  2529. notify_on_alert?: boolean;
  2530. show_on_card?: boolean;
  2531. sort_order?: number;
  2532. }
  2533. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2534. // An entity offered by the binding picker.
  2535. export interface HADisplayEntity {
  2536. entity_id: string;
  2537. friendly_name: string;
  2538. state: string | null;
  2539. domain: string; // "binary_sensor" | "sensor"
  2540. device_class: string | null;
  2541. unit_of_measurement: string | null;
  2542. }
  2543. export interface SmartPlugEnergy {
  2544. power: number | null; // Current watts
  2545. voltage: number | null; // Volts
  2546. current: number | null; // Amps
  2547. today: number | null; // kWh used today
  2548. yesterday: number | null; // kWh used yesterday
  2549. total: number | null; // Total kWh
  2550. factor: number | null; // Power factor (0-1)
  2551. apparent_power: number | null; // VA
  2552. reactive_power: number | null; // VAr
  2553. }
  2554. export interface SmartPlugStatus {
  2555. state: string | null;
  2556. reachable: boolean;
  2557. device_name: string | null;
  2558. energy: SmartPlugEnergy | null;
  2559. }
  2560. export interface SmartPlugTestResult {
  2561. success: boolean;
  2562. state: string | null;
  2563. device_name: string | null;
  2564. }
  2565. // Tasmota Discovery types
  2566. export interface TasmotaScanStatus {
  2567. running: boolean;
  2568. scanned: number;
  2569. total: number;
  2570. }
  2571. export interface DiscoveredTasmotaDevice {
  2572. ip_address: string;
  2573. name: string;
  2574. module: number | null;
  2575. state: string | null;
  2576. discovered_at: string | null;
  2577. }
  2578. // Print Queue types
  2579. export interface PrintQueueItem {
  2580. id: number;
  2581. printer_id: number | null; // null = unassigned
  2582. target_model: string | null; // Target printer model for model-based assignment
  2583. target_location: string | null; // Target location filter for model-based assignment
  2584. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2585. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2586. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2587. // items. Present until dispatch resolves one, after which library_file_id and
  2588. // target_model name the candidate that actually ran.
  2589. variants?: Array<{
  2590. library_file_id: number;
  2591. filename: string;
  2592. target_model: string;
  2593. position: number;
  2594. }>;
  2595. // Either archive_id OR library_file_id must be set (archive created at print start)
  2596. archive_id: number | null;
  2597. library_file_id: number | null;
  2598. cost_center_id: number | null;
  2599. estimated_cost: number | null;
  2600. position: number;
  2601. scheduled_time: string | null;
  2602. require_previous_success: boolean;
  2603. auto_off_after: boolean;
  2604. manual_start: boolean; // Requires manual trigger to start (staged)
  2605. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2606. // any required slot's grams (#1496). Surfaced on the queue row as a
  2607. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2608. filament_short: boolean;
  2609. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2610. // skips the deficit check for this item (#1698-followup). Set by the
  2611. // start route when skip_filament_check=true, or at queue creation if
  2612. // PrintModal's deficit warning was acknowledged.
  2613. skip_filament_check: boolean;
  2614. // True when the source archive carries the slicer's own live-resolved
  2615. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2616. // exact physical spool instead of re-deriving one from type/color.
  2617. archive_has_slicer_ams_mapping: boolean;
  2618. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2619. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  2620. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2621. // Print options
  2622. bed_levelling: CalibrationMode;
  2623. flow_cali: CalibrationMode;
  2624. vibration_cali: boolean;
  2625. layer_inspect: boolean;
  2626. timelapse: boolean;
  2627. use_ams: boolean;
  2628. nozzle_offset_cali: CalibrationMode;
  2629. // Ask for a post-print outcome verdict when this job completes (#1898)
  2630. confirm_outcome: boolean;
  2631. preheat_override: 'inherit' | 'on' | 'off';
  2632. preheat_chamber_target_override: number | null;
  2633. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2634. started_at: string | null;
  2635. completed_at: string | null;
  2636. error_message: string | null;
  2637. created_at: string;
  2638. archive_name?: string | null;
  2639. archive_thumbnail?: string | null;
  2640. // True when the linked archive has been soft-deleted; archive_name /
  2641. // archive_thumbnail / downstream metadata are left null in that case so
  2642. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2643. archive_deleted?: boolean;
  2644. library_file_name?: string | null;
  2645. library_file_thumbnail?: string | null;
  2646. printer_name?: string | null;
  2647. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2648. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2649. filament_type?: string | null; // e.g. "PLA", "PETG"
  2650. filament_color?: string | null; // Hex RGBA from the slicer
  2651. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2652. // User tracking (Issue #206)
  2653. created_by_id?: number | null;
  2654. created_by_username?: string | null;
  2655. // Batch grouping
  2656. batch_id?: number | null;
  2657. batch_name?: string | null;
  2658. // Shortest-job-first scheduling
  2659. been_jumped?: boolean;
  2660. // Auto-print G-code injection
  2661. gcode_injection?: boolean;
  2662. cleanup_library_after_dispatch?: boolean;
  2663. /** Which rack position each filament group prints from, on a nozzle-rack
  2664. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2665. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2666. nozzle_rack_choice?: Record<number, number> | null;
  2667. /** Slots sent with a spool of another colour than the file asks for
  2668. * (#3279). Worked out when the job is sent; null when every slot got its
  2669. * colour or nothing could be compared. */
  2670. color_substitutions?: ColorSubstitution[] | null;
  2671. }
  2672. /** One slot printed in another colour than the file asked for (#3279). */
  2673. export interface ColorSubstitution {
  2674. slot_id: number;
  2675. type: string;
  2676. /** `#RRGGBB` the file asks for, after overrides. */
  2677. wanted: string;
  2678. /** `#RRGGBB` of the spool the slot was sent with. */
  2679. got: string;
  2680. tray: number;
  2681. }
  2682. export interface PrintBatchPlateTarget {
  2683. plate_id: number | null;
  2684. plate_name?: string | null;
  2685. quantity_target: number;
  2686. sort_order?: number;
  2687. }
  2688. export interface PrintBatchPlateProgress {
  2689. plate_id: number | null;
  2690. plate_name: string | null;
  2691. quantity_target: number;
  2692. dispatched: number;
  2693. remaining: number;
  2694. pending_count: number;
  2695. printing_count: number;
  2696. completed_count: number;
  2697. failed_count: number;
  2698. cancelled_count: number;
  2699. skipped_count: number;
  2700. /** Measured from finished runs; null until one has produced a cost. */
  2701. actual_cost: number | null;
  2702. estimated_remaining_cost: number | null;
  2703. filament_used_grams: number | null;
  2704. print_time_seconds: number;
  2705. /** False when this plate owes runs but has no queue item left to clone
  2706. * their configuration from, so queueing it could only fail (#2960). */
  2707. can_dispatch: boolean;
  2708. }
  2709. export interface PrintBatch {
  2710. id: number;
  2711. name: string;
  2712. archive_id: number | null;
  2713. library_file_id: number | null;
  2714. quantity: number;
  2715. status: string;
  2716. created_at: string;
  2717. completed_at: string | null;
  2718. created_by_id: number | null;
  2719. created_by_username: string | null;
  2720. project_id: number | null;
  2721. due_date: string | null;
  2722. notes: string | null;
  2723. /** Set when an integration (e.g. a shop connector) created the batch. */
  2724. external_source: string | null;
  2725. external_ref: string | null;
  2726. pending_count: number;
  2727. printing_count: number;
  2728. completed_count: number;
  2729. failed_count: number;
  2730. cancelled_count: number;
  2731. skipped_count: number;
  2732. /** False for batches created before per-plate targets existed (#342):
  2733. * they report progress but owe nothing and cannot be dispatched from. */
  2734. has_targets: boolean;
  2735. target_count: number;
  2736. remaining_count: number;
  2737. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2738. dispatchable_count: number;
  2739. actual_cost: number | null;
  2740. estimated_remaining_cost: number | null;
  2741. filament_used_grams: number | null;
  2742. print_time_seconds: number;
  2743. plates: PrintBatchPlateProgress[];
  2744. }
  2745. export interface PrintQueueItemCreate {
  2746. printer_id?: number | null; // null = unassigned
  2747. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2748. target_location?: string | null; // Target location filter (only used with target_model)
  2749. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2750. archive_id?: number | null;
  2751. library_file_id?: number | null;
  2752. scheduled_time?: string | null;
  2753. require_previous_success?: boolean;
  2754. auto_off_after?: boolean;
  2755. manual_start?: boolean; // Requires manual trigger to start (staged)
  2756. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2757. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2758. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2759. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2760. skip_filament_check?: boolean;
  2761. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2762. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2763. // Print options
  2764. bed_levelling?: CalibrationMode;
  2765. flow_cali?: CalibrationMode;
  2766. vibration_cali?: boolean;
  2767. layer_inspect?: boolean;
  2768. timelapse?: boolean;
  2769. use_ams?: boolean;
  2770. nozzle_offset_cali?: CalibrationMode;
  2771. // Ask for a post-print outcome verdict when this job completes (#1898)
  2772. confirm_outcome?: boolean;
  2773. preheat_override?: 'inherit' | 'on' | 'off';
  2774. preheat_chamber_target_override?: number | null;
  2775. // Auto-print G-code injection
  2776. gcode_injection?: boolean;
  2777. // Batch: create multiple copies (creates a batch if > 1)
  2778. quantity?: number;
  2779. // Existing batch to add this item into (multi-plate auto-batch flow).
  2780. batch_id?: number | null;
  2781. // Project to associate the resulting archive with
  2782. project_id?: number;
  2783. cost_center_id?: number | null;
  2784. estimated_cost?: number | null;
  2785. // Delete transient uploaded library file after scheduler creates the archive
  2786. cleanup_library_after_dispatch?: boolean;
  2787. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2788. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2789. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2790. // Order is priority — index 0 wins when several printers are idle at once.
  2791. variants?: QueueVariantCreate[];
  2792. /** Which rack position each filament group prints from, on a nozzle-rack
  2793. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2794. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2795. nozzle_rack_choice?: Record<number, number> | null;
  2796. }
  2797. /** One candidate file for a cross-model queue item (#671). */
  2798. export interface QueueVariantCreate {
  2799. library_file_id: number;
  2800. /** Read from the file's own sliced_for_model unless it declares none. */
  2801. target_model?: string | null;
  2802. plate_id?: number | null;
  2803. ams_mapping?: number[] | null;
  2804. nozzle_mapping?: number[] | null;
  2805. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2806. }
  2807. export interface PrintBatchCreate {
  2808. name: string;
  2809. archive_id?: number | null;
  2810. library_file_id?: number | null;
  2811. /** When set, the listed pending items are assigned to the new batch
  2812. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2813. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2814. item_ids?: number[];
  2815. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2816. plates?: PrintBatchPlateTarget[];
  2817. project_id?: number | null;
  2818. due_date?: string | null;
  2819. notes?: string | null;
  2820. }
  2821. export interface PrintBatchUpdate {
  2822. name?: string;
  2823. status?: 'active' | 'cancelled';
  2824. /** Replaces the full target set — a plate omitted here is removed. */
  2825. plates?: PrintBatchPlateTarget[];
  2826. project_id?: number | null;
  2827. due_date?: string | null;
  2828. notes?: string | null;
  2829. }
  2830. export interface PrintBatchDispatchRequest {
  2831. plate_id?: number | null;
  2832. only_plate?: boolean;
  2833. /** Cap on items created across all plates; omit to queue everything owed. */
  2834. limit?: number;
  2835. }
  2836. export interface PrintQueueItemUpdate {
  2837. printer_id?: number | null; // null = unassign
  2838. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2839. skip_filament_check?: boolean;
  2840. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2841. target_location?: string | null; // Target location filter (only used with target_model)
  2842. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2843. position?: number;
  2844. scheduled_time?: string | null;
  2845. require_previous_success?: boolean;
  2846. auto_off_after?: boolean;
  2847. manual_start?: boolean;
  2848. ams_mapping?: number[];
  2849. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2850. // Print options
  2851. bed_levelling?: CalibrationMode;
  2852. flow_cali?: CalibrationMode;
  2853. vibration_cali?: boolean;
  2854. layer_inspect?: boolean;
  2855. timelapse?: boolean;
  2856. use_ams?: boolean;
  2857. nozzle_offset_cali?: CalibrationMode;
  2858. // Ask for a post-print outcome verdict when this job completes (#1898)
  2859. confirm_outcome?: boolean;
  2860. preheat_override?: 'inherit' | 'on' | 'off';
  2861. preheat_chamber_target_override?: number | null;
  2862. // Auto-print G-code injection
  2863. gcode_injection?: boolean;
  2864. cost_center_id?: number | null;
  2865. estimated_cost?: number | null;
  2866. /** Which rack position each filament group prints from, on a nozzle-rack
  2867. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2868. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2869. nozzle_rack_choice?: Record<number, number> | null;
  2870. }
  2871. export interface PrintQueueBulkUpdate {
  2872. item_ids: number[];
  2873. printer_id?: number | null;
  2874. scheduled_time?: string | null;
  2875. require_previous_success?: boolean;
  2876. auto_off_after?: boolean;
  2877. manual_start?: boolean;
  2878. // Print options
  2879. bed_levelling?: CalibrationMode;
  2880. flow_cali?: CalibrationMode;
  2881. vibration_cali?: boolean;
  2882. layer_inspect?: boolean;
  2883. timelapse?: boolean;
  2884. use_ams?: boolean;
  2885. nozzle_offset_cali?: CalibrationMode;
  2886. // Ask for a post-print outcome verdict when this job completes (#1898)
  2887. confirm_outcome?: boolean;
  2888. preheat_override?: 'inherit' | 'on' | 'off';
  2889. preheat_chamber_target_override?: number | null;
  2890. // Auto-print G-code injection
  2891. gcode_injection?: boolean;
  2892. cost_center_id?: number | null;
  2893. estimated_cost?: number | null;
  2894. }
  2895. export interface PrintQueueBulkUpdateResponse {
  2896. updated_count: number;
  2897. skipped_count: number;
  2898. message: string;
  2899. }
  2900. // MQTT Logging types
  2901. export interface MQTTLogEntry {
  2902. timestamp: string;
  2903. topic: string;
  2904. direction: 'in' | 'out';
  2905. payload: Record<string, unknown>;
  2906. }
  2907. export interface MQTTLogsResponse {
  2908. logging_enabled: boolean;
  2909. logs: MQTTLogEntry[];
  2910. }
  2911. // K-Profile types
  2912. export interface KProfile {
  2913. slot_id: number;
  2914. extruder_id: number;
  2915. nozzle_id: string;
  2916. nozzle_diameter: string;
  2917. filament_id: string;
  2918. name: string;
  2919. k_value: string;
  2920. n_coef: string;
  2921. ams_id: number;
  2922. tray_id: number;
  2923. setting_id: string | null;
  2924. }
  2925. export interface KProfileCreate {
  2926. slot_id?: number; // Storage slot, 0 for new profiles
  2927. extruder_id?: number;
  2928. nozzle_id: string;
  2929. nozzle_diameter: string;
  2930. filament_id: string;
  2931. name: string;
  2932. k_value: string;
  2933. n_coef?: string;
  2934. ams_id?: number;
  2935. tray_id?: number;
  2936. setting_id?: string | null;
  2937. }
  2938. export interface KProfileDelete {
  2939. slot_id: number; // cali_idx - calibration index to delete
  2940. extruder_id: number;
  2941. nozzle_id: string; // e.g., "HH00-0.4"
  2942. nozzle_diameter: string; // e.g., "0.4"
  2943. filament_id: string; // Bambu filament identifier
  2944. setting_id?: string | null; // Setting ID (for X1C series)
  2945. }
  2946. export interface KProfilesResponse {
  2947. profiles: KProfile[];
  2948. nozzle_diameter: string;
  2949. }
  2950. export interface KProfileNote {
  2951. setting_id: string;
  2952. note: string;
  2953. }
  2954. export interface KProfileNotesResponse {
  2955. notes: Record<string, string>; // setting_id -> note
  2956. }
  2957. // Slot Preset Mapping
  2958. export interface SlotPresetMapping {
  2959. ams_id: number;
  2960. tray_id: number;
  2961. preset_id: string;
  2962. preset_name: string;
  2963. // Filament id the slot was configured with alongside this preset; null for
  2964. // rows that predate it or whose writer did not know it (#3216).
  2965. tray_info_idx?: string | null;
  2966. }
  2967. // Filament types
  2968. export interface Filament {
  2969. id: number;
  2970. name: string;
  2971. type: string; // PLA, PETG, ABS, etc.
  2972. brand: string | null;
  2973. color: string | null;
  2974. color_hex: string | null;
  2975. cost_per_kg: number;
  2976. spool_weight_g: number;
  2977. currency: string;
  2978. density: number | null;
  2979. print_temp_min: number | null;
  2980. print_temp_max: number | null;
  2981. bed_temp_min: number | null;
  2982. bed_temp_max: number | null;
  2983. created_at: string;
  2984. updated_at: string;
  2985. }
  2986. // Notification Provider types
  2987. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  2988. // How a Telegram provider collects the outcome verdict (#3046)
  2989. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  2990. export interface NotificationProvider {
  2991. id: number;
  2992. name: string;
  2993. provider_type: ProviderType;
  2994. enabled: boolean;
  2995. config: Record<string, unknown>;
  2996. attach_photo: boolean;
  2997. // Print lifecycle events
  2998. on_print_start: boolean;
  2999. on_print_complete: boolean;
  3000. on_print_failed: boolean;
  3001. on_print_stopped: boolean;
  3002. on_print_progress: boolean;
  3003. on_print_missing_spool_assignment: boolean;
  3004. on_billing_charge_failed: boolean;
  3005. // Printer status events
  3006. on_printer_offline: boolean;
  3007. on_printer_error: boolean;
  3008. on_ai_failure_detection: boolean;
  3009. on_filament_low: boolean;
  3010. on_maintenance_due: boolean;
  3011. // AMS environmental alarms (regular AMS)
  3012. on_ams_humidity_high: boolean;
  3013. on_ams_temperature_high: boolean;
  3014. on_ams_drying_suspended: boolean;
  3015. // AMS-HT environmental alarms
  3016. on_ams_ht_humidity_high: boolean;
  3017. on_ams_ht_temperature_high: boolean;
  3018. // Build plate detection
  3019. on_plate_not_empty: boolean;
  3020. on_plate_clear_required: boolean;
  3021. // Post-print outcome confirmation (#1898)
  3022. on_print_confirm_request: boolean;
  3023. telegram_verdict_mode: TelegramVerdictMode;
  3024. // Bed cooled
  3025. on_bed_cooled: boolean;
  3026. on_ha_sensor_alert: boolean;
  3027. on_location_ha_sensor_alert: boolean;
  3028. // First layer complete
  3029. on_first_layer_complete: boolean;
  3030. on_print_pause_upcoming: boolean;
  3031. on_app_message: boolean;
  3032. // Inventory stock alerts
  3033. on_stock_reorder_alert: boolean;
  3034. on_stock_break_alert: boolean;
  3035. // Print queue events
  3036. on_queue_job_added: boolean;
  3037. on_queue_job_assigned: boolean;
  3038. on_queue_job_started: boolean;
  3039. on_queue_job_waiting: boolean;
  3040. on_queue_job_skipped: boolean;
  3041. on_queue_job_failed: boolean;
  3042. on_queue_completed: boolean;
  3043. // Quiet hours
  3044. quiet_hours_enabled: boolean;
  3045. quiet_hours_start: string | null;
  3046. quiet_hours_end: string | null;
  3047. // Daily digest
  3048. daily_digest_enabled: boolean;
  3049. daily_digest_time: string | null;
  3050. // Printer filter
  3051. printer_id: number | null;
  3052. // Status tracking
  3053. last_success: string | null;
  3054. last_error: string | null;
  3055. last_error_at: string | null;
  3056. // Timestamps
  3057. created_at: string;
  3058. updated_at: string;
  3059. }
  3060. export interface NotificationProviderCreate {
  3061. name: string;
  3062. provider_type: ProviderType;
  3063. enabled?: boolean;
  3064. config: Record<string, unknown>;
  3065. attach_photo?: boolean;
  3066. // Print lifecycle events
  3067. on_print_start?: boolean;
  3068. on_print_complete?: boolean;
  3069. on_print_failed?: boolean;
  3070. on_print_stopped?: boolean;
  3071. on_print_progress?: boolean;
  3072. on_print_missing_spool_assignment?: boolean;
  3073. on_billing_charge_failed?: boolean;
  3074. // Printer status events
  3075. on_printer_offline?: boolean;
  3076. on_printer_error?: boolean;
  3077. on_ai_failure_detection?: boolean;
  3078. on_filament_low?: boolean;
  3079. on_maintenance_due?: boolean;
  3080. // AMS environmental alarms (regular AMS)
  3081. on_ams_humidity_high?: boolean;
  3082. on_ams_temperature_high?: boolean;
  3083. on_ams_drying_suspended?: boolean;
  3084. // AMS-HT environmental alarms
  3085. on_ams_ht_humidity_high?: boolean;
  3086. on_ams_ht_temperature_high?: boolean;
  3087. // Build plate detection
  3088. on_plate_not_empty?: boolean;
  3089. on_plate_clear_required?: boolean;
  3090. // Post-print outcome confirmation (#1898)
  3091. on_print_confirm_request?: boolean;
  3092. telegram_verdict_mode?: TelegramVerdictMode;
  3093. // Bed cooled
  3094. on_bed_cooled?: boolean;
  3095. on_ha_sensor_alert?: boolean;
  3096. on_location_ha_sensor_alert?: boolean;
  3097. // First layer complete
  3098. on_first_layer_complete?: boolean;
  3099. on_print_pause_upcoming?: boolean;
  3100. on_app_message?: boolean;
  3101. // Inventory stock alerts
  3102. on_stock_reorder_alert?: boolean;
  3103. on_stock_break_alert?: boolean;
  3104. // Print queue events
  3105. on_queue_job_added?: boolean;
  3106. on_queue_job_assigned?: boolean;
  3107. on_queue_job_started?: boolean;
  3108. on_queue_job_waiting?: boolean;
  3109. on_queue_job_skipped?: boolean;
  3110. on_queue_job_failed?: boolean;
  3111. on_queue_completed?: boolean;
  3112. // Quiet hours
  3113. quiet_hours_enabled?: boolean;
  3114. quiet_hours_start?: string | null;
  3115. quiet_hours_end?: string | null;
  3116. // Daily digest
  3117. daily_digest_enabled?: boolean;
  3118. daily_digest_time?: string | null;
  3119. // Printer filter
  3120. printer_id?: number | null;
  3121. }
  3122. export interface NotificationProviderUpdate {
  3123. name?: string;
  3124. provider_type?: ProviderType;
  3125. enabled?: boolean;
  3126. config?: Record<string, unknown>;
  3127. attach_photo?: boolean;
  3128. // Print lifecycle events
  3129. on_print_start?: boolean;
  3130. on_print_complete?: boolean;
  3131. on_print_failed?: boolean;
  3132. on_print_stopped?: boolean;
  3133. on_print_progress?: boolean;
  3134. on_print_missing_spool_assignment?: boolean;
  3135. on_billing_charge_failed?: boolean;
  3136. // Printer status events
  3137. on_printer_offline?: boolean;
  3138. on_printer_error?: boolean;
  3139. on_ai_failure_detection?: boolean;
  3140. on_filament_low?: boolean;
  3141. on_maintenance_due?: boolean;
  3142. // AMS environmental alarms (regular AMS)
  3143. on_ams_humidity_high?: boolean;
  3144. on_ams_temperature_high?: boolean;
  3145. on_ams_drying_suspended?: boolean;
  3146. // AMS-HT environmental alarms
  3147. on_ams_ht_humidity_high?: boolean;
  3148. on_ams_ht_temperature_high?: boolean;
  3149. // Build plate detection
  3150. on_plate_not_empty?: boolean;
  3151. on_plate_clear_required?: boolean;
  3152. // Post-print outcome confirmation (#1898)
  3153. on_print_confirm_request?: boolean;
  3154. telegram_verdict_mode?: TelegramVerdictMode;
  3155. // Bed cooled
  3156. on_bed_cooled?: boolean;
  3157. on_ha_sensor_alert?: boolean;
  3158. on_location_ha_sensor_alert?: boolean;
  3159. // First layer complete
  3160. on_first_layer_complete?: boolean;
  3161. on_print_pause_upcoming?: boolean;
  3162. on_app_message?: boolean;
  3163. // Inventory stock alerts
  3164. on_stock_reorder_alert?: boolean;
  3165. on_stock_break_alert?: boolean;
  3166. // Print queue events
  3167. on_queue_job_added?: boolean;
  3168. on_queue_job_assigned?: boolean;
  3169. on_queue_job_started?: boolean;
  3170. on_queue_job_waiting?: boolean;
  3171. on_queue_job_skipped?: boolean;
  3172. on_queue_job_failed?: boolean;
  3173. on_queue_completed?: boolean;
  3174. // Quiet hours
  3175. quiet_hours_enabled?: boolean;
  3176. quiet_hours_start?: string | null;
  3177. quiet_hours_end?: string | null;
  3178. // Daily digest
  3179. daily_digest_enabled?: boolean;
  3180. daily_digest_time?: string | null;
  3181. // Printer filter
  3182. printer_id?: number | null;
  3183. }
  3184. // GitHub Backup types
  3185. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3186. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3187. /** How many cloud accounts a backup would collect presets from. Counts only —
  3188. * with auth enabled the accounts belong to individual users, so the backup
  3189. * administrator sees how many, never whose. */
  3190. export interface CloudAccountCounts {
  3191. bambu: number;
  3192. orca: number;
  3193. }
  3194. export interface GitHubBackupConfig {
  3195. id: number;
  3196. repository_url: string;
  3197. has_token: boolean;
  3198. branch: string;
  3199. provider: GitProviderType;
  3200. allow_insecure_http: boolean;
  3201. schedule_enabled: boolean;
  3202. schedule_type: ScheduleType;
  3203. backup_kprofiles: boolean;
  3204. backup_cloud_profiles: boolean;
  3205. backup_settings: boolean;
  3206. backup_spools: boolean;
  3207. backup_archives: boolean;
  3208. enabled: boolean;
  3209. last_backup_at: string | null;
  3210. last_backup_status: string | null;
  3211. last_backup_message: string | null;
  3212. last_backup_commit_sha: string | null;
  3213. next_scheduled_run: string | null;
  3214. created_at: string;
  3215. updated_at: string;
  3216. }
  3217. export interface GitHubBackupConfigCreate {
  3218. repository_url: string;
  3219. access_token: string;
  3220. branch?: string;
  3221. provider?: GitProviderType;
  3222. allow_insecure_http?: boolean;
  3223. schedule_enabled?: boolean;
  3224. schedule_type?: ScheduleType;
  3225. backup_kprofiles?: boolean;
  3226. backup_cloud_profiles?: boolean;
  3227. backup_settings?: boolean;
  3228. backup_spools?: boolean;
  3229. backup_archives?: boolean;
  3230. enabled?: boolean;
  3231. }
  3232. export interface GitHubBackupLog {
  3233. id: number;
  3234. config_id: number;
  3235. started_at: string;
  3236. completed_at: string | null;
  3237. status: string;
  3238. trigger: string;
  3239. commit_sha: string | null;
  3240. files_changed: number;
  3241. error_message: string | null;
  3242. }
  3243. export interface GitHubBackupStatus {
  3244. configured: boolean;
  3245. enabled: boolean;
  3246. is_running: boolean;
  3247. restore_running: boolean;
  3248. progress: string | null;
  3249. last_backup_at: string | null;
  3250. last_backup_status: string | null;
  3251. next_scheduled_run: string | null;
  3252. }
  3253. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3254. // the backup collector never writes them, so there is nothing to restore.
  3255. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3256. export interface GitHubCommitInfo {
  3257. sha: string;
  3258. message: string;
  3259. author: string;
  3260. date: string;
  3261. }
  3262. export interface GitHubCommitListResponse {
  3263. success: boolean;
  3264. message: string;
  3265. branch: string;
  3266. commits: GitHubCommitInfo[];
  3267. }
  3268. /**
  3269. * Values the server interpolates into a translated note or preview detail.
  3270. * Kept to strings and numbers on purpose — anything richer would have to be
  3271. * formatted server-side and could not be translated.
  3272. */
  3273. export type GitHubRestoreParams = Record<string, string | number>;
  3274. export interface GitHubRestorePreviewCategory {
  3275. category: RestoreCategory;
  3276. available: boolean;
  3277. item_count: number;
  3278. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3279. detail: string | null;
  3280. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3281. detail_code: string | null;
  3282. detail_params: GitHubRestoreParams;
  3283. }
  3284. export interface GitHubRestorePreview {
  3285. success: boolean;
  3286. message: string;
  3287. ref: string;
  3288. commit: GitHubCommitInfo | null;
  3289. metadata_version: string | null;
  3290. categories: GitHubRestorePreviewCategory[];
  3291. }
  3292. export interface GitHubRestoreRequest {
  3293. ref?: string;
  3294. categories: RestoreCategory[];
  3295. overwrite_existing?: boolean;
  3296. }
  3297. /**
  3298. * One tally note, as a translation code plus its parameters (#2656).
  3299. *
  3300. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3301. * the code and supplies typed params, and the client renders
  3302. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3303. * A code the client does not know yet falls back to the English `message`
  3304. * rather than showing the raw key.
  3305. */
  3306. export interface GitHubRestoreNote {
  3307. code: string;
  3308. params: GitHubRestoreParams;
  3309. message: string;
  3310. }
  3311. export interface GitHubRestoreCategoryResult {
  3312. restored: number;
  3313. skipped: number;
  3314. failed: number;
  3315. notes: GitHubRestoreNote[];
  3316. }
  3317. export interface GitHubRestoreResponse {
  3318. success: boolean;
  3319. message: string;
  3320. log_id: number | null;
  3321. ref: string | null;
  3322. results: Record<string, GitHubRestoreCategoryResult>;
  3323. }
  3324. export interface LocalBackupStatus {
  3325. enabled: boolean;
  3326. schedule: string;
  3327. time: string;
  3328. retention: number;
  3329. path: string;
  3330. default_path: string;
  3331. is_running: boolean;
  3332. last_backup_at: string | null;
  3333. last_status: string | null;
  3334. last_message: string | null;
  3335. next_run: string | null;
  3336. timezone: string;
  3337. }
  3338. export interface LocalBackupFile {
  3339. filename: string;
  3340. size: number;
  3341. created_at: string;
  3342. }
  3343. /** Result of writing a probe file into the configured backup directory (#2544). */
  3344. export interface LocalBackupPathCheck {
  3345. writable: boolean;
  3346. path: string;
  3347. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3348. code: string;
  3349. /** Raw OS error, shown as-is under the translated explanation. */
  3350. detail: string | null;
  3351. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3352. remedy: string | null;
  3353. message: string;
  3354. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3355. warning: string | null;
  3356. }
  3357. export interface ObicoDetectionEvent {
  3358. printer_id: number;
  3359. task_name: string;
  3360. timestamp: string;
  3361. current_p: number;
  3362. score: number;
  3363. class: 'safe' | 'warning' | 'failure';
  3364. detections: number;
  3365. }
  3366. export interface ObicoStatus {
  3367. is_running: boolean;
  3368. last_error: string | null;
  3369. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3370. thresholds: { low: number; high: number };
  3371. history: ObicoDetectionEvent[];
  3372. enabled: boolean;
  3373. ml_url: string;
  3374. sensitivity: 'low' | 'medium' | 'high';
  3375. action: 'notify' | 'pause' | 'pause_and_off';
  3376. poll_interval: number;
  3377. external_url_configured: boolean;
  3378. }
  3379. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3380. export interface ObicoPrinterStatus {
  3381. enabled: boolean;
  3382. // null = all printers are monitored
  3383. monitored_printers: number[] | null;
  3384. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3385. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3386. last_error: string | null;
  3387. }
  3388. export interface ObicoTestConnection {
  3389. ok: boolean;
  3390. status_code: number | null;
  3391. body: string | null;
  3392. error: string | null;
  3393. // Whether the ML API accepted the token. null = not determined (the health
  3394. // check failed first, or the token probe itself errored).
  3395. auth_ok: boolean | null;
  3396. }
  3397. export interface GitHubTestConnectionResponse {
  3398. success: boolean;
  3399. message: string;
  3400. repo_name: string | null;
  3401. permissions: Record<string, boolean> | null;
  3402. // true = confirmed private, false = confirmed public/internal,
  3403. // null = could not determine. Backend rejects save unless true.
  3404. is_private: boolean | null;
  3405. }
  3406. export interface GitHubBackupTriggerResponse {
  3407. success: boolean;
  3408. message: string;
  3409. log_id: number | null;
  3410. commit_sha: string | null;
  3411. files_changed: number;
  3412. }
  3413. export interface NotificationTestRequest {
  3414. provider_type: ProviderType;
  3415. config: Record<string, unknown>;
  3416. attach_photo?: boolean;
  3417. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3418. provider_id?: number;
  3419. }
  3420. export interface NotificationTestResponse {
  3421. success: boolean;
  3422. message: string;
  3423. }
  3424. // Provider-specific config types for reference
  3425. export interface CallMeBotConfig {
  3426. phone: string;
  3427. apikey: string;
  3428. }
  3429. export interface NtfyConfig {
  3430. server?: string;
  3431. topic: string;
  3432. auth_token?: string | null;
  3433. }
  3434. export interface PushoverConfig {
  3435. user_key: string;
  3436. app_token: string;
  3437. priority?: number;
  3438. }
  3439. export interface NotifyConfig {
  3440. device_id: string;
  3441. token: string;
  3442. icon_url?: string;
  3443. group_type?: string;
  3444. live_activities?: boolean;
  3445. lock_screen_widgets?: boolean;
  3446. live_activity_privacy?: boolean;
  3447. live_activity_stage?: boolean;
  3448. live_activity_style?: 'bar' | 'segments' | 'none';
  3449. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3450. live_activity_button_url?: string;
  3451. live_activity_symbol?: string;
  3452. live_activity_tint?: string;
  3453. time_sensitive?: boolean;
  3454. }
  3455. export interface TelegramConfig {
  3456. bot_token: string;
  3457. chat_id: string;
  3458. }
  3459. export interface EmailConfig {
  3460. smtp_server: string;
  3461. smtp_port?: number;
  3462. username: string;
  3463. password: string;
  3464. from_email: string;
  3465. to_email: string;
  3466. use_tls?: boolean;
  3467. }
  3468. // Notification Template types
  3469. export interface NotificationTemplate {
  3470. id: number;
  3471. event_type: string;
  3472. name: string;
  3473. title_template: string;
  3474. body_template: string;
  3475. is_default: boolean;
  3476. created_at: string;
  3477. updated_at: string;
  3478. }
  3479. export interface NotificationTemplateUpdate {
  3480. title_template?: string;
  3481. body_template?: string;
  3482. }
  3483. export interface EventVariablesResponse {
  3484. event_type: string;
  3485. event_name: string;
  3486. variables: string[];
  3487. supports_photo: boolean;
  3488. }
  3489. export interface TemplatePreviewRequest {
  3490. event_type: string;
  3491. title_template: string;
  3492. body_template: string;
  3493. }
  3494. export interface TemplatePreviewResponse {
  3495. title: string;
  3496. body: string;
  3497. }
  3498. // Notification Log types
  3499. export interface NotificationLogEntry {
  3500. id: number;
  3501. provider_id: number;
  3502. provider_name: string | null;
  3503. provider_type: string | null;
  3504. event_type: string;
  3505. title: string;
  3506. message: string;
  3507. success: boolean;
  3508. error_message: string | null;
  3509. printer_id: number | null;
  3510. printer_name: string | null;
  3511. created_at: string;
  3512. }
  3513. export interface NotificationLogStats {
  3514. total: number;
  3515. success_count: number;
  3516. failure_count: number;
  3517. by_event_type: Record<string, number>;
  3518. by_provider: Record<string, number>;
  3519. }
  3520. // Spoolman types
  3521. export interface SpoolmanStatus {
  3522. enabled: boolean;
  3523. connected: boolean;
  3524. url: string | null;
  3525. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3526. }
  3527. export interface SpoolmanTagMigrationReport {
  3528. dry_run: boolean;
  3529. moved: number[];
  3530. already: number;
  3531. slot_ids: number;
  3532. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3533. }
  3534. export interface SkippedSpool {
  3535. location: string;
  3536. reason: string;
  3537. filament_type: string | null;
  3538. color: string | null;
  3539. }
  3540. export interface SpoolmanSyncResult {
  3541. success: boolean;
  3542. synced_count: number;
  3543. skipped_count: number;
  3544. skipped: SkippedSpool[];
  3545. errors: string[];
  3546. }
  3547. export interface UnlinkedSpool {
  3548. id: number;
  3549. filament_name: string | null;
  3550. filament_vendor: string | null;
  3551. filament_material: string | null;
  3552. filament_color_hex: string | null;
  3553. remaining_weight: number | null;
  3554. location: string | null;
  3555. }
  3556. export interface LinkedSpoolInfo {
  3557. id: number;
  3558. remaining_weight: number | null;
  3559. filament_weight: number | null;
  3560. }
  3561. export interface LinkedSpoolsMap {
  3562. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3563. }
  3564. export interface SpoolmanVendor {
  3565. id: number;
  3566. name: string;
  3567. }
  3568. export interface SpoolmanFilamentEntry {
  3569. id: number;
  3570. name: string;
  3571. material: string | null;
  3572. color_hex: string | null;
  3573. color_name: string | null;
  3574. weight: number | null;
  3575. spool_weight: number | null;
  3576. vendor: SpoolmanVendor | null;
  3577. }
  3578. // Inventory types
  3579. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3580. export type SpoolLabelTemplate =
  3581. | 'ams_holder_74x33'
  3582. | 'ams_holder_75x55'
  3583. | 'box_40x30'
  3584. | 'box_62x29'
  3585. | 'avery_5160'
  3586. | 'avery_l7160';
  3587. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3588. export const SPOOL_LABEL_FIELDS = [
  3589. 'brand',
  3590. 'material',
  3591. 'hex',
  3592. 'name',
  3593. 'location',
  3594. 'material_number',
  3595. 'temps',
  3596. 'weight',
  3597. 'note',
  3598. 'added',
  3599. 'qr',
  3600. 'spool_id',
  3601. ] as const;
  3602. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3603. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3604. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3605. 'brand',
  3606. 'material',
  3607. 'hex',
  3608. 'name',
  3609. 'location',
  3610. 'qr',
  3611. 'spool_id',
  3612. ];
  3613. export interface PrintSpoolLabelsRequest {
  3614. spool_ids: number[];
  3615. template: SpoolLabelTemplate;
  3616. monochrome: boolean;
  3617. starting_position: number;
  3618. fields?: SpoolLabelField[];
  3619. format?: 'pdf' | 'png';
  3620. dpi?: 203 | 300 | 600;
  3621. }
  3622. export interface PreviewSpoolLabelRequest {
  3623. spool_id: number;
  3624. template: SpoolLabelTemplate;
  3625. monochrome: boolean;
  3626. fields: SpoolLabelField[];
  3627. }
  3628. export interface InventorySpool {
  3629. id: number;
  3630. material: string;
  3631. subtype: string | null;
  3632. color_name: string | null;
  3633. // True when color_name was synthesised from subtype because Spoolman has no
  3634. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3635. // leave the input blank, so the user doesn't round-trip the synth value
  3636. // back to Spoolman as if it were a real user-set color_name (#1319).
  3637. color_name_is_synthesized?: boolean;
  3638. rgba: string | null;
  3639. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3640. extra_colors: string | null;
  3641. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3642. effect_type: string | null;
  3643. brand: string | null;
  3644. label_weight: number;
  3645. core_weight: number;
  3646. // Spoolman-backed inventory only: true when the spool has no tare of its
  3647. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3648. core_weight_is_inherited?: boolean;
  3649. core_weight_catalog_id: number | null;
  3650. weight_used: number;
  3651. // Anchor for the resettable "Total Consumed" display (#1390). The
  3652. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3653. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3654. // zeroes the counter without disturbing remaining. Optional for back-compat
  3655. // with rows from a pre-migration DB snapshot — default to 0.
  3656. weight_used_baseline?: number;
  3657. slicer_filament: string | null;
  3658. slicer_filament_name: string | null;
  3659. nozzle_temp_min: number | null;
  3660. nozzle_temp_max: number | null;
  3661. note: string | null;
  3662. added_full: boolean | null;
  3663. last_used: string | null;
  3664. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3665. // length ends, or set by hand. Temperature and hours are null when unknown.
  3666. last_dried_at?: string | null;
  3667. last_dried_temp?: number | null;
  3668. last_dried_hours?: number | null;
  3669. encode_time: string | null;
  3670. tag_uid: string | null;
  3671. tray_uuid: string | null;
  3672. data_origin: string | null;
  3673. tag_type: string | null;
  3674. archived_at: string | null;
  3675. created_at: string;
  3676. updated_at: string;
  3677. cost_per_kg: number | null;
  3678. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3679. // else its filament's. Display only; the form edits cost_per_kg.
  3680. effective_cost_per_kg?: number | null;
  3681. last_scale_weight: number | null;
  3682. last_weighed_at: string | null;
  3683. // User-defined category + per-spool low-stock threshold override (#729).
  3684. category: string | null;
  3685. low_stock_threshold_pct: number | null;
  3686. // Internal material / article number (#2870) — the purchasing identifier
  3687. // shared by all spools of the same product.
  3688. material_number: string | null;
  3689. k_profiles?: SpoolKProfile[];
  3690. storage_location?: string | null;
  3691. location_id?: number | null;
  3692. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3693. // vendor is the manufacturer, not the seller, so there is no mapping.
  3694. suppliers?: SpoolSupplierLink[];
  3695. }
  3696. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3697. /** Where filament is bought — distinct from brand (who made it). */
  3698. export interface Supplier {
  3699. id: number;
  3700. name: string;
  3701. website: string | null;
  3702. customer_number: string | null;
  3703. note: string | null;
  3704. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3705. spool_count: number;
  3706. created_at: string;
  3707. updated_at: string;
  3708. }
  3709. export interface SupplierInput {
  3710. name: string;
  3711. website?: string | null;
  3712. customer_number?: string | null;
  3713. note?: string | null;
  3714. }
  3715. /** One spool-to-supplier assignment as written by the spool dialog. */
  3716. export interface SpoolSupplierLinkInput {
  3717. supplier_id: number;
  3718. /** The supplier's own article number — NOT the internal material number. */
  3719. supplier_article_number?: string | null;
  3720. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3721. quoted_price_per_kg?: number | null;
  3722. /** Marks where this concrete spool was actually bought. */
  3723. is_purchase_source?: boolean;
  3724. }
  3725. export interface SpoolSupplierLink {
  3726. id: number;
  3727. supplier_id: number;
  3728. supplier_name: string;
  3729. supplier_article_number: string | null;
  3730. quoted_price_per_kg: number | null;
  3731. is_purchase_source: boolean;
  3732. }
  3733. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3734. export interface SupplierStats {
  3735. supplier_id: number;
  3736. supplier_name: string;
  3737. spool_count: number;
  3738. remaining_g: number;
  3739. consumed_g: number;
  3740. cost: number;
  3741. }
  3742. /** Per-material-number inventory aggregate (#2870). */
  3743. export interface MaterialNumberStats {
  3744. material_number: string;
  3745. spool_count: number;
  3746. remaining_g: number;
  3747. consumed_g: number;
  3748. cost: number;
  3749. }
  3750. export interface SpoolmanBulkCreateResult {
  3751. created: InventorySpool[];
  3752. requested_count: number;
  3753. failed_count: number;
  3754. }
  3755. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3756. /** One row's outcome from the import preview / real import. */
  3757. export interface CsvImportRow {
  3758. row_number: number;
  3759. status: 'valid' | 'error' | 'skipped';
  3760. reason: string | null;
  3761. material: string | null;
  3762. brand: string | null;
  3763. color_name: string | null;
  3764. rgba: string | null;
  3765. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3766. resolved_color: boolean;
  3767. /** The catalog match came from a different material's variant (no exact
  3768. * material match). Shown as a warning in the preview. */
  3769. cross_material_color: boolean;
  3770. /** An active spool with the same material+brand+color already exists.
  3771. * Informational only — the import still creates the row. */
  3772. duplicate_of_existing: boolean;
  3773. }
  3774. /** Dry-run preview: per-row classification, no rows written. */
  3775. export interface CsvImportPreview {
  3776. columns: string[];
  3777. total: number;
  3778. valid_count: number;
  3779. error_count: number;
  3780. skipped_count: number;
  3781. rows: CsvImportRow[];
  3782. warnings: string[];
  3783. }
  3784. /** Summary returned after a real (non-dry-run) import. */
  3785. export interface CsvImportResult {
  3786. created: number;
  3787. skipped: number;
  3788. errors: number;
  3789. error_rows: CsvImportRow[];
  3790. }
  3791. export interface SpoolUsageRecord {
  3792. id: number;
  3793. // null: the spool was deleted, its usage kept
  3794. spool_id: number | null;
  3795. printer_id: number | null;
  3796. print_name: string | null;
  3797. weight_used: number;
  3798. percent_used: number;
  3799. status: string;
  3800. cost: number | null;
  3801. created_at: string;
  3802. }
  3803. export interface SpoolKProfile {
  3804. id: number;
  3805. spool_id: number;
  3806. printer_id: number;
  3807. extruder: number;
  3808. nozzle_diameter: string;
  3809. nozzle_type: string | null;
  3810. k_value: number;
  3811. name: string | null;
  3812. cali_idx: number | null;
  3813. setting_id: string | null;
  3814. created_at: string;
  3815. }
  3816. export interface SpoolKProfileInput {
  3817. printer_id: number;
  3818. extruder?: number;
  3819. nozzle_diameter?: string;
  3820. nozzle_type?: string | null;
  3821. k_value: number;
  3822. name?: string | null;
  3823. cali_idx?: number | null;
  3824. setting_id?: string | null;
  3825. }
  3826. /**
  3827. * One per-printer-model override of a spool's slicer filament preset.
  3828. *
  3829. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3830. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3831. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3832. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3833. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3834. */
  3835. export interface SlotSpoolDefaults {
  3836. slicer_filament: string | null;
  3837. slicer_filament_name: string | null;
  3838. cali_idx: number | null;
  3839. k_value: number | null;
  3840. profile_name: string | null;
  3841. extruder: number | null;
  3842. nozzle_diameter: string;
  3843. }
  3844. export interface SpoolFilamentPresetInput {
  3845. printer_model: string;
  3846. nozzle_diameter: string;
  3847. slicer_filament: string | null;
  3848. slicer_filament_name: string | null;
  3849. }
  3850. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  3851. id: number;
  3852. spool_id: number;
  3853. created_at: string;
  3854. }
  3855. /**
  3856. * What a new spool of one product starts with (#1326): the slicer preset, the
  3857. * per-model preset overrides and the K profiles. `color_name` "" is the
  3858. * default for every colour of the product; one with a colour wins over it per
  3859. * preset and per hotend. Shared by both inventory modes.
  3860. */
  3861. export interface ProfileDefaultKey {
  3862. brand: string;
  3863. material: string;
  3864. subtype: string;
  3865. color_name: string;
  3866. }
  3867. export interface ProfileDefaultInput extends ProfileDefaultKey {
  3868. slicer_filament: string | null;
  3869. slicer_filament_name: string | null;
  3870. presets: SpoolFilamentPresetInput[];
  3871. k_profiles: SpoolKProfileInput[];
  3872. }
  3873. export interface ProfileDefault extends ProfileDefaultInput {
  3874. id: number;
  3875. updated_at: string;
  3876. }
  3877. /** Both levels of a product's default merged, as a create applies them. */
  3878. export interface ResolvedProfileDefault {
  3879. slicer_filament: string | null;
  3880. slicer_filament_name: string | null;
  3881. presets: SpoolFilamentPresetInput[];
  3882. k_profiles: SpoolKProfileInput[];
  3883. default_ids: number[];
  3884. }
  3885. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  3886. export interface SlotMaterial {
  3887. ams_id: number;
  3888. tray_id: number;
  3889. global_tray_id: number;
  3890. /** Opaque grouping key from the backend. Two slots back each other up under
  3891. * AMS Filament Backup only when both `material_key` and `extruder` match.
  3892. * Never parse it — the format belongs to the backend's identity rule. */
  3893. material_key: string;
  3894. remaining_g: number;
  3895. /** 0 = right / single nozzle, 1 = left. */
  3896. extruder: number;
  3897. /** How the bound spool should be *named* — display only, never matched on.
  3898. * The printer has no brand field and reports no sub-brand for a
  3899. * third-party spool, so this is the only place a slot's real identity
  3900. * exists. Null when the binding resolves to a spool we cannot describe. */
  3901. spool?: SlotSpoolIdentity | null;
  3902. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  3903. * which is charged at the default rate. Optional for an older backend. */
  3904. cost_per_kg?: number | null;
  3905. }
  3906. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  3907. export interface SlotSpoolIdentity {
  3908. brand: string | null;
  3909. material: string | null;
  3910. subtype: string | null;
  3911. color_name: string | null;
  3912. rgba: string | null;
  3913. /** Comma-separated hex stops for a multi-colour spool, and the effect
  3914. * overlay — the two things a tray record cannot carry, so a slot swatch
  3915. * can be drawn the way the inventory row draws it (#3159).
  3916. *
  3917. * Optional rather than required: the backend sends both keys on every
  3918. * binding, but a frontend running against an older one gets neither, and
  3919. * every reader here already falls back to a solid swatch. */
  3920. extra_colors?: string | null;
  3921. effect_type?: string | null;
  3922. }
  3923. export interface InventoryRemainResponse {
  3924. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  3925. inventory_remain_g: Record<string, number>;
  3926. /** Every inventory binding on the printer, with identity + extruder side. */
  3927. slot_materials: SlotMaterial[];
  3928. }
  3929. export interface SpoolAssignment {
  3930. id: number;
  3931. spool_id: number;
  3932. printer_id: number;
  3933. printer_name: string | null;
  3934. ams_id: number;
  3935. tray_id: number;
  3936. fingerprint_color: string | null;
  3937. fingerprint_type: string | null;
  3938. spool?: InventorySpool | null;
  3939. configured: boolean;
  3940. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  3941. created_at: string;
  3942. ams_label?: string | null; // User-defined friendly name for the AMS unit
  3943. }
  3944. export interface FilamentSkuSettings {
  3945. id: number;
  3946. material: string;
  3947. subtype: string | null;
  3948. brand: string | null;
  3949. color_name: string | null;
  3950. lead_time_days: number;
  3951. safety_margin_value: number;
  3952. safety_margin_unit: 'days' | 'g';
  3953. alerts_snoozed: boolean;
  3954. }
  3955. export interface ShoppingListItem {
  3956. id: number;
  3957. material: string;
  3958. subtype: string | null;
  3959. brand: string | null;
  3960. color_name: string | null;
  3961. quantity_spools: number;
  3962. note: string | null;
  3963. status: 'pending' | 'purchased' | 'received';
  3964. purchased_at: string | null;
  3965. added_at: string;
  3966. }
  3967. export interface ShoppingListItemCreate {
  3968. material: string;
  3969. subtype: string | null;
  3970. brand: string | null;
  3971. color_name: string | null;
  3972. quantity_spools: number;
  3973. note?: string | null;
  3974. }
  3975. // Update types
  3976. export interface VersionInfo {
  3977. version: string;
  3978. repo: string;
  3979. }
  3980. export interface UpdateCheckResult {
  3981. update_available: boolean;
  3982. current_version: string;
  3983. latest_version: string | null;
  3984. release_name?: string;
  3985. release_notes?: string;
  3986. release_url?: string;
  3987. published_at?: string;
  3988. error?: string;
  3989. message?: string;
  3990. is_docker?: boolean;
  3991. is_ha_addon?: boolean;
  3992. is_windows_installer?: boolean;
  3993. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  3994. installer_download_url?: string | null;
  3995. // Best-effort guess at the compose directory (#2664). Prefill only — the
  3996. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  3997. // that field falls back to this guess instead of resurrecting the old value.
  3998. compose_dir_detected?: string | null;
  3999. }
  4000. export interface UpdateStatus {
  4001. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4002. progress: number;
  4003. message: string;
  4004. error: string | null;
  4005. }
  4006. // Maintenance types
  4007. export interface MaintenanceType {
  4008. id: number;
  4009. name: string;
  4010. description: string | null;
  4011. default_interval_hours: number;
  4012. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4013. icon: string | null;
  4014. wiki_url: string | null; // Documentation link
  4015. is_system: boolean;
  4016. created_at: string;
  4017. }
  4018. export interface MaintenanceTypeCreate {
  4019. name: string;
  4020. description?: string | null;
  4021. default_interval_hours?: number;
  4022. interval_type?: 'hours' | 'days';
  4023. icon?: string | null;
  4024. wiki_url?: string | null;
  4025. }
  4026. export interface MaintenanceStatus {
  4027. id: number;
  4028. printer_id: number;
  4029. printer_name: string;
  4030. printer_model: string | null;
  4031. maintenance_type_id: number;
  4032. maintenance_type_name: string;
  4033. maintenance_type_icon: string | null;
  4034. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4035. enabled: boolean;
  4036. interval_hours: number; // For hours type: print hours; for days type: number of days
  4037. interval_type: 'hours' | 'days';
  4038. current_hours: number;
  4039. hours_since_maintenance: number;
  4040. hours_until_due: number;
  4041. days_since_maintenance: number | null; // For days type
  4042. days_until_due: number | null; // For days type
  4043. is_due: boolean;
  4044. is_warning: boolean;
  4045. last_performed_at: string | null;
  4046. }
  4047. export interface PrinterMaintenanceOverview {
  4048. printer_id: number;
  4049. printer_name: string;
  4050. printer_model: string | null;
  4051. total_print_hours: number;
  4052. maintenance_items: MaintenanceStatus[];
  4053. due_count: number;
  4054. warning_count: number;
  4055. }
  4056. // External Links (sidebar)
  4057. export interface ExternalLink {
  4058. id: number;
  4059. name: string;
  4060. url: string;
  4061. icon: string;
  4062. open_in_new_tab: boolean;
  4063. custom_icon: string | null;
  4064. sort_order: number;
  4065. created_at: string;
  4066. updated_at: string;
  4067. /** Count reported by the app the link points to, while it keeps reporting. */
  4068. badge_count?: number | null;
  4069. }
  4070. export interface ExternalLinkCreate {
  4071. name: string;
  4072. url: string;
  4073. icon: string;
  4074. open_in_new_tab?: boolean;
  4075. }
  4076. export interface ExternalLinkUpdate {
  4077. name?: string;
  4078. url?: string;
  4079. icon?: string;
  4080. open_in_new_tab?: boolean;
  4081. }
  4082. // Finance types
  4083. export interface CostCenterSummary {
  4084. id: number;
  4085. name: string;
  4086. is_private: boolean;
  4087. owner_user_id: number | null;
  4088. is_active: boolean;
  4089. total_balance: number;
  4090. total_budget: number | null;
  4091. monthly_budget: number | null;
  4092. budget_mode: 'none' | 'total' | 'monthly';
  4093. budget_limit: number | null;
  4094. budget_used: number | null;
  4095. budget_available: number | null;
  4096. can_print: boolean;
  4097. }
  4098. export interface CostCenterCreateRequest {
  4099. name: string;
  4100. total_budget?: number | null;
  4101. monthly_budget?: number | null;
  4102. is_active?: boolean;
  4103. }
  4104. export interface CostCenterBudgetUpdateRequest {
  4105. total_budget?: number | null;
  4106. monthly_budget?: number | null;
  4107. }
  4108. export interface CostCenterUpdateRequest {
  4109. name?: string;
  4110. is_active?: boolean;
  4111. }
  4112. export interface CostCenterMemberRequest {
  4113. user_id: number;
  4114. can_print?: boolean;
  4115. }
  4116. export interface CostCenterMemberResponse {
  4117. id: number;
  4118. cost_center_id: number;
  4119. user_id: number;
  4120. can_print: boolean;
  4121. created_at: string;
  4122. }
  4123. export interface CostCenterDetail extends CostCenterSummary {
  4124. members: CostCenterMemberResponse[];
  4125. }
  4126. export interface WalletBalance {
  4127. user_id: number;
  4128. balance: number;
  4129. currency: string;
  4130. updated_at: string | null;
  4131. }
  4132. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4133. export interface WalletTransaction {
  4134. id: number;
  4135. user_id: number | null; // null once the user is deleted
  4136. cost_center_id: number | null;
  4137. transaction_type: WalletTransactionType;
  4138. amount: number;
  4139. balance_after: number | null;
  4140. description: string | null;
  4141. created_by_user_id: number | null;
  4142. print_run_id: string | null;
  4143. print_archive_id: number | null;
  4144. print_queue_id: number | null;
  4145. created_at: string;
  4146. }
  4147. export interface WalletTransactionListResponse {
  4148. items: WalletTransaction[];
  4149. total: number;
  4150. limit: number;
  4151. offset: number;
  4152. }
  4153. export interface WalletAdjustmentRequest {
  4154. amount: number;
  4155. description?: string;
  4156. cost_center_id?: number | null;
  4157. }
  4158. export interface WalletAdjustmentResponse {
  4159. transaction: WalletTransaction;
  4160. balance: WalletBalance;
  4161. }
  4162. export interface TransactionEditRequest {
  4163. user_id?: number | null;
  4164. cost_center_id?: number | null;
  4165. amount?: number | null;
  4166. description?: string | null;
  4167. }
  4168. export interface ManualPrintRequest {
  4169. user_id: number;
  4170. cost_center_id: number;
  4171. amount: number;
  4172. description?: string | null;
  4173. created_at?: string | null;
  4174. }
  4175. // Permission type - all available permissions
  4176. export type Permission =
  4177. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4178. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4179. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4180. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4181. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4182. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4183. | 'queue:reorder' | 'queue:start_unreviewed'
  4184. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4185. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4186. | 'library:purge'
  4187. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4188. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4189. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4190. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4191. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4192. | 'camera:view'
  4193. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4194. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4195. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4196. | 'notification_templates:read' | 'notification_templates:update'
  4197. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4198. | 'discovery:scan'
  4199. | 'firmware:read' | 'firmware:update'
  4200. | 'ams_history:read'
  4201. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4202. | 'stats:read' | 'stats:filter_by_user'
  4203. | 'system:read'
  4204. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4205. | 'github:backup' | 'github:restore'
  4206. | 'cloud:auth' | 'orca_cloud:auth'
  4207. | 'makerworld:view' | 'makerworld:import'
  4208. | 'manyfold:view' | 'manyfold:import'
  4209. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4210. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4211. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4212. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4213. | 'websocket:connect';
  4214. // Group types
  4215. export interface GroupBrief {
  4216. id: number;
  4217. name: string;
  4218. }
  4219. export interface Group {
  4220. id: number;
  4221. name: string;
  4222. description: string | null;
  4223. permissions: Permission[];
  4224. is_system: boolean;
  4225. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4226. restrict_printers: boolean;
  4227. printer_ids: number[];
  4228. /** Matched against Printer.location, so printers added there later are included */
  4229. locations: string[];
  4230. user_count: number;
  4231. created_at: string;
  4232. updated_at: string;
  4233. }
  4234. export interface GroupDetail extends Group {
  4235. users: Array<{ id: number; username: string; is_active: boolean }>;
  4236. }
  4237. export interface GroupCreate {
  4238. name: string;
  4239. description?: string;
  4240. permissions: Permission[];
  4241. restrict_printers?: boolean;
  4242. printer_ids?: number[];
  4243. locations?: string[];
  4244. }
  4245. export interface GroupUpdate {
  4246. name?: string;
  4247. description?: string;
  4248. permissions?: Permission[];
  4249. restrict_printers?: boolean;
  4250. printer_ids?: number[];
  4251. locations?: string[];
  4252. }
  4253. export interface PermissionInfo {
  4254. value: Permission;
  4255. label: string;
  4256. }
  4257. export interface PermissionCategory {
  4258. name: string;
  4259. permissions: PermissionInfo[];
  4260. }
  4261. export interface PermissionsListResponse {
  4262. categories: PermissionCategory[];
  4263. all_permissions: Permission[];
  4264. }
  4265. // User email notification preferences
  4266. export interface UserEmailPreferences {
  4267. notify_print_start: boolean;
  4268. notify_print_complete: boolean;
  4269. notify_print_failed: boolean;
  4270. notify_print_stopped: boolean;
  4271. }
  4272. // Auth types
  4273. export interface LoginRequest {
  4274. username: string;
  4275. password: string;
  4276. }
  4277. export interface LoginResponse {
  4278. access_token?: string;
  4279. token_type?: string;
  4280. user?: UserResponse;
  4281. /** Set when 2FA verification is required before a full token is issued. */
  4282. requires_2fa?: boolean;
  4283. pre_auth_token?: string;
  4284. two_fa_methods?: string[];
  4285. }
  4286. export interface UserResponse {
  4287. id: number;
  4288. username: string;
  4289. email?: string;
  4290. role: string; // Deprecated, kept for backward compatibility
  4291. is_active: boolean;
  4292. is_admin: boolean; // Computed from role and group membership
  4293. auth_source: string; // "local" or "ldap"
  4294. groups: GroupBrief[];
  4295. permissions: Permission[]; // All permissions from groups
  4296. created_at: string;
  4297. }
  4298. /**
  4299. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4300. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4301. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4302. * name, so operators are not forced into the full listing to get one.
  4303. */
  4304. export interface UserSlim {
  4305. id: number;
  4306. username: string;
  4307. }
  4308. export interface UserCreate {
  4309. username: string;
  4310. password?: string; // Optional when advanced auth is enabled
  4311. email?: string;
  4312. role: string;
  4313. group_ids?: number[];
  4314. }
  4315. export interface UserUpdate {
  4316. username?: string;
  4317. password?: string;
  4318. email?: string;
  4319. role?: string;
  4320. is_active?: boolean;
  4321. group_ids?: number[];
  4322. }
  4323. export interface SetupRequest {
  4324. auth_enabled: boolean;
  4325. admin_username?: string;
  4326. admin_password?: string;
  4327. }
  4328. export interface ForgotPasswordRequest {
  4329. email: string;
  4330. }
  4331. export interface ForgotPasswordResponse {
  4332. message: string;
  4333. }
  4334. export interface ResetPasswordRequest {
  4335. user_id: number;
  4336. }
  4337. export interface ResetPasswordResponse {
  4338. message: string;
  4339. }
  4340. export interface SMTPSettings {
  4341. smtp_host: string;
  4342. smtp_port: number;
  4343. smtp_username?: string;
  4344. smtp_password?: string;
  4345. smtp_security: 'starttls' | 'ssl' | 'none';
  4346. smtp_auth_enabled: boolean;
  4347. smtp_from_email: string;
  4348. smtp_from_name: string;
  4349. }
  4350. // 2FA / MFA interfaces
  4351. export interface TwoFAStatus {
  4352. totp_enabled: boolean;
  4353. email_otp_enabled: boolean;
  4354. backup_codes_remaining: number;
  4355. }
  4356. export interface TOTPSetupResponse {
  4357. secret: string;
  4358. qr_code_b64: string;
  4359. issuer: string;
  4360. }
  4361. export interface TOTPEnableResponse {
  4362. message: string;
  4363. backup_codes: string[];
  4364. }
  4365. export interface BackupCodesResponse {
  4366. backup_codes: string[];
  4367. message: string;
  4368. }
  4369. export interface TwoFAVerifyRequest {
  4370. pre_auth_token: string;
  4371. code: string;
  4372. method: 'totp' | 'email' | 'backup';
  4373. }
  4374. /**
  4375. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4376. *
  4377. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4378. * can be distinguished from arbitrary strings at the type level. The brand
  4379. * is compile-time only; at runtime these are plain strings.
  4380. *
  4381. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4382. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4383. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4384. * that no external URL slips through.
  4385. */
  4386. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4387. // OIDC interfaces
  4388. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4389. * what the login page renders. The full provider, group sync config
  4390. * included, needs the admin-only /auth/oidc/providers/all. */
  4391. export interface OIDCProviderPublic {
  4392. id: number;
  4393. name: string;
  4394. has_icon: boolean;
  4395. is_autologin: boolean;
  4396. }
  4397. export interface OIDCProvider {
  4398. id: number;
  4399. name: string;
  4400. issuer_url: string;
  4401. client_id: string;
  4402. scopes: string;
  4403. is_enabled: boolean;
  4404. auto_create_users: boolean;
  4405. auto_link_existing_accounts: boolean;
  4406. email_claim: string;
  4407. require_email_verified: boolean;
  4408. // #3107 — group sync. Empty mapping = sync off (default).
  4409. group_claim?: string;
  4410. group_mapping?: Record<string, string>;
  4411. icon_url?: string | null;
  4412. default_group_id?: number | null;
  4413. // True when the backend has cached icon bytes for this provider.
  4414. // Login page / admin preview consume this via the proxy URL
  4415. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4416. // hotlinks the external icon URL — that would require loosening
  4417. // the strict img-src CSP. Required, not optional: the backend always
  4418. // includes this field in the response (Pydantic default-False is
  4419. // populated unconditionally in the route handler).
  4420. has_icon: boolean;
  4421. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4422. // straight to this provider on mount. At most one provider may carry this.
  4423. is_autologin: boolean;
  4424. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4425. // every boot. The API answers 409 to any write, so the settings UI must not
  4426. // offer edit/delete controls that cannot succeed. Optional so a response
  4427. // from an older backend still type-checks.
  4428. is_env_managed?: boolean;
  4429. }
  4430. export interface OIDCProviderCreate {
  4431. name: string;
  4432. issuer_url: string;
  4433. client_id: string;
  4434. client_secret: string;
  4435. scopes?: string;
  4436. is_enabled?: boolean;
  4437. auto_create_users?: boolean;
  4438. auto_link_existing_accounts?: boolean;
  4439. email_claim?: string;
  4440. require_email_verified?: boolean;
  4441. // #3107 — group sync. Omit both to leave them unchanged on update.
  4442. group_claim?: string;
  4443. group_mapping?: Record<string, string>;
  4444. icon_url?: string | null;
  4445. default_group_id?: number | null;
  4446. is_autologin?: boolean; // #1589
  4447. }
  4448. export interface OIDCLink {
  4449. id: number;
  4450. provider_id: number;
  4451. provider_name: string;
  4452. provider_email?: string | null;
  4453. created_at: string;
  4454. }
  4455. export interface TestSMTPRequest {
  4456. test_recipient: string;
  4457. // The form's settings, tested before they are saved. An empty password
  4458. // keeps the saved one.
  4459. smtp?: SMTPSettings;
  4460. }
  4461. export interface TestSMTPResponse {
  4462. success: boolean;
  4463. message: string;
  4464. }
  4465. export interface AdvancedAuthStatus {
  4466. advanced_auth_enabled: boolean;
  4467. smtp_configured: boolean;
  4468. // #1589: false hides the username/password form on the LoginPage; the env
  4469. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4470. // the recovery path remains visible.
  4471. local_login_enabled: boolean;
  4472. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4473. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4474. autologin_provider_id: number | null;
  4475. }
  4476. export interface LDAPStatus {
  4477. ldap_enabled: boolean;
  4478. ldap_configured: boolean;
  4479. }
  4480. export interface EncryptionRowCounts {
  4481. oidc_providers: number;
  4482. user_totp: number;
  4483. }
  4484. export interface EncryptionStatus {
  4485. key_configured: boolean;
  4486. key_source: 'env' | 'file' | 'generated' | 'none';
  4487. legacy_plaintext_rows: EncryptionRowCounts;
  4488. encrypted_rows: EncryptionRowCounts;
  4489. decryption_broken: boolean;
  4490. // B2: count of rows skipped during the last legacy re-encryption migration.
  4491. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4492. migration_error_count: number;
  4493. }
  4494. export interface LDAPTestRequest {
  4495. ldap_server_url?: string;
  4496. ldap_bind_dn?: string;
  4497. ldap_bind_password?: string;
  4498. ldap_search_base?: string;
  4499. ldap_user_filter?: string;
  4500. ldap_security?: string;
  4501. }
  4502. export interface LDAPTestResponse {
  4503. success: boolean;
  4504. message: string;
  4505. }
  4506. export interface LDAPSearchResult {
  4507. username: string;
  4508. email: string | null;
  4509. display_name: string | null;
  4510. dn: string;
  4511. already_provisioned: boolean;
  4512. }
  4513. export interface SetupResponse {
  4514. auth_enabled: boolean;
  4515. admin_created?: boolean;
  4516. }
  4517. export interface AuthStatus {
  4518. auth_enabled: boolean;
  4519. requires_setup: boolean;
  4520. }
  4521. // API functions
  4522. export interface QueueHistoryFilters {
  4523. printerId?: number | null;
  4524. status?: string;
  4525. location?: string;
  4526. }
  4527. export interface QueueHistoryParams extends QueueHistoryFilters {
  4528. sortBy?: 'date' | 'name' | 'printer';
  4529. // Flips the default order: newest first by date, A to Z by name or printer.
  4530. reverse?: boolean;
  4531. limit?: number;
  4532. offset?: number;
  4533. }
  4534. export interface QueueHistoryPage {
  4535. // The page in display order, then any other runs of the batches on it.
  4536. items: PrintQueueItem[];
  4537. total: number;
  4538. locations: string[];
  4539. }
  4540. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4541. const search = new URLSearchParams();
  4542. if (params.printerId) search.set('printer_id', String(params.printerId));
  4543. if (params.status) search.set('status', params.status);
  4544. if (params.location) search.set('location', params.location);
  4545. if (params.sortBy) search.set('sort_by', params.sortBy);
  4546. if (params.reverse) search.set('reverse', 'true');
  4547. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4548. if (params.offset) search.set('offset', String(params.offset));
  4549. return search;
  4550. }
  4551. // Per-printer reads that a page showing every printer makes once per printer,
  4552. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4553. // keeps its single-printer request for a lone id.
  4554. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4555. const printerStatusBatch = batched(
  4556. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4557. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4558. );
  4559. const slotPresetsBatch = batched(
  4560. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4561. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4562. );
  4563. const amsLabelsBatch = batched(
  4564. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4565. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4566. );
  4567. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4568. const cardPlugs = async (ids: number[]) =>
  4569. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4570. const smartPlugBatch = batched(
  4571. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4572. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4573. );
  4574. const scriptPlugsBatch = batched(
  4575. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4576. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4577. );
  4578. const haSensorReadingsBatch = batched(
  4579. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4580. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4581. );
  4582. const firmwareUpdateBatch = batched(
  4583. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4584. async (ids) =>
  4585. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4586. );
  4587. // One batcher per status asked for: the bulk route takes a single status list.
  4588. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4589. const printerQueueBatch = (status: string) => {
  4590. let batch = printerQueueBatches.get(status);
  4591. if (!batch) {
  4592. batch = batched(
  4593. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4594. async (ids) =>
  4595. byId(
  4596. await request<Record<string, PrintQueueItem[]>>(
  4597. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4598. ),
  4599. ),
  4600. );
  4601. printerQueueBatches.set(status, batch);
  4602. }
  4603. return batch;
  4604. };
  4605. const foldersByArchiveBatch = batched(
  4606. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4607. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4608. );
  4609. export const api = {
  4610. // Overlay branding
  4611. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4612. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4613. const response = await fetch(`${API_BASE}${endpoint}`, {
  4614. signal, cache: 'no-store',
  4615. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4616. });
  4617. if (response.status === 404) return null;
  4618. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4619. return response.blob();
  4620. },
  4621. uploadOverlayLogo: async (file: File): Promise<void> => {
  4622. const body = new FormData();
  4623. body.append('file', file);
  4624. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4625. method: 'POST', body,
  4626. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4627. });
  4628. if (!response.ok) {
  4629. const error = await response.json().catch(() => ({}));
  4630. const detail = error?.detail;
  4631. const message = typeof detail === 'string' ? detail : detail?.message;
  4632. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4633. }
  4634. },
  4635. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4636. // Authentication
  4637. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4638. setupAuth: (data: SetupRequest) =>
  4639. request<SetupResponse>('/auth/setup', {
  4640. method: 'POST',
  4641. body: JSON.stringify(data),
  4642. }),
  4643. login: (data: LoginRequest) =>
  4644. request<LoginResponse>('/auth/login', {
  4645. method: 'POST',
  4646. body: JSON.stringify(data),
  4647. }),
  4648. logout: () =>
  4649. request<{ message: string }>('/auth/logout', {
  4650. method: 'POST',
  4651. }),
  4652. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4653. disableAuth: () =>
  4654. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4655. method: 'POST',
  4656. }),
  4657. // Advanced Authentication
  4658. testSMTP: (data: TestSMTPRequest) =>
  4659. request<TestSMTPResponse>('/auth/smtp/test', {
  4660. method: 'POST',
  4661. body: JSON.stringify(data),
  4662. }),
  4663. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4664. saveSMTPSettings: (data: SMTPSettings) =>
  4665. request<{ message: string }>('/auth/smtp', {
  4666. method: 'POST',
  4667. body: JSON.stringify(data),
  4668. }),
  4669. enableAdvancedAuth: () =>
  4670. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4671. method: 'POST',
  4672. }),
  4673. disableAdvancedAuth: () =>
  4674. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4675. method: 'POST',
  4676. }),
  4677. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4678. // LDAP Authentication
  4679. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4680. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4681. // form: the settings being edited, tested before they are saved. An empty
  4682. // bind password keeps the saved one.
  4683. testLDAP: (form?: LDAPTestRequest) =>
  4684. request<LDAPTestResponse>('/auth/ldap/test', {
  4685. method: 'POST',
  4686. ...(form ? { body: JSON.stringify(form) } : {}),
  4687. }),
  4688. searchLDAPDirectory: (q: string) =>
  4689. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4690. provisionLDAPUser: (username: string) =>
  4691. request<UserResponse>('/auth/ldap/provision', {
  4692. method: 'POST',
  4693. body: JSON.stringify({ username }),
  4694. }),
  4695. forgotPassword: (data: ForgotPasswordRequest) =>
  4696. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4697. method: 'POST',
  4698. body: JSON.stringify(data),
  4699. }),
  4700. // H-6: Confirm password reset using the token from the emailed link
  4701. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4702. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4703. method: 'POST',
  4704. body: JSON.stringify({ token, new_password: newPassword }),
  4705. }),
  4706. resetUserPassword: (data: ResetPasswordRequest) =>
  4707. request<ResetPasswordResponse>('/auth/reset-password', {
  4708. method: 'POST',
  4709. body: JSON.stringify(data),
  4710. }),
  4711. // 2FA - status
  4712. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4713. // 2FA - TOTP
  4714. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4715. enableTOTP: (code: string) =>
  4716. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4717. method: 'POST',
  4718. body: JSON.stringify({ code }),
  4719. }),
  4720. disableTOTP: (code: string) =>
  4721. request<{ message: string }>('/auth/2fa/totp/disable', {
  4722. method: 'POST',
  4723. body: JSON.stringify({ code }),
  4724. }),
  4725. regenerateBackupCodes: (code: string) =>
  4726. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4727. method: 'POST',
  4728. body: JSON.stringify({ code }),
  4729. }),
  4730. // 2FA - Email OTP
  4731. // Step 1: send a verification code to the user's email (proof of possession)
  4732. enableEmailOTP: () =>
  4733. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4734. // Step 2: confirm with the code received by email
  4735. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4736. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4737. method: 'POST',
  4738. body: JSON.stringify({ setup_token, code }),
  4739. }),
  4740. // Disable requires account password for re-auth
  4741. disableEmailOTP: (password: string) =>
  4742. request<{ message: string }>('/auth/2fa/email/disable', {
  4743. method: 'POST',
  4744. body: JSON.stringify({ password }),
  4745. }),
  4746. sendEmailOTP: (preAuthToken: string) =>
  4747. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4748. method: 'POST',
  4749. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4750. }),
  4751. // 2FA - verify (completes login)
  4752. verify2FA: (data: TwoFAVerifyRequest) =>
  4753. request<LoginResponse>('/auth/2fa/verify', {
  4754. method: 'POST',
  4755. body: JSON.stringify(data),
  4756. }),
  4757. // 2FA - admin
  4758. // adminPassword: the calling admin's own password; null for an admin
  4759. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4760. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4761. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4762. method: 'DELETE',
  4763. body: JSON.stringify({ admin_password: adminPassword }),
  4764. }),
  4765. // OIDC providers (public list)
  4766. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4767. // OIDC providers (admin)
  4768. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4769. createOIDCProvider: (data: OIDCProviderCreate) =>
  4770. request<OIDCProvider>('/auth/oidc/providers', {
  4771. method: 'POST',
  4772. body: JSON.stringify(data),
  4773. }),
  4774. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4775. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4776. method: 'PUT',
  4777. body: JSON.stringify(data),
  4778. }),
  4779. deleteOIDCProvider: (id: number) =>
  4780. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4781. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4782. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4783. // so a future caller can't accidentally substitute an attacker-
  4784. // controlled URL where this is consumed.
  4785. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4786. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4787. deleteOIDCProviderIcon: (id: number) =>
  4788. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4789. refreshOIDCProviderIcon: (id: number) =>
  4790. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4791. // OIDC authorize URL
  4792. getOIDCAuthorizeUrl: (providerId: number) =>
  4793. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4794. // OIDC exchange token for JWT
  4795. exchangeOIDCToken: (oidcToken: string) =>
  4796. request<LoginResponse>('/auth/oidc/exchange', {
  4797. method: 'POST',
  4798. body: JSON.stringify({ oidc_token: oidcToken }),
  4799. }),
  4800. // OIDC links for current user
  4801. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4802. deleteOIDCLink: (providerId: number) =>
  4803. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4804. // Users
  4805. getUsers: () => request<UserResponse[]>('/users/'),
  4806. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4807. createUser: (data: UserCreate) =>
  4808. request<UserResponse>('/users/', {
  4809. method: 'POST',
  4810. body: JSON.stringify(data),
  4811. }),
  4812. updateUser: (id: number, data: UserUpdate) =>
  4813. request<UserResponse>(`/users/${id}`, {
  4814. method: 'PATCH',
  4815. body: JSON.stringify(data),
  4816. }),
  4817. deleteUser: (id: number, deleteItems: boolean = false) =>
  4818. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4819. method: 'DELETE',
  4820. }),
  4821. getUserItemsCount: (id: number) =>
  4822. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4823. changePassword: (currentPassword: string, newPassword: string) =>
  4824. request<{ message: string }>('/users/me/change-password', {
  4825. method: 'POST',
  4826. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4827. }),
  4828. // User Email Notifications
  4829. getUserEmailPreferences: () =>
  4830. request<UserEmailPreferences>('/user-notifications/preferences'),
  4831. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4832. request<UserEmailPreferences>('/user-notifications/preferences', {
  4833. method: 'PUT',
  4834. body: JSON.stringify(data),
  4835. }),
  4836. // Groups
  4837. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4838. getGroups: () => request<Group[]>('/groups/'),
  4839. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4840. createGroup: (data: GroupCreate) =>
  4841. request<Group>('/groups/', {
  4842. method: 'POST',
  4843. body: JSON.stringify(data),
  4844. }),
  4845. updateGroup: (id: number, data: GroupUpdate) =>
  4846. request<Group>(`/groups/${id}`, {
  4847. method: 'PATCH',
  4848. body: JSON.stringify(data),
  4849. }),
  4850. deleteGroup: (id: number) =>
  4851. request<void>(`/groups/${id}`, {
  4852. method: 'DELETE',
  4853. }),
  4854. // Printers
  4855. getPrinters: () => request<Printer[]>('/printers/'),
  4856. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  4857. createPrinter: (data: PrinterCreate) =>
  4858. request<Printer>('/printers/', {
  4859. method: 'POST',
  4860. body: JSON.stringify(data),
  4861. }),
  4862. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  4863. request<Printer>(`/printers/${id}`, {
  4864. method: 'PATCH',
  4865. body: JSON.stringify(data),
  4866. }),
  4867. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  4868. request<{ status: string; archives_deleted: boolean }>(
  4869. `/printers/${id}?delete_archives=${deleteArchives}`,
  4870. { method: 'DELETE' }
  4871. ),
  4872. getDeveloperModeWarnings: () =>
  4873. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  4874. getAvailableFilaments: (model: string, location?: string) => {
  4875. const params = new URLSearchParams({ model });
  4876. if (location) params.set('location', location);
  4877. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  4878. },
  4879. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  4880. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  4881. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  4882. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  4883. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  4884. deletePrinterLocations: (names: string[]) =>
  4885. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  4886. method: 'POST',
  4887. body: JSON.stringify({ names }),
  4888. }),
  4889. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  4890. request<{ moved: number }>('/printer-locations/assign', {
  4891. method: 'POST',
  4892. body: JSON.stringify({ printer_ids: printerIds, location }),
  4893. }),
  4894. getPrinterStatus: (id: number) => printerStatusBatch(id),
  4895. refreshPrinterStatus: (id: number) =>
  4896. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  4897. method: 'POST',
  4898. }),
  4899. connectPrinter: (id: number) =>
  4900. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  4901. method: 'POST',
  4902. }),
  4903. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  4904. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  4905. // `coalesced` is true when the frame came from a capture that was already
  4906. // running (Obico polling, a snapshot) rather than a connection this test
  4907. // opened — a single-reader camera is shared rather than opened twice, so
  4908. // the result is real but says nothing about reaching the camera just now.
  4909. // `live_view` is true when the tested camera is the one a viewer is
  4910. // watching: the answer comes from the live frame, not a test of its own.
  4911. // In the body: the URL may carry the camera login, and a query string
  4912. // ends up in the server's access log.
  4913. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  4914. `/printers/${printerId}/camera/external/test`,
  4915. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  4916. ),
  4917. // Print Control
  4918. stopPrint: (printerId: number) =>
  4919. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  4920. method: 'POST',
  4921. }),
  4922. pausePrint: (printerId: number) =>
  4923. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  4924. method: 'POST',
  4925. }),
  4926. resumePrint: (printerId: number) =>
  4927. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  4928. method: 'POST',
  4929. }),
  4930. clearPlate: (printerId: number) =>
  4931. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  4932. method: 'POST',
  4933. }),
  4934. // Get current print user (for reprint tracking - Issue #206)
  4935. getCurrentPrintUser: (printerId: number) =>
  4936. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  4937. // Print Speed Control
  4938. setPrintSpeed: (printerId: number, mode: number) =>
  4939. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  4940. method: 'POST',
  4941. }),
  4942. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  4943. request<{ success: boolean; message: string }>(
  4944. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  4945. { method: 'POST' }
  4946. ),
  4947. setBedTemperature: (printerId: number, target: number) =>
  4948. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  4949. method: 'POST',
  4950. }),
  4951. setChamberTemperature: (printerId: number, target: number) =>
  4952. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  4953. method: 'POST',
  4954. }),
  4955. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  4956. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  4957. method: 'POST',
  4958. }),
  4959. selectExtruder: (printerId: number, extruder: number) =>
  4960. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  4961. method: 'POST',
  4962. }),
  4963. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  4964. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  4965. method: 'POST',
  4966. }),
  4967. // Bed (Z-axis) jog
  4968. bedJog: (printerId: number, distance: number) =>
  4969. request<{ success: boolean; message: string }>(
  4970. `/printers/${printerId}/bed-jog?distance=${distance}`,
  4971. { method: 'POST' }
  4972. ),
  4973. xyJog: (printerId: number, x: number, y: number) =>
  4974. request<{ success: boolean; message: string }>(
  4975. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  4976. { method: 'POST' }
  4977. ),
  4978. extruderJog: (printerId: number, distance: number) =>
  4979. request<{ success: boolean; message: string }>(
  4980. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  4981. { method: 'POST' }
  4982. ),
  4983. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  4984. request<{ success: boolean; message: string }>(
  4985. `/printers/${printerId}/home-axes?axes=${axes}`,
  4986. { method: 'POST' }
  4987. ),
  4988. // Chamber Light Control
  4989. setChamberLight: (printerId: number, on: boolean) =>
  4990. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  4991. method: 'POST',
  4992. }),
  4993. // AMS Drying Control
  4994. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  4995. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  4996. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  4997. { method: 'POST' }
  4998. ),
  4999. stopDrying: (printerId: number, amsId: number) =>
  5000. request<{ status: string; ams_id: number }>(
  5001. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5002. { method: 'POST' }
  5003. ),
  5004. // Scheduled (delayed) drying runs (#2638)
  5005. createScheduledDrying: (data: {
  5006. printer_id: number;
  5007. ams_id: number;
  5008. temp: number;
  5009. duration_hours: number;
  5010. filament?: string;
  5011. rotate_tray?: boolean;
  5012. start_after: string | null;
  5013. }) =>
  5014. request<ScheduledDrying>('/scheduled-dryings', {
  5015. method: 'POST',
  5016. body: JSON.stringify(data),
  5017. }),
  5018. // Omit printerId for the whole fleet in one request; the printer cards share
  5019. // that single query rather than each polling for its own id.
  5020. listScheduledDryings: (printerId?: number) =>
  5021. request<ScheduledDrying[]>(
  5022. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5023. ),
  5024. cancelScheduledDrying: (id: number) =>
  5025. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5026. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5027. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5028. request<{ success: boolean; ams_filament_backup: boolean }>(
  5029. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5030. { method: 'POST' }
  5031. ),
  5032. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5033. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5034. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5035. // so internal and Spoolman modes both work uniformly.
  5036. getInventoryRemain: (printerId: number) =>
  5037. request<InventoryRemainResponse>(
  5038. `/printers/${printerId}/inventory-remain`,
  5039. ),
  5040. // Skip Objects
  5041. getPrintableObjects: (printerId: number) =>
  5042. request<{
  5043. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5044. total: number;
  5045. skipped_count: number;
  5046. is_printing: boolean;
  5047. bbox_all: [number, number, number, number] | null;
  5048. }>(`/printers/${printerId}/print/objects`),
  5049. skipObjects: (printerId: number, objectIds: number[]) =>
  5050. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5051. `/printers/${printerId}/print/skip-objects`,
  5052. {
  5053. method: 'POST',
  5054. body: JSON.stringify(objectIds),
  5055. }
  5056. ),
  5057. // HMS Errors
  5058. clearHMSErrors: (printerId: number) =>
  5059. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5060. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5061. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5062. method: 'POST',
  5063. body: JSON.stringify(data),
  5064. }),
  5065. // AMS Control
  5066. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5067. request<{ success: boolean; message: string }>(
  5068. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5069. { method: 'POST' }
  5070. ),
  5071. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 128-135 for an
  5072. // AMS-HT (its unit id), 254 for external spool.
  5073. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5074. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5075. // inlet rather than a hotend, so the firmware cannot work the target out and
  5076. // drops the command. Omit it everywhere else, as BambuStudio does.
  5077. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5078. request<{ success: boolean; message: string }>(
  5079. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5080. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5081. { method: 'POST' }
  5082. ),
  5083. // Unload filament. trayId names the slot to unload, which is what tells a
  5084. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5085. // whatever the printer's single tray_now field names.
  5086. unloadAms: (printerId: number, trayId?: number) =>
  5087. request<{ success: boolean; message: string }>(
  5088. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5089. { method: 'POST' }
  5090. ),
  5091. // MQTT Debug Logging
  5092. enableMQTTLogging: (printerId: number) =>
  5093. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5094. method: 'POST',
  5095. }),
  5096. disableMQTTLogging: (printerId: number) =>
  5097. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5098. method: 'POST',
  5099. }),
  5100. getMQTTLogs: (printerId: number) =>
  5101. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5102. clearMQTTLogs: (printerId: number) =>
  5103. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5104. method: 'DELETE',
  5105. }),
  5106. // Printer File Manager
  5107. getPrinterFiles: (printerId: number, path = '/') =>
  5108. request<{
  5109. path: string;
  5110. files: Array<{
  5111. name: string;
  5112. is_directory: boolean;
  5113. size: number;
  5114. path: string;
  5115. mtime?: string;
  5116. }>;
  5117. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5118. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5119. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5120. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5121. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5122. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5123. getPrinterFilePlates: (printerId: number, path: string) =>
  5124. request<{
  5125. printer_id: number;
  5126. path: string;
  5127. filename: string;
  5128. plates: Array<{
  5129. index: number;
  5130. name: string | null;
  5131. objects: string[];
  5132. has_thumbnail: boolean;
  5133. thumbnail_url: string | null;
  5134. print_time_seconds: number | null;
  5135. filament_used_grams: number | null;
  5136. filaments: Array<{
  5137. slot_id: number;
  5138. type: string;
  5139. color: string;
  5140. used_grams: number;
  5141. used_meters: number;
  5142. }>;
  5143. }>;
  5144. is_multi_plate: boolean;
  5145. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5146. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5147. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5148. downloadPrinterFilesAsZip: async (
  5149. printerId: number,
  5150. paths: string[],
  5151. sizes: Record<string, number>,
  5152. filename = 'printer-files.zip',
  5153. asZip = true,
  5154. signal?: AbortSignal,
  5155. onProgress?: (completed: number, total: number) => void,
  5156. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5157. type JobStatus = {
  5158. job_id: string;
  5159. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5160. requested: number;
  5161. successful: number;
  5162. failed: number;
  5163. token: string | null;
  5164. message: string | null;
  5165. };
  5166. let jobId: string | null = null;
  5167. try {
  5168. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5169. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5170. method: 'POST',
  5171. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5172. signal,
  5173. });
  5174. jobId = status.job_id;
  5175. let polls = 0;
  5176. while (status.state === 'queued' || status.state === 'preparing') {
  5177. onProgress?.(status.successful + status.failed, status.requested);
  5178. // Small selections finish in the first seconds, so poll quickly there.
  5179. // A large one runs for up to half an hour, where half-second polling is
  5180. // thousands of requests that each re-check the caller's credentials.
  5181. const delay = polls < 10 ? 500 : 2000;
  5182. polls += 1;
  5183. await new Promise<void>((resolve, reject) => {
  5184. if (signal?.aborted) {
  5185. reject(new DOMException('Download cancelled', 'AbortError'));
  5186. return;
  5187. }
  5188. const onAbort = () => {
  5189. window.clearTimeout(timer);
  5190. reject(new DOMException('Download cancelled', 'AbortError'));
  5191. };
  5192. const timer = window.setTimeout(() => {
  5193. signal?.removeEventListener('abort', onAbort);
  5194. resolve();
  5195. }, delay);
  5196. signal?.addEventListener('abort', onAbort, { once: true });
  5197. });
  5198. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5199. }
  5200. onProgress?.(status.successful + status.failed, status.requested);
  5201. if (status.state !== 'ready' || !status.token) {
  5202. throw new Error(status.message || (status.state === 'cancelled'
  5203. ? 'Download cancelled'
  5204. : 'Printer download preparation failed'));
  5205. }
  5206. const link = document.createElement('a');
  5207. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5208. link.download = filename;
  5209. document.body.appendChild(link);
  5210. link.click();
  5211. link.remove();
  5212. return {
  5213. requested: status.requested,
  5214. successful: status.successful,
  5215. failed: status.failed,
  5216. };
  5217. } catch (error) {
  5218. if (jobId) {
  5219. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5220. }
  5221. throw error;
  5222. }
  5223. },
  5224. deletePrinterFile: (printerId: number, path: string) =>
  5225. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5226. method: 'DELETE',
  5227. }),
  5228. getPrinterStorage: (printerId: number) =>
  5229. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5230. // Archives
  5231. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5232. const params = new URLSearchParams();
  5233. if (printerId) params.set('printer_id', String(printerId));
  5234. if (projectId) params.set('project_id', String(projectId));
  5235. params.set('limit', String(limit));
  5236. params.set('offset', String(offset));
  5237. if (dateFrom) params.set('date_from', dateFrom);
  5238. if (dateTo) params.set('date_to', dateTo);
  5239. addDayZone(params);
  5240. return request<Archive[]>(`/archives/?${params}`);
  5241. },
  5242. // Latest archive of every printer in one request, for the printer cards.
  5243. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5244. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5245. const params = new URLSearchParams();
  5246. if (dateFrom) params.set('date_from', dateFrom);
  5247. if (dateTo) params.set('date_to', dateTo);
  5248. addDayZone(params);
  5249. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5250. const qs = params.toString();
  5251. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5252. },
  5253. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  5254. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5255. /**
  5256. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5257. * related queue items that will be removed along with the archive AND how
  5258. * many are currently printing (server 409s on delete if > 0).
  5259. */
  5260. getArchiveDeleteImpact: (id: number) =>
  5261. request<{ related_queue_items: number; currently_printing: number }>(
  5262. `/archives/${id}/delete-impact`
  5263. ),
  5264. getNo3MFWarning: () =>
  5265. request<{
  5266. has_fallback: boolean;
  5267. reason:
  5268. | 'ftps_cooloff'
  5269. | 'ftp_transfer_failed'
  5270. | 'internal_storage'
  5271. | 'no_external_storage'
  5272. | 'internal_history'
  5273. | null;
  5274. }>(
  5275. '/archives/no-3mf-warning',
  5276. ),
  5277. updateArchive: (id: number, data: {
  5278. printer_id?: number | null;
  5279. project_id?: number | null;
  5280. print_name?: string;
  5281. is_favorite?: boolean;
  5282. tags?: string;
  5283. notes?: string;
  5284. cost?: number;
  5285. failure_reason?: string | null;
  5286. status?: string;
  5287. quantity?: number;
  5288. external_url?: string | null;
  5289. filament_used_grams?: number | null;
  5290. // Post-print outcome verdict (#1898); null clears it
  5291. user_verdict?: 'good' | 'reject' | null;
  5292. // Which surface answered. The backend only accepts the sources a client
  5293. // can honestly claim and defaults to 'api' when none is given.
  5294. user_verdict_source?: 'dialog' | 'printer_card';
  5295. }) =>
  5296. request<Archive>(`/archives/${id}`, {
  5297. method: 'PATCH',
  5298. body: JSON.stringify(data),
  5299. }),
  5300. toggleFavorite: (id: number) =>
  5301. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5302. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5303. // from listings, but its filament / time / cost / energy contribution
  5304. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5305. // row from statistics too.
  5306. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5307. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5308. // ========== Archive auto-purge (#1008 follow-up) ==========
  5309. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5310. request<ArchivePurgePreview>(
  5311. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5312. ),
  5313. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5314. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5315. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5316. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5317. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5318. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5319. method: 'POST',
  5320. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5321. }),
  5322. getArchivePurgeSettings: () =>
  5323. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5324. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5325. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5326. method: 'PUT',
  5327. body: JSON.stringify(body),
  5328. }),
  5329. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5330. const params = new URLSearchParams();
  5331. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5332. if (options?.dateTo) params.set('date_to', options.dateTo);
  5333. addDayZone(params);
  5334. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5335. const qs = params.toString();
  5336. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5337. },
  5338. // Tag management
  5339. getTags: () => request<TagInfo[]>('/archives/tags'),
  5340. renameTag: (oldName: string, newName: string) =>
  5341. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5342. method: 'PUT',
  5343. body: JSON.stringify({ new_name: newName }),
  5344. }),
  5345. deleteTag: (name: string) =>
  5346. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5347. method: 'DELETE',
  5348. }),
  5349. recalculateCosts: () =>
  5350. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  5351. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5352. const params = new URLSearchParams();
  5353. if (options?.days) params.set('days', String(options.days));
  5354. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5355. if (options?.dateTo) params.set('date_to', options.dateTo);
  5356. addDayZone(params);
  5357. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5358. if (options?.projectId) params.set('project_id', String(options.projectId));
  5359. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5360. const qs = params.toString();
  5361. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5362. },
  5363. compareArchives: (archiveIds: number[]) =>
  5364. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5365. exportArchives: async (options?: {
  5366. format?: 'csv' | 'xlsx';
  5367. fields?: string[];
  5368. printerId?: number;
  5369. projectId?: number;
  5370. status?: string;
  5371. dateFrom?: string;
  5372. dateTo?: string;
  5373. search?: string;
  5374. }): Promise<{ blob: Blob; filename: string }> => {
  5375. const params = new URLSearchParams();
  5376. if (options?.format) params.set('format', options.format);
  5377. if (options?.fields) params.set('fields', options.fields.join(','));
  5378. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5379. if (options?.projectId) params.set('project_id', String(options.projectId));
  5380. if (options?.status) params.set('status', options.status);
  5381. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5382. if (options?.dateTo) params.set('date_to', options.dateTo);
  5383. addDayZone(params);
  5384. if (options?.search) params.set('search', options.search);
  5385. const headers: Record<string, string> = {};
  5386. if (authToken) {
  5387. headers['Authorization'] = `Bearer ${authToken}`;
  5388. }
  5389. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5390. if (!response.ok) {
  5391. const error = await response.json().catch(() => ({}));
  5392. throw new Error(error.detail || `HTTP ${response.status}`);
  5393. }
  5394. const contentDisposition = response.headers.get('Content-Disposition');
  5395. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5396. if (contentDisposition) {
  5397. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5398. if (match) filename = match[1];
  5399. }
  5400. const blob = await response.blob();
  5401. return { blob, filename };
  5402. },
  5403. exportStats: async (options?: {
  5404. format?: 'csv' | 'xlsx';
  5405. days?: number;
  5406. printerId?: number;
  5407. projectId?: number;
  5408. createdById?: number;
  5409. }): Promise<{ blob: Blob; filename: string }> => {
  5410. const params = new URLSearchParams();
  5411. if (options?.format) params.set('format', options.format);
  5412. if (options?.days) params.set('days', String(options.days));
  5413. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5414. if (options?.projectId) params.set('project_id', String(options.projectId));
  5415. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5416. const headers: Record<string, string> = {};
  5417. if (authToken) {
  5418. headers['Authorization'] = `Bearer ${authToken}`;
  5419. }
  5420. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5421. if (!response.ok) {
  5422. const error = await response.json().catch(() => ({}));
  5423. throw new Error(error.detail || `HTTP ${response.status}`);
  5424. }
  5425. const contentDisposition = response.headers.get('Content-Disposition');
  5426. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5427. if (contentDisposition) {
  5428. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5429. if (match) filename = match[1];
  5430. }
  5431. const blob = await response.blob();
  5432. return { blob, filename };
  5433. },
  5434. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5435. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5436. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5437. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5438. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5439. const headers: Record<string, string> = {};
  5440. if (authToken) {
  5441. headers['Authorization'] = `Bearer ${authToken}`;
  5442. }
  5443. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5444. if (!response.ok) {
  5445. const error = await response.json().catch(() => ({}));
  5446. throw new Error(error.detail || `HTTP ${response.status}`);
  5447. }
  5448. const disposition = response.headers.get('Content-Disposition');
  5449. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5450. const blob = await response.blob();
  5451. const url = window.URL.createObjectURL(blob);
  5452. const a = document.createElement('a');
  5453. a.href = url;
  5454. a.download = downloadFilename;
  5455. document.body.appendChild(a);
  5456. a.click();
  5457. document.body.removeChild(a);
  5458. window.URL.revokeObjectURL(url);
  5459. },
  5460. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5461. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5462. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5463. const prepared = await request<{ token: string; filename: string }>(
  5464. `/archives/${id}/media-download-token`,
  5465. { method: 'POST' },
  5466. );
  5467. const link = document.createElement('a');
  5468. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5469. link.download = filename;
  5470. document.body.appendChild(link);
  5471. link.click();
  5472. link.remove();
  5473. },
  5474. getArchivePrinterMedia: (id: number) =>
  5475. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5476. scanArchiveTimelapse: (id: number) =>
  5477. request<{
  5478. status: string;
  5479. message: string;
  5480. filename?: string;
  5481. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5482. }>(`/archives/${id}/timelapse/scan`, {
  5483. method: 'POST',
  5484. }),
  5485. selectArchiveTimelapse: (id: number, filename: string) =>
  5486. request<{ status: string; message: string; filename: string }>(
  5487. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5488. { method: 'POST' }
  5489. ),
  5490. deleteArchiveTimelapse: (id: number) =>
  5491. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5492. method: 'DELETE',
  5493. }),
  5494. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5495. const formData = new FormData();
  5496. formData.append('file', file);
  5497. const headers: Record<string, string> = {};
  5498. if (authToken) {
  5499. headers['Authorization'] = `Bearer ${authToken}`;
  5500. }
  5501. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5502. method: 'POST',
  5503. headers,
  5504. body: formData,
  5505. });
  5506. if (!response.ok) {
  5507. const error = await response.json().catch(() => ({}));
  5508. throw new Error(error.detail || `HTTP ${response.status}`);
  5509. }
  5510. return response.json();
  5511. },
  5512. // Timelapse Editor
  5513. getTimelapseInfo: (archiveId: number) =>
  5514. request<{
  5515. duration: number;
  5516. width: number;
  5517. height: number;
  5518. fps: number;
  5519. codec: string;
  5520. file_size: number;
  5521. has_audio: boolean;
  5522. }>(`/archives/${archiveId}/timelapse/info`),
  5523. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5524. request<{
  5525. thumbnails: string[];
  5526. timestamps: number[];
  5527. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5528. processTimelapse: async (
  5529. archiveId: number,
  5530. params: {
  5531. trimStart?: number;
  5532. trimEnd?: number;
  5533. speed?: number;
  5534. /** Music volume, 0 to 1. */
  5535. audioVolume?: number;
  5536. saveMode: 'replace' | 'new';
  5537. outputFilename?: string;
  5538. },
  5539. audioFile?: File
  5540. ): Promise<TimelapseJob> => {
  5541. const formData = new FormData();
  5542. formData.append('trim_start', String(params.trimStart ?? 0));
  5543. if (params.trimEnd !== undefined) {
  5544. formData.append('trim_end', String(params.trimEnd));
  5545. }
  5546. formData.append('speed', String(params.speed ?? 1));
  5547. if (params.audioVolume !== undefined) {
  5548. formData.append('audio_volume', String(params.audioVolume));
  5549. }
  5550. formData.append('save_mode', params.saveMode);
  5551. if (params.outputFilename) {
  5552. formData.append('output_filename', params.outputFilename);
  5553. }
  5554. if (audioFile) {
  5555. formData.append('audio', audioFile);
  5556. }
  5557. const headers: Record<string, string> = {};
  5558. if (authToken) {
  5559. headers['Authorization'] = `Bearer ${authToken}`;
  5560. }
  5561. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5562. method: 'POST',
  5563. headers,
  5564. body: formData,
  5565. });
  5566. if (!response.ok) {
  5567. const error = await response.json().catch(() => ({}));
  5568. throw new Error(error.detail || `HTTP ${response.status}`);
  5569. }
  5570. return response.json();
  5571. },
  5572. // The archive's running or last re-encode; null when there has been none.
  5573. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5574. try {
  5575. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5576. } catch (error) {
  5577. if (error instanceof ApiError && error.status === 404) return null;
  5578. throw error;
  5579. }
  5580. },
  5581. cancelTimelapseJob: (archiveId: number) =>
  5582. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5583. // Photos
  5584. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5585. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5586. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5587. const formData = new FormData();
  5588. formData.append('file', file);
  5589. const headers: Record<string, string> = {};
  5590. if (authToken) {
  5591. headers['Authorization'] = `Bearer ${authToken}`;
  5592. }
  5593. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5594. headers,
  5595. method: 'POST',
  5596. body: formData,
  5597. });
  5598. if (!response.ok) {
  5599. const error = await response.json().catch(() => ({}));
  5600. throw new Error(error.detail || `HTTP ${response.status}`);
  5601. }
  5602. return response.json();
  5603. },
  5604. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5605. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5606. method: 'DELETE',
  5607. }),
  5608. // Source 3MF (original slicer project file)
  5609. getSource3mfDownloadUrl: (archiveId: number) =>
  5610. `${API_BASE}/archives/${archiveId}/source`,
  5611. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5612. const headers: Record<string, string> = {};
  5613. if (authToken) {
  5614. headers['Authorization'] = `Bearer ${authToken}`;
  5615. }
  5616. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5617. if (!response.ok) {
  5618. const error = await response.json().catch(() => ({}));
  5619. throw new Error(error.detail || `HTTP ${response.status}`);
  5620. }
  5621. const disposition = response.headers.get('Content-Disposition');
  5622. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5623. const blob = await response.blob();
  5624. const url = window.URL.createObjectURL(blob);
  5625. const a = document.createElement('a');
  5626. a.href = url;
  5627. a.download = filename;
  5628. document.body.appendChild(a);
  5629. a.click();
  5630. document.body.removeChild(a);
  5631. window.URL.revokeObjectURL(url);
  5632. },
  5633. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5634. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5635. const safe = filename.replace(/[/\\?#]/g, '_');
  5636. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5637. },
  5638. createSourceSlicerToken: (archiveId: number) =>
  5639. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5640. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5641. const safe = filename.replace(/[/\\?#]/g, '_');
  5642. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5643. },
  5644. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5645. const formData = new FormData();
  5646. formData.append('file', file);
  5647. const headers: Record<string, string> = {};
  5648. if (authToken) {
  5649. headers['Authorization'] = `Bearer ${authToken}`;
  5650. }
  5651. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5652. method: 'POST',
  5653. headers,
  5654. body: formData,
  5655. });
  5656. if (!response.ok) {
  5657. const error = await response.json().catch(() => ({}));
  5658. throw new Error(error.detail || `HTTP ${response.status}`);
  5659. }
  5660. return response.json();
  5661. },
  5662. deleteSource3mf: (archiveId: number) =>
  5663. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5664. method: 'DELETE',
  5665. }),
  5666. // F3D (Fusion 360 design file)
  5667. downloadF3d: async (archiveId: number): Promise<void> => {
  5668. const headers: Record<string, string> = {};
  5669. if (authToken) {
  5670. headers['Authorization'] = `Bearer ${authToken}`;
  5671. }
  5672. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5673. if (!response.ok) {
  5674. const error = await response.json().catch(() => ({}));
  5675. throw new Error(error.detail || `HTTP ${response.status}`);
  5676. }
  5677. const disposition = response.headers.get('Content-Disposition');
  5678. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5679. const blob = await response.blob();
  5680. const url = window.URL.createObjectURL(blob);
  5681. const a = document.createElement('a');
  5682. a.href = url;
  5683. a.download = filename;
  5684. document.body.appendChild(a);
  5685. a.click();
  5686. document.body.removeChild(a);
  5687. window.URL.revokeObjectURL(url);
  5688. },
  5689. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5690. const formData = new FormData();
  5691. formData.append('file', file);
  5692. const headers: Record<string, string> = {};
  5693. if (authToken) {
  5694. headers['Authorization'] = `Bearer ${authToken}`;
  5695. }
  5696. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5697. method: 'POST',
  5698. headers,
  5699. body: formData,
  5700. });
  5701. if (!response.ok) {
  5702. const error = await response.json().catch(() => ({}));
  5703. throw new Error(error.detail || `HTTP ${response.status}`);
  5704. }
  5705. return response.json();
  5706. },
  5707. deleteF3d: (archiveId: number) =>
  5708. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5709. method: 'DELETE',
  5710. }),
  5711. // QR Code
  5712. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5713. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5714. getArchiveCapabilities: (id: number) =>
  5715. request<{
  5716. has_model: boolean;
  5717. has_gcode: boolean;
  5718. has_source: boolean;
  5719. build_volume: { x: number; y: number; z: number };
  5720. filament_colors: string[];
  5721. }>(`/archives/${id}/capabilities`),
  5722. // Project Page
  5723. getArchiveProjectPage: (id: number) =>
  5724. request<{
  5725. title: string | null;
  5726. description: string | null;
  5727. designer: string | null;
  5728. designer_user_id: string | null;
  5729. license: string | null;
  5730. copyright: string | null;
  5731. creation_date: string | null;
  5732. modification_date: string | null;
  5733. origin: string | null;
  5734. profile_title: string | null;
  5735. profile_description: string | null;
  5736. profile_cover: string | null;
  5737. profile_user_id: string | null;
  5738. profile_user_name: string | null;
  5739. design_model_id: string | null;
  5740. design_profile_id: string | null;
  5741. design_region: string | null;
  5742. model_pictures: Array<{ name: string; path: string; url: string }>;
  5743. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5744. thumbnails: Array<{ name: string; path: string; url: string }>;
  5745. }>(`/archives/${id}/project-page`),
  5746. updateArchiveProjectPage: (id: number, data: {
  5747. title?: string;
  5748. description?: string;
  5749. designer?: string;
  5750. license?: string;
  5751. copyright?: string;
  5752. profile_title?: string;
  5753. profile_description?: string;
  5754. }) =>
  5755. request(`/archives/${id}/project-page`, {
  5756. method: 'PATCH',
  5757. body: JSON.stringify(data),
  5758. }),
  5759. getArchiveForSlicer: (id: number, filename: string) => {
  5760. const safe = filename.replace(/[/\\?#]/g, '_');
  5761. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5762. },
  5763. createArchiveSlicerToken: (archiveId: number) =>
  5764. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5765. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5766. const safe = filename.replace(/[/\\?#]/g, '_');
  5767. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5768. },
  5769. getArchivePlates: (archiveId: number) =>
  5770. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5771. getArchiveFilamentRequirements: (
  5772. archiveId: number,
  5773. plateId?: number,
  5774. requestId?: string,
  5775. /** Ask for one entry per project slot instead of only the slots this
  5776. * plate consumes. The slice modal needs it: its filament list is
  5777. * positional, so a source whose only used slot is 4 must still present
  5778. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5779. * AMS matching must NOT set this — it wants the used-only list. */
  5780. fullSlots?: boolean,
  5781. ) => {
  5782. const qs = new URLSearchParams();
  5783. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5784. if (requestId) qs.set('request_id', requestId);
  5785. if (fullSlots) qs.set('full_slots', 'true');
  5786. return request<{
  5787. archive_id: number;
  5788. filename: string;
  5789. plate_id: number | null;
  5790. filaments: Array<{
  5791. slot_id: number;
  5792. type: string;
  5793. color: string;
  5794. used_grams: number;
  5795. used_meters: number;
  5796. used_in_plate?: boolean;
  5797. }>;
  5798. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5799. },
  5800. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5801. const formData = new FormData();
  5802. files.forEach((file) => formData.append('files', file));
  5803. const url = printerId
  5804. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  5805. : `${API_BASE}/archives/upload-bulk`;
  5806. const headers: Record<string, string> = {};
  5807. if (authToken) {
  5808. headers['Authorization'] = `Bearer ${authToken}`;
  5809. }
  5810. const response = await fetch(url, {
  5811. method: 'POST',
  5812. headers,
  5813. body: formData,
  5814. });
  5815. if (!response.ok) {
  5816. const error = await response.json().catch(() => ({}));
  5817. throw new Error(error.detail || `HTTP ${response.status}`);
  5818. }
  5819. return response.json();
  5820. },
  5821. // Print Log
  5822. getPrintLog: (params?: {
  5823. search?: string;
  5824. printerId?: number;
  5825. username?: string;
  5826. status?: string;
  5827. dateFrom?: string;
  5828. dateTo?: string;
  5829. limit?: number;
  5830. offset?: number;
  5831. // Sorting is server-side because paging is: ordering only the rows the
  5832. // client holds would sort one page, not the log (#2636).
  5833. sortBy?: string;
  5834. sortDir?: 'asc' | 'desc';
  5835. }) => {
  5836. const searchParams = new URLSearchParams();
  5837. if (params?.search) searchParams.set('search', params.search);
  5838. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  5839. if (params?.username) searchParams.set('created_by_username', params.username);
  5840. if (params?.status) searchParams.set('status', params.status);
  5841. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  5842. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  5843. if (params?.limit) searchParams.set('limit', String(params.limit));
  5844. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  5845. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  5846. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  5847. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  5848. },
  5849. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  5850. clearPrintLog: () =>
  5851. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  5852. deletePrintLogEntry: (id: number) =>
  5853. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  5854. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  5855. // Distinct from updateArchive: archives describe the model, log entries
  5856. // describe a single print event. Orphan entries (no archive_id) have no
  5857. // archive to reach through and this is the only path to classify them.
  5858. updatePrintLogEntry: (
  5859. id: number,
  5860. body: { failure_reason?: string | null; status?: string },
  5861. ) =>
  5862. request<PrintLogEntry>(`/print-log/${id}`, {
  5863. method: 'PATCH',
  5864. body: JSON.stringify(body),
  5865. }),
  5866. // Settings
  5867. getSettings: () => request<AppSettings>('/settings/'),
  5868. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  5869. // Public subset of settings for UI rendering — no settings:read required.
  5870. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  5871. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  5872. // backend/app/api/routes/settings.py.
  5873. getUiPreferences: () =>
  5874. request<{
  5875. require_plate_clear?: boolean;
  5876. check_printer_firmware?: boolean;
  5877. camera_view_mode?: 'window' | 'embedded';
  5878. time_format?: 'system' | '12h' | '24h';
  5879. date_format?: string;
  5880. drying_presets?: string;
  5881. ams_humidity_thresholds?: string;
  5882. ams_humidity_good?: number;
  5883. ams_humidity_fair?: number;
  5884. ams_temp_good?: number;
  5885. ams_temp_fair?: number;
  5886. bed_cooled_threshold?: number;
  5887. nozzle_temp_presets?: string;
  5888. bed_temp_presets?: string;
  5889. chamber_temp_presets?: string;
  5890. fan_speed_presets?: string;
  5891. }>('/settings/ui-preferences'),
  5892. // Install configuration the app shell needs, for any signed-in user. Separate
  5893. // from getUiPreferences: that endpoint is public because its fields are
  5894. // defaults shipped with the app, while these describe how this deployment is
  5895. // configured. Neither requires settings:read -- which is the point, since a
  5896. // non-admin reading GET /settings gets a 403 and every gate that consults it
  5897. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  5898. // backend/app/api/routes/settings.py.
  5899. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  5900. // The two above together: what a page needs from the settings when its user
  5901. // may not read GET /settings. See useUiSettings.
  5902. getUiSettings: async (): Promise<UiSettings> => {
  5903. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  5904. return { ...(preferences as UiSettings), ...flags };
  5905. },
  5906. updateSettings: (data: AppSettingsUpdate) =>
  5907. request<AppSettings>('/settings/', {
  5908. method: 'PUT',
  5909. body: JSON.stringify(data),
  5910. }),
  5911. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  5912. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  5913. // New simplified backup - complete database + all files
  5914. const url = `${API_BASE}/settings/backup`;
  5915. const headers: Record<string, string> = {};
  5916. if (authToken) {
  5917. headers['Authorization'] = `Bearer ${authToken}`;
  5918. }
  5919. const response = await fetch(url, { headers });
  5920. // Check for errors
  5921. if (!response.ok) {
  5922. const errorText = await response.text();
  5923. throw new Error(errorText || `Backup failed with status ${response.status}`);
  5924. }
  5925. // Get filename from Content-Disposition header
  5926. const contentDisposition = response.headers.get('Content-Disposition');
  5927. let filename = 'bambuddy-backup.zip';
  5928. if (contentDisposition) {
  5929. const match = contentDisposition.match(/filename=([^;]+)/);
  5930. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  5931. }
  5932. const blob = await response.blob();
  5933. return { blob, filename };
  5934. },
  5935. importBackup: async (file: File) => {
  5936. // New simplified restore - replaces database + all directories
  5937. const formData = new FormData();
  5938. formData.append('file', file);
  5939. const url = `${API_BASE}/settings/restore`;
  5940. const headers: Record<string, string> = {};
  5941. if (authToken) {
  5942. headers['Authorization'] = `Bearer ${authToken}`;
  5943. }
  5944. const response = await fetch(url, {
  5945. method: 'POST',
  5946. headers,
  5947. body: formData,
  5948. });
  5949. const data = (await response.json().catch(() => null)) as {
  5950. success?: boolean;
  5951. message?: string;
  5952. detail?: string;
  5953. } | null;
  5954. // A refused restore is an HTTPException, so the body is {detail}, not
  5955. // {success, message}. Returning it unmapped made `success` undefined and
  5956. // `message` undefined too — the modal then raised an empty error toast,
  5957. // which is the one case where the reason matters most (e.g. a backup this
  5958. // version cannot import names the columns and both versions).
  5959. if (!response.ok) {
  5960. return { success: false, message: data?.detail ?? data?.message ?? '' };
  5961. }
  5962. return (data ?? { success: false, message: '' }) as {
  5963. success: boolean;
  5964. message: string;
  5965. };
  5966. },
  5967. checkFfmpeg: () =>
  5968. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  5969. getNetworkInterfaces: () =>
  5970. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  5971. // Cloud
  5972. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  5973. cloudLogin: (email: string, password: string, region = 'global') =>
  5974. request<CloudLoginResponse>('/cloud/login', {
  5975. method: 'POST',
  5976. body: JSON.stringify({ email, password, region }),
  5977. }),
  5978. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  5979. request<CloudLoginResponse>('/cloud/verify', {
  5980. method: 'POST',
  5981. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  5982. }),
  5983. cloudSetToken: (access_token: string, region: string = 'global') =>
  5984. request<CloudAuthStatus>('/cloud/token', {
  5985. method: 'POST',
  5986. body: JSON.stringify({ access_token, region }),
  5987. }),
  5988. cloudLogout: () =>
  5989. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  5990. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  5991. // user_code + verification link; the user approves it in their Orca Cloud
  5992. // settings while the frontend polls devicePoll() every `interval` seconds
  5993. // until the status flips to 'complete' (or a terminal deny/expire).
  5994. orcaCloudDeviceStart: () =>
  5995. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  5996. method: 'POST',
  5997. }),
  5998. orcaCloudDevicePoll: () =>
  5999. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6000. method: 'POST',
  6001. }),
  6002. orcaCloudStatus: () =>
  6003. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6004. orcaCloudLogout: () =>
  6005. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6006. orcaCloudListProfiles: () =>
  6007. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6008. orcaCloudGetProfile: (id: string) =>
  6009. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6010. getCloudSettings: (version = '02.04.00.70') =>
  6011. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6012. getBuiltinFilaments: () =>
  6013. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6014. getFilamentIdMap: () =>
  6015. request<Record<string, string>>('/cloud/filament-id-map'),
  6016. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6017. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6018. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6019. * collapses these to the first hit; this endpoint preserves the material
  6020. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6021. * catalog at all. #1718. */
  6022. getColorByMaterial: (hex: string, material?: string) => {
  6023. const params = new URLSearchParams({ hex });
  6024. if (material) params.set('material', material);
  6025. return request<{ color_name: string | null }>(
  6026. `/inventory/colors/by-material?${params.toString()}`,
  6027. );
  6028. },
  6029. // MakerWorld URL-paste import flow.
  6030. getMakerworldStatus: () =>
  6031. request<MakerworldStatus>('/makerworld/status'),
  6032. resolveMakerworldUrl: (url: string) =>
  6033. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6034. method: 'POST',
  6035. body: JSON.stringify({ url }),
  6036. }),
  6037. getMakerworldRecentImports: (limit = 10) =>
  6038. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6039. importMakerworldInstance: (
  6040. model_id: number,
  6041. instance_id: number | null,
  6042. profile_id?: number | null,
  6043. folder_id?: number | null,
  6044. ) =>
  6045. request<MakerworldImportResponse>('/makerworld/import', {
  6046. method: 'POST',
  6047. body: JSON.stringify({
  6048. model_id,
  6049. instance_id: instance_id ?? null,
  6050. profile_id: profile_id ?? null,
  6051. folder_id: folder_id ?? null,
  6052. }),
  6053. }),
  6054. // Manyfold (#1471).
  6055. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6056. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6057. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6058. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6059. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6060. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6061. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6062. listManyfoldModels: (query: string, page: number) => {
  6063. const params = new URLSearchParams({ page: String(page) });
  6064. if (query) params.set('q', query);
  6065. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6066. },
  6067. getManyfoldModel: (modelId: string) =>
  6068. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6069. /** The model's preview, or null when it has none. Fetched rather than used
  6070. * as an <img src>: a failing protected <img> makes the app renew its media
  6071. * token, and models without a preview answer 404. */
  6072. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6073. const headers: Record<string, string> = {};
  6074. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6075. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6076. if (!response.ok) return null;
  6077. return response.blob();
  6078. },
  6079. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6080. request<ManyfoldImportResponse>('/manyfold/import', {
  6081. method: 'POST',
  6082. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6083. }),
  6084. getCloudSettingDetail: (settingId: string) =>
  6085. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6086. createCloudSetting: (data: SlicerSettingCreate) =>
  6087. request<SlicerSettingDetail>('/cloud/settings', {
  6088. method: 'POST',
  6089. body: JSON.stringify(data),
  6090. }),
  6091. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6092. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6093. method: 'PUT',
  6094. body: JSON.stringify(data),
  6095. }),
  6096. deleteCloudSetting: (settingId: string) =>
  6097. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6098. method: 'DELETE',
  6099. }),
  6100. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6101. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6102. getFilamentInfo: (settingIds: string[]) =>
  6103. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6104. method: 'POST',
  6105. body: JSON.stringify(settingIds),
  6106. }),
  6107. // Smart Plugs
  6108. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6109. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6110. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6111. createSmartPlug: (data: SmartPlugCreate) =>
  6112. request<SmartPlug>('/smart-plugs/', {
  6113. method: 'POST',
  6114. body: JSON.stringify(data),
  6115. }),
  6116. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6117. request<SmartPlug>(`/smart-plugs/${id}`, {
  6118. method: 'PATCH',
  6119. body: JSON.stringify(data),
  6120. }),
  6121. deleteSmartPlug: (id: number) =>
  6122. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6123. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6124. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6125. method: 'POST',
  6126. body: JSON.stringify({ action }),
  6127. }),
  6128. getSmartPlugStatus: (id: number) =>
  6129. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6130. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6131. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6132. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6133. method: 'POST',
  6134. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6135. }),
  6136. // Tasmota Discovery (auto-detects network)
  6137. startTasmotaScan: () =>
  6138. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6139. getTasmotaScanStatus: () =>
  6140. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6141. stopTasmotaScan: () =>
  6142. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6143. getDiscoveredTasmotaDevices: () =>
  6144. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6145. // Home Assistant Integration
  6146. testHAConnection: (url: string, token: string) =>
  6147. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6148. method: 'POST',
  6149. body: JSON.stringify({ url, token }),
  6150. }),
  6151. getHAEntities: (search?: string) => {
  6152. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6153. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6154. },
  6155. getHASensorEntities: () =>
  6156. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6157. // Home Assistant sensors bound to a printer (#1148, #448)
  6158. getHASensors: (printerId?: number) =>
  6159. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6160. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6161. getBindableHAEntities: (search?: string) => {
  6162. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6163. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6164. },
  6165. createHASensor: (data: PrinterHASensorCreate) =>
  6166. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6167. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6168. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6169. deleteHASensor: (id: number) =>
  6170. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6171. getLocationHASensors: (locationId?: number) =>
  6172. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6173. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6174. request<LocationHASensorReading[]>(
  6175. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6176. ),
  6177. getBindableLocationHAEntities: (search?: string) => {
  6178. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6179. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6180. },
  6181. createLocationHASensor: (data: LocationHASensorCreate) =>
  6182. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6183. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6184. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6185. deleteLocationHASensor: (id: number) =>
  6186. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6187. // REST smart plug
  6188. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6189. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6190. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6191. method: 'POST',
  6192. body: JSON.stringify({ url, method, headers, plug_id }),
  6193. }),
  6194. // Print Queue
  6195. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6196. const params = new URLSearchParams();
  6197. if (printerId) params.set('printer_id', String(printerId));
  6198. if (status) params.set('status', status);
  6199. if (targetModel) params.set('target_model', targetModel);
  6200. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6201. },
  6202. // History (completed / failed / skipped / cancelled), one page at a time.
  6203. getQueueHistory: (params: QueueHistoryParams) =>
  6204. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6205. // Removes the history matching the same filters, server-side.
  6206. clearQueueHistory: (params: QueueHistoryFilters) =>
  6207. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6208. method: 'POST',
  6209. }),
  6210. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6211. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6212. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6213. addToQueue: (data: PrintQueueItemCreate) =>
  6214. request<PrintQueueItem>('/queue/', {
  6215. method: 'POST',
  6216. body: JSON.stringify(data),
  6217. }),
  6218. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6219. request<PrintQueueItem>(`/queue/${id}`, {
  6220. method: 'PATCH',
  6221. body: JSON.stringify(data),
  6222. }),
  6223. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6224. * last run a batch order could re-queue its plate from (#2960). */
  6225. removeFromQueue: (id: number) =>
  6226. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6227. reorderQueue: (items: { id: number; position: number }[]) =>
  6228. request<{ message: string }>('/queue/reorder', {
  6229. method: 'POST',
  6230. body: JSON.stringify({ items }),
  6231. }),
  6232. cancelQueueItem: (id: number) =>
  6233. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6234. stopQueueItem: (id: number) =>
  6235. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6236. /**
  6237. * Start a staged queue item. The backend re-checks live filament deficit
  6238. * for the assigned spool and, when short, returns 409 with a structured
  6239. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6240. * after the user confirms "Print Anyway" (#1496).
  6241. */
  6242. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6243. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6244. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6245. },
  6246. /**
  6247. * Clear the `require_previous_success` gate for a printer after the user
  6248. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6249. * restores skipped items whose error_message matches the gate string
  6250. * back to pending. Returns counts so the UI can render a precise toast.
  6251. */
  6252. // A job for any printer of a model waits when the last print failed on every
  6253. // free one; this clears the gate on the model's printers.
  6254. resumeModelQueueAfterFailure: (model: string) =>
  6255. request<{ acknowledged: number; printers: number }>(
  6256. `/queue/model/${encodeURIComponent(model)}/resume`,
  6257. { method: 'POST' },
  6258. ),
  6259. resumeQueueAfterFailure: (printerId: number) =>
  6260. request<{ acknowledged: number; restored: number }>(
  6261. `/queue/printer/${printerId}/resume`,
  6262. { method: 'POST' },
  6263. ),
  6264. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6265. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6266. method: 'PATCH',
  6267. body: JSON.stringify(data),
  6268. }),
  6269. // Batches
  6270. getBatches: (status?: string) => {
  6271. const params = status ? `?status=${status}` : '';
  6272. return request<PrintBatch[]>(`/queue/batches${params}`);
  6273. },
  6274. cancelBatch: (id: number) =>
  6275. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6276. createBatch: (data: PrintBatchCreate) =>
  6277. request<PrintBatch>('/queue/batches', {
  6278. method: 'POST',
  6279. body: JSON.stringify(data),
  6280. }),
  6281. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6282. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6283. method: 'POST',
  6284. body: JSON.stringify(data),
  6285. }),
  6286. ungroupBatch: (id: number) =>
  6287. request<{ ungrouped_count: number; message: string }>(
  6288. `/queue/batches/${id}/ungroup`,
  6289. { method: 'POST' },
  6290. ),
  6291. // K-Profiles
  6292. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6293. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6294. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6295. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6296. method: 'POST',
  6297. body: JSON.stringify(profile),
  6298. }),
  6299. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6300. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6301. method: 'DELETE',
  6302. body: JSON.stringify(profile),
  6303. }),
  6304. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6305. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6306. method: 'POST',
  6307. body: JSON.stringify(profiles),
  6308. }),
  6309. // Finance
  6310. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6311. getMyTransactions: (limit = 50, offset = 0) =>
  6312. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6313. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6314. const params = new URLSearchParams();
  6315. params.set('limit', String(limit));
  6316. params.set('offset', String(offset));
  6317. if (userId !== undefined) params.set('user_id', String(userId));
  6318. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6319. },
  6320. deleteTransaction: (transactionId: number) =>
  6321. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6322. method: 'DELETE',
  6323. }),
  6324. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6325. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6326. method: 'PATCH',
  6327. body: JSON.stringify(data),
  6328. }),
  6329. createManualPrint: (data: ManualPrintRequest) =>
  6330. request<WalletTransaction>('/finance/transactions/manual', {
  6331. method: 'POST',
  6332. body: JSON.stringify(data),
  6333. }),
  6334. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6335. listCostCenters: (includeInactive = false) =>
  6336. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6337. createCostCenter: (data: CostCenterCreateRequest) =>
  6338. request<CostCenterSummary>('/finance/cost-centers', {
  6339. method: 'POST',
  6340. body: JSON.stringify(data),
  6341. }),
  6342. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6343. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6344. method: 'PATCH',
  6345. body: JSON.stringify(data),
  6346. }),
  6347. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6348. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6349. method: 'PATCH',
  6350. body: JSON.stringify(data),
  6351. }),
  6352. deleteCostCenter: (costCenterId: number) =>
  6353. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6354. method: 'DELETE',
  6355. }),
  6356. getCostCenter: (costCenterId: number) =>
  6357. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6358. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6359. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6360. method: 'POST',
  6361. body: JSON.stringify(data),
  6362. }),
  6363. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6364. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6365. method: 'DELETE',
  6366. }),
  6367. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6368. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6369. method: 'POST',
  6370. body: JSON.stringify(data),
  6371. }),
  6372. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6373. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6374. method: 'POST',
  6375. body: JSON.stringify(data),
  6376. }),
  6377. rebuildBalanceLedger: () =>
  6378. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6379. method: 'POST',
  6380. }),
  6381. // K-Profile Notes (stored locally, not on printer)
  6382. getKProfileNotes: (printerId: number) =>
  6383. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6384. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6385. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6386. method: 'PUT',
  6387. body: JSON.stringify({ setting_id: settingId, note }),
  6388. }),
  6389. // Slot Preset Mappings
  6390. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6391. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6392. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}${trayInfoIdx ? `&tray_info_idx=${encodeURIComponent(trayInfoIdx)}` : ''}`, {
  6393. method: 'PUT',
  6394. }),
  6395. // AMS Labels (user-defined friendly names)
  6396. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6397. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6398. request<{ ams_id: number; label: string }>(
  6399. `/printers/${printerId}/ams-labels/${amsId}`,
  6400. {
  6401. method: 'PUT',
  6402. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6403. }
  6404. ),
  6405. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6406. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6407. method: 'DELETE',
  6408. }),
  6409. configureAmsSlot: (
  6410. printerId: number,
  6411. amsId: number,
  6412. trayId: number,
  6413. config: {
  6414. tray_info_idx: string;
  6415. tray_type: string;
  6416. tray_sub_brands: string;
  6417. tray_color: string;
  6418. nozzle_temp_min: number;
  6419. nozzle_temp_max: number;
  6420. cali_idx: number;
  6421. nozzle_diameter: string;
  6422. setting_id?: string;
  6423. kprofile_filament_id?: string;
  6424. kprofile_setting_id?: string;
  6425. k_value?: number;
  6426. // Orca Cloud profile the slot is set to; the backend looks up its
  6427. // filament id when tray_info_idx is empty (#3216).
  6428. orca_profile_id?: string;
  6429. }
  6430. ) => {
  6431. const params = new URLSearchParams({
  6432. tray_info_idx: config.tray_info_idx,
  6433. tray_type: config.tray_type,
  6434. tray_sub_brands: config.tray_sub_brands,
  6435. tray_color: config.tray_color,
  6436. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6437. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6438. cali_idx: config.cali_idx.toString(),
  6439. nozzle_diameter: config.nozzle_diameter,
  6440. });
  6441. if (config.setting_id) {
  6442. params.set('setting_id', config.setting_id);
  6443. }
  6444. if (config.kprofile_filament_id) {
  6445. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6446. }
  6447. if (config.kprofile_setting_id) {
  6448. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6449. }
  6450. if (config.k_value !== undefined && config.k_value > 0) {
  6451. params.set('k_value', config.k_value.toString());
  6452. }
  6453. if (config.orca_profile_id) {
  6454. params.set('orca_profile_id', config.orca_profile_id);
  6455. }
  6456. return request<{
  6457. success: boolean;
  6458. message: string;
  6459. // The filament id the slot was actually given.
  6460. tray_info_idx?: string;
  6461. // Why an Orca profile went out as the generic for its material, or "".
  6462. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6463. /** A manual K value could not be sent; the filament setting was. */
  6464. k_value_unsent?: boolean;
  6465. }>(
  6466. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6467. { method: 'POST' }
  6468. );
  6469. },
  6470. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6471. request<{ success: boolean; message: string }>(
  6472. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6473. { method: 'POST' }
  6474. ),
  6475. // Notification Providers
  6476. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6477. createNotificationProvider: (data: NotificationProviderCreate) =>
  6478. request<NotificationProvider>('/notifications/', {
  6479. method: 'POST',
  6480. body: JSON.stringify(data),
  6481. }),
  6482. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6483. request<NotificationProvider>(`/notifications/${id}`, {
  6484. method: 'PATCH',
  6485. body: JSON.stringify(data),
  6486. }),
  6487. deleteNotificationProvider: (id: number) =>
  6488. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6489. testNotificationProvider: (id: number) =>
  6490. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6491. testNotificationConfig: (data: NotificationTestRequest) =>
  6492. request<NotificationTestResponse>('/notifications/test-config', {
  6493. method: 'POST',
  6494. body: JSON.stringify(data),
  6495. }),
  6496. testAllNotificationProviders: () =>
  6497. request<{
  6498. tested: number;
  6499. success: number;
  6500. failed: number;
  6501. results: Array<{
  6502. provider_id: number;
  6503. provider_name: string;
  6504. provider_type: string;
  6505. success: boolean;
  6506. message: string;
  6507. }>;
  6508. }>('/notifications/test-all', { method: 'POST' }),
  6509. // Notification Templates
  6510. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6511. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6512. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6513. method: 'PUT',
  6514. body: JSON.stringify(data),
  6515. }),
  6516. resetNotificationTemplate: (id: number) =>
  6517. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6518. method: 'POST',
  6519. }),
  6520. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6521. previewTemplate: (data: TemplatePreviewRequest) =>
  6522. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6523. method: 'POST',
  6524. body: JSON.stringify(data),
  6525. }),
  6526. // Notification Logs
  6527. getNotificationLogs: (params?: {
  6528. limit?: number;
  6529. offset?: number;
  6530. provider_id?: number;
  6531. event_type?: string;
  6532. success?: boolean;
  6533. days?: number;
  6534. }) => {
  6535. const searchParams = new URLSearchParams();
  6536. if (params?.limit) searchParams.set('limit', String(params.limit));
  6537. if (params?.offset) searchParams.set('offset', String(params.offset));
  6538. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6539. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6540. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6541. if (params?.days) searchParams.set('days', String(params.days));
  6542. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6543. },
  6544. getNotificationLogStats: (days = 7) =>
  6545. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6546. clearNotificationLogs: (olderThanDays = 30) =>
  6547. request<{ deleted: number; message: string }>(
  6548. `/notifications/logs?older_than_days=${olderThanDays}`,
  6549. { method: 'DELETE' }
  6550. ),
  6551. // Spoolman Integration
  6552. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6553. migrateSpoolmanTags: (dryRun: boolean) =>
  6554. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6555. method: 'POST',
  6556. }),
  6557. connectSpoolman: () =>
  6558. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6559. method: 'POST',
  6560. }),
  6561. syncPrinterAms: (printerId: number) =>
  6562. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6563. method: 'POST',
  6564. }),
  6565. syncAllPrintersAms: () =>
  6566. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6567. method: 'POST',
  6568. }),
  6569. getSpoolmanInventoryFilaments: () =>
  6570. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6571. getUnlinkedSpools: () =>
  6572. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6573. getLinkedSpools: () =>
  6574. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6575. linkSpool: (
  6576. spoolId: number,
  6577. context: {
  6578. spoolTag: string;
  6579. printerId: number;
  6580. amsId: number;
  6581. trayId: number;
  6582. }
  6583. ) =>
  6584. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6585. method: 'POST',
  6586. body: JSON.stringify({
  6587. spool_tag: context.spoolTag,
  6588. printer_id: context.printerId,
  6589. ams_id: context.amsId,
  6590. tray_id: context.trayId,
  6591. }),
  6592. }),
  6593. unlinkSpool: (spoolId: number) =>
  6594. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6595. method: 'POST',
  6596. }),
  6597. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6598. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6599. method: 'POST',
  6600. body: JSON.stringify(data),
  6601. }),
  6602. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6603. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6604. method: 'POST',
  6605. body: JSON.stringify(data),
  6606. }),
  6607. getSpoolmanSettings: () =>
  6608. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; auto_add_unknown_rfid: string; }>('/settings/spoolman'),
  6609. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; auto_add_unknown_rfid?: string; }) =>
  6610. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; auto_add_unknown_rfid: string; }>('/settings/spoolman', {
  6611. method: 'PUT',
  6612. body: JSON.stringify(data),
  6613. }),
  6614. // Inventory
  6615. getSpools: (includeArchived = false) =>
  6616. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6617. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6618. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6619. request<InventorySpool>('/inventory/spools', {
  6620. method: 'POST',
  6621. body: JSON.stringify(data),
  6622. }),
  6623. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6624. request<InventorySpool[]>('/inventory/spools/bulk', {
  6625. method: 'POST',
  6626. body: JSON.stringify({ spool: data, quantity }),
  6627. }),
  6628. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6629. // dry_run=true → preview (no write); omitted → real import. Both share one
  6630. // multipart upload helper; see `uploadSpoolsCsv` below.
  6631. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6632. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6633. exportSpoolsCsv: async (): Promise<void> => {
  6634. const headers: Record<string, string> = {};
  6635. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6636. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6637. if (!response.ok) {
  6638. const error = await response.json().catch(() => ({}));
  6639. throw new Error(error.detail || `HTTP ${response.status}`);
  6640. }
  6641. const disposition = response.headers.get('Content-Disposition');
  6642. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6643. const blob = await response.blob();
  6644. const url = window.URL.createObjectURL(blob);
  6645. const a = document.createElement('a');
  6646. a.href = url;
  6647. a.download = filename;
  6648. document.body.appendChild(a);
  6649. a.click();
  6650. document.body.removeChild(a);
  6651. window.URL.revokeObjectURL(url);
  6652. },
  6653. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6654. request<InventorySpool>(`/inventory/spools/${id}`, {
  6655. method: 'PATCH',
  6656. body: JSON.stringify(data),
  6657. }),
  6658. deleteSpool: (id: number) =>
  6659. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6660. archiveSpool: (id: number) =>
  6661. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6662. restoreSpool: (id: number) =>
  6663. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6664. resetSpoolConsumedCounter: (id: number) =>
  6665. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6666. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6667. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6668. method: 'POST',
  6669. body: JSON.stringify({ spool_ids: spoolIds }),
  6670. }),
  6671. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6672. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6673. method: 'POST',
  6674. body: JSON.stringify({ ids, update }),
  6675. }),
  6676. bulkDeleteSpools: (ids: number[]) =>
  6677. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6678. method: 'POST',
  6679. body: JSON.stringify({ ids }),
  6680. }),
  6681. bulkArchiveSpools: (ids: number[]) =>
  6682. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6683. method: 'POST',
  6684. body: JSON.stringify({ ids }),
  6685. }),
  6686. bulkRestoreSpools: (ids: number[]) =>
  6687. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6688. method: 'POST',
  6689. body: JSON.stringify({ ids }),
  6690. }),
  6691. getSpoolKProfiles: (spoolId: number) =>
  6692. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6693. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6694. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6695. method: 'PUT',
  6696. body: JSON.stringify(profiles),
  6697. }),
  6698. /**
  6699. * What the spool assigned to this slot is configured to use *here* -- its
  6700. * per-printer-model filament preset and the K profile for this slot's hotend.
  6701. * Nulls when the slot holds no known spool.
  6702. */
  6703. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6704. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6705. getSpoolFilamentPresets: (spoolId: number) =>
  6706. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6707. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6708. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6709. method: 'PUT',
  6710. body: JSON.stringify(presets),
  6711. }),
  6712. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6713. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6714. const params = new URLSearchParams({
  6715. brand: key.brand,
  6716. material: key.material,
  6717. subtype: key.subtype,
  6718. color_name: key.color_name,
  6719. });
  6720. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6721. },
  6722. saveProfileDefault: (data: ProfileDefaultInput) =>
  6723. request<ProfileDefault>('/inventory/profile-defaults', {
  6724. method: 'PUT',
  6725. body: JSON.stringify(data),
  6726. }),
  6727. deleteProfileDefault: (defaultId: number) =>
  6728. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6729. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6730. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6731. request<{ updated: number }>(
  6732. spoolmanMode
  6733. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6734. : `/inventory/profile-defaults/${defaultId}/apply`,
  6735. { method: 'POST' },
  6736. ),
  6737. getAssignments: (printerId?: number) =>
  6738. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6739. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  6740. request<SpoolAssignment>('/inventory/assignments', {
  6741. method: 'POST',
  6742. body: JSON.stringify(data),
  6743. }),
  6744. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6745. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6746. // ── Spool label printing (#809) ──────────────────────────────────────────
  6747. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6748. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6749. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6750. postForBlob('/inventory/labels', data),
  6751. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6752. postForBlob('/spoolman/labels', data),
  6753. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6754. postForBlob('/inventory/labels/preview', data, signal),
  6755. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6756. postForBlob('/spoolman/labels/preview', data, signal),
  6757. getSpoolCatalog: () =>
  6758. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6759. addCatalogEntry: (data: { name: string; weight: number }) =>
  6760. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6761. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6762. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6763. deleteCatalogEntry: (id: number) =>
  6764. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6765. bulkDeleteCatalogEntries: (ids: number[]) =>
  6766. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6767. resetSpoolCatalog: () =>
  6768. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6769. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6770. getSuppliers: () =>
  6771. request<Supplier[]>('/inventory/suppliers'),
  6772. createSupplier: (data: SupplierInput) =>
  6773. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6774. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6775. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6776. deleteSupplier: (id: number) =>
  6777. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6778. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6779. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6780. method: 'PUT',
  6781. body: JSON.stringify(links),
  6782. }),
  6783. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6784. // remote spool id — same request/response shape as the built-in inventory.
  6785. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6786. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6787. method: 'PUT',
  6788. body: JSON.stringify(links),
  6789. }),
  6790. // date_from/date_to scope the usage half only, so the widget can follow the
  6791. // dashboard timeframe; stock stays point-in-time.
  6792. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6793. const params = new URLSearchParams();
  6794. if (dateFrom) params.set('date_from', dateFrom);
  6795. if (dateTo) params.set('date_to', dateTo);
  6796. addDayZone(params);
  6797. const qs = params.toString();
  6798. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  6799. },
  6800. getLocations: () =>
  6801. request<StorageLocation[]>('/inventory/locations'),
  6802. createLocation: (data: { name: string; identifier?: string | null }) =>
  6803. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  6804. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  6805. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6806. deleteLocation: (id: number) =>
  6807. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  6808. getColorCatalog: () =>
  6809. request<ColorCatalogEntry[]>('/inventory/colors'),
  6810. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  6811. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  6812. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  6813. * map says "Jade White"). #2875. */
  6814. getColorNameMap: () =>
  6815. request<{
  6816. colors: Record<string, string>;
  6817. by_material?: Record<string, string>;
  6818. bambu?: BambuCatalogColor[];
  6819. preset_materials?: Record<string, string>;
  6820. }>('/inventory/colors/map'),
  6821. addColorEntry: (data: {
  6822. manufacturer: string;
  6823. color_name: string;
  6824. hex_color: string;
  6825. material: string | null;
  6826. extra_colors?: string | null;
  6827. effect_type?: string | null;
  6828. }) =>
  6829. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  6830. updateColorEntry: (
  6831. id: number,
  6832. data: {
  6833. manufacturer: string;
  6834. color_name: string;
  6835. hex_color: string;
  6836. material: string | null;
  6837. extra_colors?: string | null;
  6838. effect_type?: string | null;
  6839. },
  6840. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6841. deleteColorEntry: (id: number) =>
  6842. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  6843. bulkDeleteColorEntries: (ids: number[]) =>
  6844. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6845. resetColorCatalog: () =>
  6846. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  6847. searchColors: (manufacturer?: string, material?: string) =>
  6848. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  6849. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  6850. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  6851. method: 'PATCH',
  6852. body: JSON.stringify(data),
  6853. }),
  6854. // Per-material-number inventory aggregate (#2870). The date range narrows
  6855. // the usage half only — stock is point-in-time.
  6856. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  6857. const params = new URLSearchParams();
  6858. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  6859. if (options?.dateTo) params.set('date_to', options.dateTo);
  6860. addDayZone(params);
  6861. const qs = params.toString();
  6862. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  6863. },
  6864. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  6865. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  6866. getAllUsageHistory: (limit = 100, printerId?: number) =>
  6867. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  6868. clearSpoolUsageHistory: (spoolId: number) =>
  6869. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  6870. syncWeightsFromAms: () =>
  6871. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  6872. getSkuSettings: () =>
  6873. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  6874. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  6875. request<FilamentSkuSettings>('/inventory/sku-settings', {
  6876. method: 'POST',
  6877. body: JSON.stringify(data),
  6878. }),
  6879. getShoppingList: () =>
  6880. request<ShoppingListItem[]>('/inventory/shopping-list'),
  6881. addToShoppingList: (data: ShoppingListItemCreate) =>
  6882. request<ShoppingListItem>('/inventory/shopping-list', {
  6883. method: 'POST',
  6884. body: JSON.stringify(data),
  6885. }),
  6886. removeFromShoppingList: (id: number) =>
  6887. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  6888. clearShoppingList: () =>
  6889. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  6890. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  6891. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  6892. method: 'PATCH',
  6893. body: JSON.stringify({ status }),
  6894. }),
  6895. getFilamentPresets: () =>
  6896. request<SlicerSetting[]>('/cloud/filaments'),
  6897. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  6898. getSpoolmanInventorySpools: (includeArchived = false) =>
  6899. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  6900. getSpoolmanInventorySpool: (id: number) =>
  6901. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  6902. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6903. request<InventorySpool>('/spoolman/inventory/spools', {
  6904. method: 'POST',
  6905. body: JSON.stringify(data),
  6906. }),
  6907. bulkCreateSpoolmanInventorySpools: (
  6908. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  6909. quantity: number,
  6910. ) =>
  6911. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  6912. method: 'POST',
  6913. body: JSON.stringify({ spool: data, quantity }),
  6914. }),
  6915. updateSpoolmanInventorySpool: (
  6916. id: number,
  6917. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  6918. ) =>
  6919. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  6920. method: 'PATCH',
  6921. body: JSON.stringify(data),
  6922. }),
  6923. deleteSpoolmanInventorySpool: (id: number) =>
  6924. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  6925. archiveSpoolmanInventorySpool: (id: number) =>
  6926. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  6927. restoreSpoolmanInventorySpool: (id: number) =>
  6928. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  6929. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  6930. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6931. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  6932. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  6933. method: 'POST',
  6934. body: JSON.stringify({ spool_ids: spoolIds }),
  6935. }),
  6936. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6937. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  6938. method: 'POST',
  6939. body: JSON.stringify({ ids, update }),
  6940. }),
  6941. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  6942. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  6943. method: 'POST',
  6944. body: JSON.stringify({ ids }),
  6945. }),
  6946. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  6947. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  6948. method: 'POST',
  6949. body: JSON.stringify({ ids }),
  6950. }),
  6951. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  6952. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  6953. method: 'POST',
  6954. body: JSON.stringify({ ids }),
  6955. }),
  6956. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  6957. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  6958. method: 'PATCH',
  6959. body: JSON.stringify(data),
  6960. }),
  6961. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  6962. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  6963. method: 'PATCH',
  6964. body: JSON.stringify({ weight_grams: weightGrams }),
  6965. }),
  6966. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  6967. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  6968. method: 'POST',
  6969. body: JSON.stringify(data),
  6970. }),
  6971. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  6972. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  6973. getSpoolmanSlotAssignments: (printerId?: number) =>
  6974. request<Array<{
  6975. printer_id: number;
  6976. printer_name: string | null;
  6977. ams_id: number;
  6978. tray_id: number;
  6979. spoolman_spool_id: number;
  6980. ams_label: string | null;
  6981. }>>(
  6982. printerId !== undefined
  6983. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  6984. : '/spoolman/inventory/slot-assignments/all',
  6985. ),
  6986. syncSpoolmanAmsWeights: () =>
  6987. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  6988. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6989. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  6990. method: 'PUT',
  6991. body: JSON.stringify(profiles),
  6992. }),
  6993. getSpoolmanFilamentPresets: (spoolId: number) =>
  6994. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  6995. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6996. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  6997. method: 'PUT',
  6998. body: JSON.stringify(presets),
  6999. }),
  7000. // Updates
  7001. getVersion: () => request<VersionInfo>('/updates/version'),
  7002. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7003. applyUpdate: () =>
  7004. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7005. method: 'POST',
  7006. }),
  7007. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7008. // Maintenance
  7009. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7010. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7011. request<MaintenanceType>('/maintenance/types', {
  7012. method: 'POST',
  7013. body: JSON.stringify(data),
  7014. }),
  7015. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7016. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7017. method: 'PATCH',
  7018. body: JSON.stringify(data),
  7019. }),
  7020. deleteMaintenanceType: (id: number) =>
  7021. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7022. restoreDefaultMaintenanceTypes: () =>
  7023. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7024. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7025. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7026. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7027. method: 'PATCH',
  7028. body: JSON.stringify(data),
  7029. }),
  7030. performMaintenance: (itemId: number, notes?: string) =>
  7031. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7032. method: 'POST',
  7033. body: JSON.stringify({ notes }),
  7034. }),
  7035. setPrinterHours: (printerId: number, totalHours: number) =>
  7036. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7037. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7038. { method: 'PATCH' }
  7039. ),
  7040. assignMaintenanceType: (printerId: number, typeId: number) =>
  7041. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7042. method: 'POST',
  7043. }),
  7044. removeMaintenanceItem: (itemId: number) =>
  7045. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7046. method: 'DELETE',
  7047. }),
  7048. // Camera
  7049. getCameraStreamToken: () =>
  7050. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7051. // Media token (#3025) — the credential for thumbnails, plate previews,
  7052. // timelapses, cover images and link icons. Minted behind plain auth rather
  7053. // than camera:view, and identified, so those routes gate on the resource's
  7054. // own permission and ownership instead of on the camera.
  7055. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7056. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7057. // the /ws connection. Browsers can't attach Authorization headers to a
  7058. // WebSocket handshake, so the token rides in the ?token= query param.
  7059. getWebSocketToken: () =>
  7060. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7061. // Connected apps: sign-in to external applications with Bambuddy
  7062. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7063. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7064. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7065. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7066. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7067. rotateConnectedAppSecret: (id: number) =>
  7068. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7069. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7070. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7071. request<ConnectAuthorizeInfo>(
  7072. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7073. ),
  7074. connectAuthorize: (payload: {
  7075. client_id: string;
  7076. redirect_uri: string;
  7077. code_challenge: string;
  7078. code_challenge_method: 'S256';
  7079. }) =>
  7080. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7081. method: 'POST',
  7082. body: JSON.stringify(payload),
  7083. }),
  7084. // Long-lived camera tokens (#1108, #2531)
  7085. createLongLivedCameraToken: (payload: {
  7086. name: string;
  7087. expires_in_days: number;
  7088. scope?: LongLivedTokenScope;
  7089. }) =>
  7090. request<LongLivedCameraToken>('/auth/tokens', {
  7091. method: 'POST',
  7092. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7093. }),
  7094. listMyLongLivedCameraTokens: () =>
  7095. request<LongLivedCameraToken[]>('/auth/tokens'),
  7096. listAllLongLivedCameraTokens: () =>
  7097. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7098. revokeLongLivedCameraToken: (tokenId: number) =>
  7099. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7100. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7101. // auth is disabled, where the backend gate is a no-op anyway.
  7102. getCamWallPrinters: (token?: string) =>
  7103. request<CamWallPrinter[]>(
  7104. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7105. ),
  7106. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7107. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7108. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7109. getOverlayStatus: (printerId: number, token?: string) =>
  7110. request<OverlayStatus>(
  7111. token
  7112. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7113. : `/printers/${printerId}/overlay-status`,
  7114. ),
  7115. getCameraStatus: (printerId: number) =>
  7116. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7117. diagnoseCamera: (printerId: number) =>
  7118. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7119. diagnosePrinter: (printerId: number) =>
  7120. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7121. diagnoseConnection: (body: {
  7122. ip_address: string;
  7123. serial_number?: string;
  7124. access_code?: string;
  7125. }) =>
  7126. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7127. method: 'POST',
  7128. body: JSON.stringify(body),
  7129. }),
  7130. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7131. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7132. const params = new URLSearchParams();
  7133. // Only forward use_external when the caller explicitly sets it. Omitted →
  7134. // backend derives the default from the printer's external_camera_enabled
  7135. // setting so calibration and runtime checks use the same camera (#1359).
  7136. if (options?.useExternal !== undefined) {
  7137. params.set('use_external', String(options.useExternal));
  7138. }
  7139. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7140. return request<PlateDetectionResult>(
  7141. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7142. );
  7143. },
  7144. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7145. const params = new URLSearchParams();
  7146. if (options?.label) params.set('label', options.label);
  7147. if (options?.useExternal !== undefined) {
  7148. params.set('use_external', String(options.useExternal));
  7149. }
  7150. return request<CalibrationResult & { index: number }>(
  7151. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7152. { method: 'POST' }
  7153. );
  7154. },
  7155. getPlateReferences: (printerId: number) => {
  7156. return request<{
  7157. references: PlateReference[];
  7158. max_references: number;
  7159. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7160. },
  7161. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7162. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7163. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7164. const params = new URLSearchParams();
  7165. params.set('label', label);
  7166. return request<{ success: boolean; index: number; label: string }>(
  7167. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7168. { method: 'PUT' }
  7169. );
  7170. },
  7171. deletePlateReference: (printerId: number, index: number) => {
  7172. return request<{ success: boolean; message: string }>(
  7173. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7174. { method: 'DELETE' }
  7175. );
  7176. },
  7177. // External Links
  7178. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7179. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7180. createExternalLink: (data: ExternalLinkCreate) =>
  7181. request<ExternalLink>('/external-links/', {
  7182. method: 'POST',
  7183. body: JSON.stringify(data),
  7184. }),
  7185. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7186. request<ExternalLink>(`/external-links/${id}`, {
  7187. method: 'PATCH',
  7188. body: JSON.stringify(data),
  7189. }),
  7190. deleteExternalLink: (id: number) =>
  7191. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7192. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7193. const formData = new FormData();
  7194. formData.append('file', file);
  7195. const headers: Record<string, string> = {};
  7196. if (authToken) {
  7197. headers['Authorization'] = `Bearer ${authToken}`;
  7198. }
  7199. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7200. method: 'POST',
  7201. headers,
  7202. body: formData,
  7203. });
  7204. if (!response.ok) {
  7205. const error = await response.json().catch(() => ({}));
  7206. throw new Error(error.detail || `HTTP ${response.status}`);
  7207. }
  7208. return response.json();
  7209. },
  7210. deleteExternalLinkIcon: (id: number) =>
  7211. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7212. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7213. // Projects
  7214. getProjects: (status?: string) => {
  7215. const params = new URLSearchParams();
  7216. if (status) params.set('status', status);
  7217. return request<ProjectListItem[]>(`/projects/?${params}`);
  7218. },
  7219. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7220. createProject: (data: ProjectCreate) =>
  7221. request<Project>('/projects/', {
  7222. method: 'POST',
  7223. body: JSON.stringify(data),
  7224. }),
  7225. updateProject: (id: number, data: ProjectUpdate) =>
  7226. request<Project>(`/projects/${id}`, {
  7227. method: 'PATCH',
  7228. body: JSON.stringify(data),
  7229. }),
  7230. deleteProject: (id: number) =>
  7231. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7232. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7233. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7234. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7235. getProjectFileProgress: (id: number) =>
  7236. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7237. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7238. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7239. method: 'POST',
  7240. body: JSON.stringify({ archive_ids: archiveIds }),
  7241. }),
  7242. // #1155: Cover image
  7243. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7244. // append the stream-token query string the same way archive thumbnails do.
  7245. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7246. // before the token does: callers used to append their own `?v=` to the
  7247. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7248. // inside the token value and the image 401'd whenever auth was enabled.
  7249. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7250. withMediaToken(
  7251. `${API_BASE}/projects/${projectId}/cover-image${
  7252. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7253. }`
  7254. ),
  7255. uploadProjectCoverImage: async (
  7256. projectId: number,
  7257. file: File
  7258. ): Promise<{ status: string; filename: string; size: number }> => {
  7259. const formData = new FormData();
  7260. formData.append('file', file);
  7261. const headers: Record<string, string> = {};
  7262. if (authToken) {
  7263. headers['Authorization'] = `Bearer ${authToken}`;
  7264. }
  7265. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7266. method: 'POST',
  7267. headers,
  7268. body: formData,
  7269. });
  7270. if (!response.ok) {
  7271. const error = await response.json().catch(() => ({}));
  7272. throw new Error(error.detail || `HTTP ${response.status}`);
  7273. }
  7274. return response.json();
  7275. },
  7276. deleteProjectCoverImage: (projectId: number) =>
  7277. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7278. // BOM (Bill of Materials)
  7279. getProjectBOM: (projectId: number) =>
  7280. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7281. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7282. request<BOMItem>(`/projects/${projectId}/bom`, {
  7283. method: 'POST',
  7284. body: JSON.stringify(data),
  7285. }),
  7286. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7287. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7288. method: 'PATCH',
  7289. body: JSON.stringify(data),
  7290. }),
  7291. deleteBOMItem: (projectId: number, itemId: number) =>
  7292. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7293. method: 'DELETE',
  7294. }),
  7295. // Templates
  7296. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7297. createTemplateFromProject: (projectId: number) =>
  7298. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7299. createProjectFromTemplate: (templateId: number, name?: string) =>
  7300. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7301. method: 'POST',
  7302. }),
  7303. // Timeline
  7304. getProjectTimeline: (projectId: number, limit = 50) =>
  7305. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7306. // Project Export/Import
  7307. exportProjectJson: (projectId: number) =>
  7308. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7309. importProject: (data: ProjectImport) =>
  7310. request<Project>('/projects/import', {
  7311. method: 'POST',
  7312. body: JSON.stringify(data),
  7313. }),
  7314. importProjectFile: async (file: File): Promise<Project> => {
  7315. const formData = new FormData();
  7316. formData.append('file', file);
  7317. const headers: Record<string, string> = {};
  7318. if (authToken) {
  7319. headers['Authorization'] = `Bearer ${authToken}`;
  7320. }
  7321. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7322. method: 'POST',
  7323. headers,
  7324. body: formData,
  7325. });
  7326. if (!response.ok) {
  7327. const error = await response.json().catch(() => ({}));
  7328. throw new Error(error.detail || `HTTP ${response.status}`);
  7329. }
  7330. return response.json();
  7331. },
  7332. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7333. const headers: Record<string, string> = {};
  7334. if (authToken) {
  7335. headers['Authorization'] = `Bearer ${authToken}`;
  7336. }
  7337. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7338. headers,
  7339. });
  7340. if (!response.ok) {
  7341. const error = await response.json().catch(() => ({}));
  7342. throw new Error(error.detail || `HTTP ${response.status}`);
  7343. }
  7344. const contentDisposition = response.headers.get('Content-Disposition');
  7345. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7346. const blob = await response.blob();
  7347. return { blob, filename };
  7348. },
  7349. // API Keys
  7350. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7351. createAPIKey: (data: APIKeyCreate) =>
  7352. request<APIKeyCreateResponse>('/api-keys/', {
  7353. method: 'POST',
  7354. body: JSON.stringify(data),
  7355. }),
  7356. deleteAPIKey: (id: number) =>
  7357. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7358. // AMS History
  7359. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7360. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7361. // Printer heater (nozzle / bed / chamber) sensor history
  7362. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7363. const params = new URLSearchParams({ hours: String(hours) });
  7364. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7365. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7366. },
  7367. // System Info
  7368. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7369. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7370. getStorageUsage: (options?: { refresh?: boolean }) => {
  7371. const params = new URLSearchParams();
  7372. if (options?.refresh) {
  7373. params.set('refresh', 'true');
  7374. }
  7375. const query = params.toString();
  7376. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7377. },
  7378. // Library (File Manager)
  7379. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7380. createLibraryFolder: (data: LibraryFolderCreate) =>
  7381. request<LibraryFolder>('/library/folders', {
  7382. method: 'POST',
  7383. body: JSON.stringify(data),
  7384. }),
  7385. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7386. request<LibraryFolder>(`/library/folders/${id}`, {
  7387. method: 'PUT',
  7388. body: JSON.stringify(data),
  7389. }),
  7390. deleteLibraryFolder: (id: number) =>
  7391. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7392. createExternalFolder: (data: ExternalFolderCreate) =>
  7393. request<LibraryFolder>('/library/folders/external', {
  7394. method: 'POST',
  7395. body: JSON.stringify(data),
  7396. }),
  7397. scanExternalFolder: (folderId: number) =>
  7398. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7399. method: 'POST',
  7400. }),
  7401. getLibraryFoldersByProject: (projectId: number) =>
  7402. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7403. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7404. getLibraryFiles: (
  7405. folderId?: number | null,
  7406. includeRoot = true,
  7407. projectId?: number,
  7408. scope?: 'internal' | 'external',
  7409. recursive = false,
  7410. tagIds: number[] = [],
  7411. ) => {
  7412. const params = new URLSearchParams();
  7413. if (folderId !== undefined && folderId !== null) {
  7414. params.set('folder_id', String(folderId));
  7415. }
  7416. if (projectId !== undefined) {
  7417. params.set('project_id', String(projectId));
  7418. }
  7419. params.set('include_root', String(includeRoot));
  7420. if (scope === 'internal') params.set('internal_only', 'true');
  7421. else if (scope === 'external') params.set('external_only', 'true');
  7422. // recursive=true expands the folder_id filter to include every descendant
  7423. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7424. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7425. if (recursive) params.set('recursive', 'true');
  7426. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7427. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7428. // the array length. Tag filter intentionally bypasses folder scoping
  7429. // server-side (cross-cutting design decision).
  7430. for (const tagId of tagIds) {
  7431. params.append('tag_ids', String(tagId));
  7432. }
  7433. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7434. },
  7435. getLibraryFolderReadme: (folderId: number) =>
  7436. request<{ filename: string; content: string; truncated: boolean }>(
  7437. `/library/folders/${folderId}/readme`,
  7438. ),
  7439. // ============ Library tag catalog (#1268) ============
  7440. getLibraryTags: () =>
  7441. request<LibraryTag[]>('/library/tags'),
  7442. createLibraryTag: (name: string) =>
  7443. request<LibraryTag>('/library/tags', {
  7444. method: 'POST',
  7445. body: JSON.stringify({ name }),
  7446. }),
  7447. updateLibraryTag: (id: number, name: string) =>
  7448. request<LibraryTag>(`/library/tags/${id}`, {
  7449. method: 'PATCH',
  7450. body: JSON.stringify({ name }),
  7451. }),
  7452. deleteLibraryTag: (id: number) =>
  7453. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7454. bulkAssignLibraryTags: (
  7455. fileIds: number[],
  7456. tagIds: number[],
  7457. action: 'add' | 'remove' | 'replace',
  7458. ) =>
  7459. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7460. method: 'POST',
  7461. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7462. }),
  7463. // ============ Variant groups (#671 / #2570) ============
  7464. // "These files are the same job sliced for different printers." Consumed from
  7465. // both ends: the queue picks a printer and needs the matching file, the File
  7466. // Manager's print action has the printer and needs the same match.
  7467. createVariantGroup: (
  7468. members: { library_file_id: number; target_model?: string }[],
  7469. name?: string,
  7470. ) =>
  7471. request<VariantGroup>('/library/variant-groups', {
  7472. method: 'POST',
  7473. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7474. }),
  7475. getVariantGroup: (groupId: number) =>
  7476. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7477. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7478. uploadLibraryFile: async (
  7479. file: File,
  7480. folderId?: number | null,
  7481. generateStlThumbnails: boolean = true
  7482. ): Promise<LibraryFileUploadResponse> => {
  7483. const formData = new FormData();
  7484. formData.append('file', file);
  7485. const params = new URLSearchParams();
  7486. if (folderId) params.set('folder_id', String(folderId));
  7487. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7488. const headers: Record<string, string> = {};
  7489. if (authToken) {
  7490. headers['Authorization'] = `Bearer ${authToken}`;
  7491. }
  7492. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7493. method: 'POST',
  7494. headers,
  7495. body: formData,
  7496. });
  7497. if (!response.ok) {
  7498. const error = await response.json().catch(() => ({}));
  7499. throw new Error(error.detail || `HTTP ${response.status}`);
  7500. }
  7501. return response.json();
  7502. },
  7503. extractZipFile: async (
  7504. file: File,
  7505. folderId?: number | null,
  7506. preserveStructure: boolean = true,
  7507. createFolderFromZip: boolean = false,
  7508. generateStlThumbnails: boolean = true
  7509. ): Promise<ZipExtractResponse> => {
  7510. const formData = new FormData();
  7511. formData.append('file', file);
  7512. const params = new URLSearchParams();
  7513. if (folderId) params.set('folder_id', String(folderId));
  7514. params.set('preserve_structure', String(preserveStructure));
  7515. params.set('create_folder_from_zip', String(createFolderFromZip));
  7516. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7517. const headers: Record<string, string> = {};
  7518. if (authToken) {
  7519. headers['Authorization'] = `Bearer ${authToken}`;
  7520. }
  7521. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7522. method: 'POST',
  7523. headers,
  7524. body: formData,
  7525. });
  7526. if (!response.ok) {
  7527. const error = await response.json().catch(() => ({}));
  7528. throw new Error(error.detail || `HTTP ${response.status}`);
  7529. }
  7530. return response.json();
  7531. },
  7532. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7533. request<LibraryFile>(`/library/files/${id}`, {
  7534. method: 'PUT',
  7535. body: JSON.stringify(data),
  7536. }),
  7537. deleteLibraryFile: (id: number) =>
  7538. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7539. // ========== Library Trash (#1008) ==========
  7540. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7541. request<LibraryPurgePreview>(
  7542. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7543. ),
  7544. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7545. request<{ moved_to_trash: number }>('/library/purge', {
  7546. method: 'POST',
  7547. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7548. }),
  7549. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7550. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7551. restoreLibraryTrash: (fileId: number) =>
  7552. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7553. hardDeleteLibraryTrash: (fileId: number) =>
  7554. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7555. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7556. getLibraryTrashSettings: () =>
  7557. request<LibraryTrashSettings>('/library/trash/settings'),
  7558. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7559. request<LibraryTrashSettings>('/library/trash/settings', {
  7560. method: 'PUT',
  7561. body: JSON.stringify(body),
  7562. }),
  7563. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7564. createLibrarySlicerToken: (fileId: number) =>
  7565. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7566. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7567. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7568. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7569. const headers: Record<string, string> = {};
  7570. if (authToken) {
  7571. headers['Authorization'] = `Bearer ${authToken}`;
  7572. }
  7573. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7574. if (!response.ok) {
  7575. const error = await response.json().catch(() => ({}));
  7576. throw new Error(error.detail || `HTTP ${response.status}`);
  7577. }
  7578. const disposition = response.headers.get('Content-Disposition');
  7579. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7580. const blob = await response.blob();
  7581. const url = window.URL.createObjectURL(blob);
  7582. const a = document.createElement('a');
  7583. a.href = url;
  7584. a.download = downloadFilename;
  7585. document.body.appendChild(a);
  7586. a.click();
  7587. document.body.removeChild(a);
  7588. window.URL.revokeObjectURL(url);
  7589. },
  7590. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7591. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7592. // previews render in the browser; the first render is posted back so the
  7593. // grid gets a thumbnail without a server-side renderer for those formats.
  7594. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7595. const formData = new FormData();
  7596. formData.append('thumbnail', thumbnail, 'preview.png');
  7597. const headers: Record<string, string> = {};
  7598. if (authToken) {
  7599. headers['Authorization'] = `Bearer ${authToken}`;
  7600. }
  7601. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7602. method: 'POST',
  7603. headers,
  7604. body: formData,
  7605. });
  7606. if (!response.ok) {
  7607. const error = await response.json().catch(() => ({}));
  7608. throw new Error(error.detail || `HTTP ${response.status}`);
  7609. }
  7610. return response.json();
  7611. },
  7612. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7613. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7614. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7615. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7616. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7617. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7618. const formData = new FormData();
  7619. formData.append('file', file);
  7620. const headers: Record<string, string> = {};
  7621. if (authToken) {
  7622. headers['Authorization'] = `Bearer ${authToken}`;
  7623. }
  7624. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7625. method: 'POST',
  7626. headers,
  7627. body: formData,
  7628. });
  7629. if (!response.ok) {
  7630. const error = await response.json().catch(() => ({}));
  7631. throw new Error(error.detail || `HTTP ${response.status}`);
  7632. }
  7633. return response.json();
  7634. },
  7635. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7636. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7637. method: 'DELETE',
  7638. }),
  7639. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7640. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7641. request<{ status: string; moved: number }>('/library/files/move', {
  7642. method: 'POST',
  7643. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7644. }),
  7645. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7646. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7647. method: 'POST',
  7648. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7649. }),
  7650. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7651. batchGenerateStlThumbnails: (options: {
  7652. file_ids?: number[];
  7653. folder_id?: number;
  7654. all_missing?: boolean;
  7655. }) =>
  7656. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7657. method: 'POST',
  7658. body: JSON.stringify(options),
  7659. }),
  7660. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7661. request<LibraryFileUploadResponse>('/library/files/combine', {
  7662. method: 'POST',
  7663. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7664. }),
  7665. getLibraryFilePlates: (fileId: number) =>
  7666. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7667. getLibraryFileFilamentRequirements: (
  7668. fileId: number,
  7669. plateId?: number,
  7670. requestId?: string,
  7671. /** Ask for one entry per project slot instead of only the slots this
  7672. * plate consumes. The slice modal needs it: its filament list is
  7673. * positional, so a source whose only used slot is 4 must still present
  7674. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7675. * AMS matching must NOT set this — it wants the used-only list. */
  7676. fullSlots?: boolean,
  7677. ) => {
  7678. const qs = new URLSearchParams();
  7679. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7680. if (requestId) qs.set('request_id', requestId);
  7681. if (fullSlots) qs.set('full_slots', 'true');
  7682. return request<{
  7683. file_id: number;
  7684. filename: string;
  7685. filaments: Array<{
  7686. slot_id: number;
  7687. type: string;
  7688. color: string;
  7689. used_grams: number;
  7690. used_meters: number;
  7691. used_in_plate?: boolean;
  7692. }>;
  7693. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7694. },
  7695. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7696. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7697. * spinner + persistent toast can show "Generating G-code (45%)" while
  7698. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7699. * have an entry — early race window — or it expired) so the poller
  7700. * can keep trying. */
  7701. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7702. try {
  7703. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7704. } catch {
  7705. return null;
  7706. }
  7707. },
  7708. // GitHub Backup
  7709. getGitHubBackupConfig: () =>
  7710. request<GitHubBackupConfig | null>('/github-backup/config'),
  7711. getGitHubBackupCloudAccounts: () =>
  7712. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7713. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7714. request<GitHubBackupConfig>('/github-backup/config', {
  7715. method: 'POST',
  7716. body: JSON.stringify(config),
  7717. }),
  7718. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7719. request<GitHubBackupConfig>('/github-backup/config', {
  7720. method: 'PATCH',
  7721. body: JSON.stringify(config),
  7722. }),
  7723. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7724. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7725. method: 'POST',
  7726. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7727. }),
  7728. testGitHubStoredConnection: () =>
  7729. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7730. triggerGitHubBackup: () =>
  7731. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7732. getGitHubBackupStatus: () =>
  7733. request<GitHubBackupStatus>('/github-backup/status'),
  7734. getGitHubBackupLogs: (limit: number = 50) =>
  7735. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7736. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7737. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7738. // Restore from a Git backup (#2656)
  7739. getGitHubBackupCommits: (limit: number = 20) =>
  7740. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7741. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7742. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7743. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7744. request<GitHubRestoreResponse>('/github-backup/restore', {
  7745. method: 'POST',
  7746. body: JSON.stringify(payload),
  7747. }),
  7748. // Scheduled local backups
  7749. getLocalBackupStatus: () =>
  7750. request<LocalBackupStatus>('/local-backup/status'),
  7751. triggerLocalBackup: () =>
  7752. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7753. checkLocalBackupPath: () =>
  7754. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7755. getLocalBackups: () =>
  7756. request<LocalBackupFile[]>('/local-backup/backups'),
  7757. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7758. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7759. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7760. });
  7761. if (!response.ok) throw new Error('Download failed');
  7762. const blob = await response.blob();
  7763. return { blob, filename };
  7764. },
  7765. restoreLocalBackup: (filename: string) =>
  7766. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7767. deleteLocalBackup: (filename: string) =>
  7768. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7769. // Obico AI failure detection
  7770. getObicoStatus: () =>
  7771. request<ObicoStatus>('/obico/status'),
  7772. getObicoPrinterStatus: () =>
  7773. request<ObicoPrinterStatus>('/obico/printer-status'),
  7774. // `token` is sent as-is, so an empty string tests with no token at all.
  7775. // Omitting the argument makes the backend fall back to the saved token.
  7776. testObicoConnection: (url: string, token?: string) =>
  7777. request<ObicoTestConnection>('/obico/test-connection', {
  7778. method: 'POST',
  7779. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7780. }),
  7781. // Slicer API — slice in the background. Both endpoints return 202 + a
  7782. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  7783. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  7784. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  7785. method: 'POST',
  7786. body: JSON.stringify(body),
  7787. }),
  7788. sliceArchive: (archiveId: number, body: SliceRequest) =>
  7789. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  7790. method: 'POST',
  7791. body: JSON.stringify(body),
  7792. }),
  7793. getSliceJob: (jobId: number) =>
  7794. request<SliceJobState>(`/slice-jobs/${jobId}`),
  7795. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  7796. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  7797. // backend/app/api/routes/slicer_presets.py for the priority rules.
  7798. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  7799. // backend; the SliceModal's Refresh button passes true so a preset deleted
  7800. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  7801. getSlicerPresets: (options?: { refresh?: boolean }) =>
  7802. request<UnifiedPresetsResponse>(
  7803. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  7804. ),
  7805. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  7806. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  7807. listSlicerPipelines: () =>
  7808. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  7809. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  7810. request<SlicerPipeline>('/slicer-pipelines/', {
  7811. method: 'POST',
  7812. body: JSON.stringify(data),
  7813. }),
  7814. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  7815. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  7816. method: 'PUT',
  7817. body: JSON.stringify(data),
  7818. }),
  7819. deleteSlicerPipeline: (id: number) =>
  7820. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  7821. checkPipelineEligibility: (
  7822. pipelineId: number,
  7823. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  7824. ) =>
  7825. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  7826. method: 'POST',
  7827. body: JSON.stringify(
  7828. source.kind === 'libraryFile'
  7829. ? { source_library_file_id: source.id }
  7830. : { source_archive_id: source.id },
  7831. ),
  7832. }),
  7833. runPipeline: (
  7834. pipelineId: number,
  7835. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  7836. force = false,
  7837. copies = 1,
  7838. ) =>
  7839. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  7840. method: 'POST',
  7841. body: JSON.stringify({
  7842. ...(source.kind === 'libraryFile'
  7843. ? { source_library_file_id: source.id }
  7844. : { source_archive_id: source.id }),
  7845. force,
  7846. copies,
  7847. }),
  7848. }),
  7849. listPipelineRuns: (pipelineId: number, limit = 5) =>
  7850. request<PipelineRunListResponse>(
  7851. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  7852. ),
  7853. // Dashboard list across all pipelines (#1425 PR C).
  7854. listAllPipelineRuns: (params: {
  7855. limit?: number;
  7856. offset?: number;
  7857. pipelineId?: number;
  7858. status?: string;
  7859. targetPrinterId?: number;
  7860. targetModelClass?: string;
  7861. } = {}) => {
  7862. const search = new URLSearchParams();
  7863. if (params.limit) search.set('limit', String(params.limit));
  7864. if (params.offset) search.set('offset', String(params.offset));
  7865. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  7866. if (params.status) search.set('status', params.status);
  7867. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  7868. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  7869. const q = search.toString();
  7870. return request<PipelineRunListResponse>(
  7871. `/pipeline-runs${q ? '?' + q : ''}`,
  7872. );
  7873. },
  7874. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  7875. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  7876. // runs are preserved.
  7877. clearTerminalPipelineRuns: () =>
  7878. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  7879. cancelPipelineRun: (runId: number) =>
  7880. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  7881. retryFailedPipelineRun: (runId: number) =>
  7882. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  7883. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  7884. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  7885. // SliceModal uses this to classify cloud / standard presets by their
  7886. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  7887. getSlicerPrinterModels: () =>
  7888. request<Record<string, string>>('/slicer/printer-models'),
  7889. getSlicerLoadedSpools: () =>
  7890. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  7891. /**
  7892. * Effective values of a process preset, with its `inherits:` chain flattened
  7893. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  7894. * otherwise show the option schema's compiled-in defaults (a preset setting a
  7895. * 0.42mm line width appears as the C++ default of 0).
  7896. *
  7897. * `resolved: false` means the values could not be obtained -- sidecar offline,
  7898. * too old for the endpoint, or slicing not configured -- and the caller should
  7899. * fall back to schema defaults rather than treat it as a failure.
  7900. */
  7901. getSlicerPresetValues: (ref: PresetRef) =>
  7902. request<SlicerPresetValues>(
  7903. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  7904. ),
  7905. // Local Presets (OrcaSlicer imports)
  7906. getLocalPresets: () =>
  7907. request<LocalPresetsResponse>('/local-presets/'),
  7908. importLocalPresets: (formData: FormData) =>
  7909. fetch(`${API_BASE}/local-presets/import`, {
  7910. method: 'POST',
  7911. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7912. body: formData,
  7913. }).then(async (res) => {
  7914. if (!res.ok) {
  7915. const err = await res.json().catch(() => ({}));
  7916. throw new Error(err.detail || `HTTP ${res.status}`);
  7917. }
  7918. return res.json() as Promise<ImportResponse>;
  7919. }),
  7920. deleteLocalPreset: (id: number) =>
  7921. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  7922. };
  7923. // AMS History types
  7924. export interface AMSHistoryPoint {
  7925. recorded_at: string;
  7926. humidity: number | null;
  7927. humidity_raw: number | null;
  7928. temperature: number | null;
  7929. }
  7930. export interface AMSHistoryResponse {
  7931. printer_id: number;
  7932. ams_id: number;
  7933. data: AMSHistoryPoint[];
  7934. min_humidity: number | null;
  7935. max_humidity: number | null;
  7936. avg_humidity: number | null;
  7937. min_temperature: number | null;
  7938. max_temperature: number | null;
  7939. avg_temperature: number | null;
  7940. }
  7941. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  7942. export interface HeaterHistoryPoint {
  7943. recorded_at: string;
  7944. value: number | null;
  7945. target: number | null;
  7946. }
  7947. export interface HeaterSeries {
  7948. sensor_kind: HeaterSensorKind;
  7949. data: HeaterHistoryPoint[];
  7950. min_value: number | null;
  7951. max_value: number | null;
  7952. avg_value: number | null;
  7953. }
  7954. export interface PrinterSensorHistoryResponse {
  7955. printer_id: number;
  7956. series: HeaterSeries[];
  7957. }
  7958. // System Info types
  7959. export interface SystemInfo {
  7960. app: {
  7961. version: string;
  7962. base_dir: string;
  7963. archive_dir: string;
  7964. };
  7965. database: {
  7966. engine: string;
  7967. version: string;
  7968. archives: number;
  7969. archives_completed: number;
  7970. archives_failed: number;
  7971. archives_printing: number;
  7972. printers: number;
  7973. filaments: number;
  7974. projects: number;
  7975. smart_plugs: number;
  7976. total_print_time_seconds: number;
  7977. total_print_time_formatted: string;
  7978. total_filament_grams: number;
  7979. total_filament_kg: number;
  7980. };
  7981. printers: {
  7982. total: number;
  7983. connected: number;
  7984. connected_list: Array<{
  7985. id: number;
  7986. name: string;
  7987. state: string;
  7988. model: string;
  7989. }>;
  7990. };
  7991. storage: {
  7992. archive_size_bytes: number;
  7993. archive_size_formatted: string;
  7994. database_size_bytes: number;
  7995. database_size_formatted: string;
  7996. disk_total_bytes: number;
  7997. disk_total_formatted: string;
  7998. disk_used_bytes: number;
  7999. disk_used_formatted: string;
  8000. disk_free_bytes: number;
  8001. disk_free_formatted: string;
  8002. disk_percent_used: number;
  8003. };
  8004. system: {
  8005. platform: string;
  8006. platform_release: string;
  8007. platform_version: string;
  8008. architecture: string;
  8009. hostname: string;
  8010. python_version: string;
  8011. uptime_seconds: number;
  8012. uptime_formatted: string;
  8013. boot_time: string;
  8014. };
  8015. memory: {
  8016. total_bytes: number;
  8017. total_formatted: string;
  8018. available_bytes: number;
  8019. available_formatted: string;
  8020. used_bytes: number;
  8021. used_formatted: string;
  8022. percent_used: number;
  8023. };
  8024. cpu: {
  8025. count: number;
  8026. count_logical: number;
  8027. percent: number;
  8028. };
  8029. }
  8030. export interface StorageUsageCategory {
  8031. key: string;
  8032. label: string;
  8033. bytes: number;
  8034. formatted: string;
  8035. percent_of_total: number;
  8036. }
  8037. export interface StorageUsageOtherItem {
  8038. bucket: string;
  8039. label: string;
  8040. kind: 'system' | 'data';
  8041. deletable: boolean;
  8042. bytes: number;
  8043. formatted: string;
  8044. percent_of_total: number;
  8045. }
  8046. export interface StorageUsageResponse {
  8047. roots: string[];
  8048. total_bytes: number;
  8049. total_formatted: string;
  8050. categories: StorageUsageCategory[];
  8051. other_breakdown: StorageUsageOtherItem[];
  8052. scan_errors: number;
  8053. generated_at: string;
  8054. cache: {
  8055. hit: boolean;
  8056. age_seconds: number;
  8057. max_age_seconds: number;
  8058. };
  8059. }
  8060. // Library (File Manager) types
  8061. export interface LibraryFolderTree {
  8062. id: number;
  8063. name: string;
  8064. parent_id: number | null;
  8065. project_id: number | null;
  8066. archive_id: number | null;
  8067. project_name: string | null;
  8068. archive_name: string | null;
  8069. is_external: boolean;
  8070. external_path: string | null;
  8071. external_readonly: boolean;
  8072. file_count: number;
  8073. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8074. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8075. latest_activity_at: string | null;
  8076. // Ownership (#3201). can_* are for the current user: what the File
  8077. // Manager may offer on this folder. The backend enforces the same rules.
  8078. created_by_id: number | null;
  8079. shared: boolean;
  8080. can_write: boolean;
  8081. can_rename: boolean;
  8082. can_delete: boolean;
  8083. children: LibraryFolderTree[];
  8084. }
  8085. export interface LibraryFolder {
  8086. id: number;
  8087. name: string;
  8088. parent_id: number | null;
  8089. project_id: number | null;
  8090. archive_id: number | null;
  8091. project_name: string | null;
  8092. archive_name: string | null;
  8093. is_external: boolean;
  8094. external_path: string | null;
  8095. external_readonly: boolean;
  8096. external_show_hidden: boolean;
  8097. file_count: number;
  8098. latest_activity_at: string | null;
  8099. // Ownership (#3201). can_* are for the current user: what the File
  8100. // Manager may offer on this folder. The backend enforces the same rules.
  8101. created_by_id: number | null;
  8102. shared: boolean;
  8103. can_write: boolean;
  8104. can_rename: boolean;
  8105. can_delete: boolean;
  8106. created_at: string;
  8107. updated_at: string;
  8108. }
  8109. export interface LibraryFolderCreate {
  8110. name: string;
  8111. parent_id?: number | null;
  8112. project_id?: number | null;
  8113. archive_id?: number | null;
  8114. }
  8115. export interface ExternalFolderCreate {
  8116. name: string;
  8117. external_path: string;
  8118. readonly?: boolean;
  8119. show_hidden?: boolean;
  8120. parent_id?: number | null;
  8121. }
  8122. export interface LibraryFolderUpdate {
  8123. name?: string;
  8124. parent_id?: number | null;
  8125. project_id?: number | null; // 0 to unlink
  8126. archive_id?: number | null; // 0 to unlink
  8127. shared?: boolean; // library:update_all only (#3201)
  8128. }
  8129. export interface LibraryFileDuplicate {
  8130. id: number;
  8131. filename: string;
  8132. folder_id: number | null;
  8133. folder_name: string | null;
  8134. created_at: string;
  8135. }
  8136. export interface LibraryFile {
  8137. id: number;
  8138. folder_id: number | null;
  8139. folder_name: string | null;
  8140. project_id: number | null;
  8141. project_name: string | null;
  8142. is_external: boolean;
  8143. filename: string;
  8144. file_path: string;
  8145. file_type: string;
  8146. file_size: number;
  8147. file_hash: string | null;
  8148. thumbnail_path: string | null;
  8149. metadata: Record<string, unknown> | null;
  8150. print_count: number;
  8151. last_printed_at: string | null;
  8152. notes: string | null;
  8153. // User link + photos of the printed result (#3077); source_url is the
  8154. // read-only import provenance (MakerWorld).
  8155. external_url: string | null;
  8156. photos: string[];
  8157. source_url: string | null;
  8158. duplicates: LibraryFileDuplicate[] | null;
  8159. duplicate_count: number;
  8160. // User tracking (Issue #206)
  8161. created_by_id: number | null;
  8162. created_by_username: string | null;
  8163. created_at: string;
  8164. updated_at: string;
  8165. // Metadata fields
  8166. print_name: string | null;
  8167. print_time_seconds: number | null;
  8168. filament_used_grams: number | null;
  8169. sliced_for_model: string | null;
  8170. }
  8171. export interface LibraryTagSummary {
  8172. id: number;
  8173. name: string;
  8174. }
  8175. export interface LibraryFileListItem {
  8176. id: number;
  8177. folder_id: number | null;
  8178. is_external: boolean;
  8179. filename: string;
  8180. file_type: string;
  8181. file_size: number;
  8182. thumbnail_path: string | null;
  8183. print_count: number;
  8184. duplicate_count: number;
  8185. // User tracking (Issue #206)
  8186. created_by_id: number | null;
  8187. created_by_username: string | null;
  8188. created_at: string;
  8189. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8190. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8191. fs_modified_at: string | null;
  8192. print_name: string | null;
  8193. print_time_seconds: number | null;
  8194. filament_used_grams: number | null;
  8195. sliced_for_model: string | null;
  8196. // Tags assigned to this file (#1268). The backend always emits an empty
  8197. // array when a file has no tags, but the field is typed optional so any
  8198. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8199. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8200. tags?: LibraryTagSummary[];
  8201. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8202. // group, which may include files in other folders — never the number of
  8203. // matching rows on screen. 0 when the file is not grouped.
  8204. variant_group_id?: number | null;
  8205. variant_count?: number;
  8206. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8207. // mocks construct list items without them. Read sites default to falsy.
  8208. external_url?: string | null;
  8209. has_notes?: boolean;
  8210. photo_count?: number;
  8211. }
  8212. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8213. export interface VariantGroupMember {
  8214. library_file_id: number;
  8215. filename: string;
  8216. target_model: string;
  8217. position: number;
  8218. }
  8219. export interface VariantGroup {
  8220. id: number;
  8221. name: string;
  8222. /** In priority order — index 0 wins when several printers are free at once. */
  8223. members: VariantGroupMember[];
  8224. }
  8225. // Library tag catalog (#1268)
  8226. export interface LibraryTag {
  8227. id: number;
  8228. name: string;
  8229. file_count: number;
  8230. created_at: string;
  8231. updated_at: string;
  8232. }
  8233. export interface LibraryTagBulkAssignResult {
  8234. files_updated: number;
  8235. associations_added: number;
  8236. associations_removed: number;
  8237. }
  8238. export interface LibraryFileUpdate {
  8239. filename?: string;
  8240. folder_id?: number | null;
  8241. project_id?: number | null;
  8242. notes?: string | null;
  8243. external_url?: string | null;
  8244. }
  8245. // Library trash (#1008)
  8246. export interface LibraryTrashItem {
  8247. id: number;
  8248. filename: string;
  8249. file_size: number;
  8250. thumbnail_path: string | null;
  8251. folder_id: number | null;
  8252. folder_name: string | null;
  8253. created_by_id: number | null;
  8254. created_by_username: string | null;
  8255. deleted_at: string;
  8256. auto_purge_at: string;
  8257. }
  8258. export interface LibraryTrashListResponse {
  8259. items: LibraryTrashItem[];
  8260. total: number;
  8261. retention_days: number;
  8262. }
  8263. export interface LibraryPurgePreview {
  8264. count: number;
  8265. total_bytes: number;
  8266. sample_filenames: string[];
  8267. older_than_days: number;
  8268. include_never_printed: boolean;
  8269. }
  8270. export interface LibraryTrashSettings {
  8271. retention_days: number;
  8272. auto_purge_enabled: boolean;
  8273. auto_purge_days: number;
  8274. auto_purge_include_never_printed: boolean;
  8275. }
  8276. export interface ArchivePurgePreview {
  8277. count: number;
  8278. total_bytes: number;
  8279. sample_filenames: string[];
  8280. older_than_days: number;
  8281. }
  8282. export interface ArchivePurgeSettings {
  8283. enabled: boolean;
  8284. days: number;
  8285. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8286. // contribution drops from Quick Stats too. Default false — soft-delete,
  8287. // Quick Stats preserved.
  8288. purge_stats: boolean;
  8289. }
  8290. export interface LibraryFileUploadResponse {
  8291. id: number;
  8292. filename: string;
  8293. file_type: string;
  8294. file_size: number;
  8295. thumbnail_path: string | null;
  8296. duplicate_of: number | null;
  8297. metadata: Record<string, unknown> | null;
  8298. }
  8299. export interface LibraryStats {
  8300. total_files: number;
  8301. total_folders: number;
  8302. total_size_bytes: number;
  8303. files_by_type: Record<string, number>;
  8304. total_prints: number;
  8305. disk_free_bytes: number;
  8306. disk_total_bytes: number;
  8307. disk_used_bytes: number;
  8308. }
  8309. export interface ZipExtractResult {
  8310. filename: string;
  8311. file_id: number;
  8312. folder_id: number | null;
  8313. }
  8314. export interface ZipExtractError {
  8315. filename: string;
  8316. error: string;
  8317. }
  8318. export interface ZipExtractResponse {
  8319. extracted: number;
  8320. folders_created: number;
  8321. files: ZipExtractResult[];
  8322. errors: ZipExtractError[];
  8323. }
  8324. // STL Thumbnail Generation types
  8325. export interface BatchThumbnailResult {
  8326. file_id: number;
  8327. filename: string;
  8328. success: boolean;
  8329. error?: string | null;
  8330. }
  8331. export interface BatchThumbnailResponse {
  8332. processed: number;
  8333. succeeded: number;
  8334. failed: number;
  8335. results: BatchThumbnailResult[];
  8336. }
  8337. // Discovery types
  8338. export interface DiscoveredPrinter {
  8339. serial: string;
  8340. name: string;
  8341. ip_address: string;
  8342. model: string | null;
  8343. discovered_at: string | null;
  8344. }
  8345. export interface DiscoveryStatus {
  8346. running: boolean;
  8347. }
  8348. export interface DiscoveryInfo {
  8349. is_docker: boolean;
  8350. ssdp_running: boolean;
  8351. scan_running: boolean;
  8352. subnets: string[];
  8353. }
  8354. export interface SubnetScanStatus {
  8355. running: boolean;
  8356. scanned: number;
  8357. total: number;
  8358. }
  8359. // Discovery API
  8360. export const discoveryApi = {
  8361. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8362. startDiscovery: (duration: number = 10) =>
  8363. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8364. stopDiscovery: () =>
  8365. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8366. getDiscoveredPrinters: () =>
  8367. request<DiscoveredPrinter[]>('/discovery/printers'),
  8368. // Subnet scanning (for Docker environments)
  8369. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8370. request<SubnetScanStatus>('/discovery/scan', {
  8371. method: 'POST',
  8372. body: JSON.stringify({ subnet, timeout }),
  8373. }),
  8374. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8375. stopSubnetScan: () =>
  8376. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8377. };
  8378. // Virtual Printer types
  8379. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8380. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8381. // accepted by the backend so older API clients keep working, but new code
  8382. // should send the canonical names.
  8383. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  8384. export interface VirtualPrinterProxyStatus {
  8385. running: boolean;
  8386. target_host: string;
  8387. ftp_port: number;
  8388. mqtt_port: number;
  8389. ftp_connections: number;
  8390. mqtt_connections: number;
  8391. }
  8392. export interface VirtualPrinterStatus {
  8393. enabled: boolean;
  8394. running: boolean;
  8395. mode: VirtualPrinterMode;
  8396. name: string;
  8397. serial: string;
  8398. model: string;
  8399. model_name: string;
  8400. pending_files: number;
  8401. target_printer_ip?: string; // For proxy mode
  8402. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8403. }
  8404. export interface VirtualPrinterSettings {
  8405. tailscale_disabled: boolean;
  8406. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8407. status: VirtualPrinterStatus;
  8408. }
  8409. export interface NetworkInterface {
  8410. name: string;
  8411. ip: string;
  8412. netmask: string;
  8413. subnet: string;
  8414. is_alias?: boolean;
  8415. label?: string;
  8416. }
  8417. export interface PendingUpload {
  8418. id: number;
  8419. filename: string;
  8420. // Resolved name the review card should show — mirrors what archive_print
  8421. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8422. // back to the stripped filename stem when the 3MF has no embedded title or
  8423. // the operator has chosen the "filename" archive-name source.
  8424. display_name: string;
  8425. file_size: number;
  8426. source_ip: string | null;
  8427. status: string;
  8428. tags: string | null;
  8429. notes: string | null;
  8430. project_id: number | null;
  8431. uploaded_at: string;
  8432. }
  8433. // Virtual Printer API
  8434. export const virtualPrinterApi = {
  8435. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8436. updateSettings: (data: {
  8437. tailscale_disabled?: boolean;
  8438. archive_name_source?: 'metadata' | 'filename';
  8439. }) => {
  8440. const params = new URLSearchParams();
  8441. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8442. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8443. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8444. method: 'PUT',
  8445. });
  8446. },
  8447. };
  8448. // Multi Virtual Printer API
  8449. export interface VirtualPrinterConfig {
  8450. id: number;
  8451. name: string;
  8452. enabled: boolean;
  8453. mode: VirtualPrinterMode;
  8454. model: string | null;
  8455. model_name: string | null;
  8456. access_code_set: boolean;
  8457. serial: string;
  8458. target_printer_id: number | null;
  8459. auto_dispatch: boolean;
  8460. queue_force_color_match: boolean;
  8461. save_ams_mapping: boolean;
  8462. gcode_injection: boolean;
  8463. tailscale_disabled: boolean;
  8464. bind_ip: string | null;
  8465. remote_interface_ip: string | null;
  8466. position: number;
  8467. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8468. }
  8469. export interface VirtualPrinterListResponse {
  8470. printers: VirtualPrinterConfig[];
  8471. models: Record<string, string>;
  8472. }
  8473. export const multiVirtualPrinterApi = {
  8474. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8475. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8476. create: (data: {
  8477. name?: string;
  8478. enabled?: boolean;
  8479. mode?: string;
  8480. model?: string;
  8481. access_code?: string;
  8482. target_printer_id?: number;
  8483. auto_dispatch?: boolean;
  8484. queue_force_color_match?: boolean;
  8485. save_ams_mapping?: boolean;
  8486. gcode_injection?: boolean;
  8487. bind_ip?: string;
  8488. remote_interface_ip?: string;
  8489. }) =>
  8490. request<VirtualPrinterConfig>('/virtual-printers', {
  8491. method: 'POST',
  8492. body: JSON.stringify(data),
  8493. }),
  8494. update: (id: number, data: {
  8495. name?: string;
  8496. enabled?: boolean;
  8497. mode?: string;
  8498. model?: string;
  8499. access_code?: string;
  8500. target_printer_id?: number;
  8501. auto_dispatch?: boolean;
  8502. queue_force_color_match?: boolean;
  8503. save_ams_mapping?: boolean;
  8504. gcode_injection?: boolean;
  8505. tailscale_disabled?: boolean;
  8506. bind_ip?: string;
  8507. remote_interface_ip?: string;
  8508. }) =>
  8509. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8510. method: 'PUT',
  8511. body: JSON.stringify(data),
  8512. }),
  8513. remove: (id: number) =>
  8514. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8515. method: 'DELETE',
  8516. }),
  8517. getTailscaleStatus: () =>
  8518. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8519. getCaCertificate: () =>
  8520. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8521. diagnose: (id: number) =>
  8522. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8523. };
  8524. /** The shared CA certificate every virtual printer presents — imported once
  8525. * into the slicer's trust store. Only the public certificate is returned. */
  8526. export interface VPCaCertificate {
  8527. pem: string;
  8528. fingerprint_sha256: string;
  8529. not_valid_after: string;
  8530. }
  8531. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8532. export interface VPDiagnosticCheck {
  8533. id:
  8534. | 'enabled'
  8535. | 'running'
  8536. | 'bind_interface'
  8537. | 'access_code'
  8538. | 'target_printer'
  8539. | 'port_ftps'
  8540. | 'port_mqtt'
  8541. | 'port_bind'
  8542. | 'certificate';
  8543. status: VPDiagnosticStatus;
  8544. params: Record<string, string | number>;
  8545. }
  8546. export interface VPDiagnosticResult {
  8547. vp_id: number;
  8548. vp_name: string;
  8549. mode: string;
  8550. overall: 'ok' | 'warnings' | 'problems';
  8551. checks: VPDiagnosticCheck[];
  8552. }
  8553. export interface TailscaleStatusResponse {
  8554. available: boolean;
  8555. fqdn: string;
  8556. hostname: string;
  8557. tailnet_name: string;
  8558. tailscale_ips: string[];
  8559. error: string | null;
  8560. }
  8561. // Pending Uploads API
  8562. export const pendingUploadsApi = {
  8563. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8564. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8565. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8566. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8567. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  8568. method: 'POST',
  8569. body: JSON.stringify(data || {}),
  8570. }),
  8571. discard: (id: number) =>
  8572. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8573. archiveAll: () =>
  8574. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8575. discardAll: () =>
  8576. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8577. };
  8578. // Firmware API Types
  8579. export interface AvailableFirmwareVersion {
  8580. version: string;
  8581. file_available: boolean;
  8582. download_url: string | null;
  8583. release_notes: string | null;
  8584. release_time: string | null;
  8585. }
  8586. export interface FirmwareUpdateInfo {
  8587. printer_id: number;
  8588. printer_name: string;
  8589. model: string | null;
  8590. current_version: string | null;
  8591. latest_version: string | null;
  8592. update_available: boolean;
  8593. download_url: string | null;
  8594. release_notes: string | null;
  8595. available_versions: AvailableFirmwareVersion[];
  8596. }
  8597. export interface FirmwareUploadPrepare {
  8598. can_proceed: boolean;
  8599. sd_card_present: boolean;
  8600. sd_card_free_space: number;
  8601. firmware_size: number;
  8602. space_sufficient: boolean;
  8603. update_available: boolean;
  8604. current_version: string | null;
  8605. latest_version: string | null;
  8606. target_version: string | null;
  8607. firmware_filename: string | null;
  8608. errors: string[];
  8609. }
  8610. export interface FirmwareUploadStatus {
  8611. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8612. progress: number;
  8613. message: string;
  8614. error: string | null;
  8615. firmware_filename: string | null;
  8616. firmware_version: string | null;
  8617. }
  8618. // Firmware API
  8619. export const firmwareApi = {
  8620. checkUpdates: () =>
  8621. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8622. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8623. prepareUpload: (printerId: number, version?: string) =>
  8624. request<FirmwareUploadPrepare>(
  8625. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8626. ),
  8627. startUpload: (printerId: number, version?: string) =>
  8628. request<{ started: boolean; message: string }>(
  8629. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8630. { method: 'POST' },
  8631. ),
  8632. getUploadStatus: (printerId: number) =>
  8633. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8634. };
  8635. // Support types
  8636. export interface DebugLoggingState {
  8637. enabled: boolean;
  8638. enabled_at: string | null;
  8639. duration_seconds: number | null;
  8640. }
  8641. export interface LogEntry {
  8642. timestamp: string;
  8643. level: string;
  8644. logger_name: string;
  8645. message: string;
  8646. }
  8647. export interface LogsResponse {
  8648. entries: LogEntry[];
  8649. total_in_file: number;
  8650. filtered_count: number;
  8651. }
  8652. // Support API
  8653. export const supportApi = {
  8654. getDebugLoggingState: () =>
  8655. request<DebugLoggingState>('/support/debug-logging'),
  8656. setDebugLogging: (enabled: boolean) =>
  8657. request<DebugLoggingState>('/support/debug-logging', {
  8658. method: 'POST',
  8659. body: JSON.stringify({ enabled }),
  8660. }),
  8661. downloadSupportBundle: async () => {
  8662. const headers: Record<string, string> = {};
  8663. if (authToken) {
  8664. headers['Authorization'] = `Bearer ${authToken}`;
  8665. }
  8666. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8667. if (!response.ok) {
  8668. const error = await response.json().catch(() => ({}));
  8669. throw new Error(error.detail || `HTTP ${response.status}`);
  8670. }
  8671. // Get filename from Content-Disposition header or use default
  8672. const disposition = response.headers.get('Content-Disposition');
  8673. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8674. // Download the blob
  8675. const blob = await response.blob();
  8676. const url = window.URL.createObjectURL(blob);
  8677. const a = document.createElement('a');
  8678. a.href = url;
  8679. a.download = filename;
  8680. document.body.appendChild(a);
  8681. a.click();
  8682. document.body.removeChild(a);
  8683. window.URL.revokeObjectURL(url);
  8684. },
  8685. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8686. const searchParams = new URLSearchParams();
  8687. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8688. if (params?.level) searchParams.set('level', params.level);
  8689. if (params?.search) searchParams.set('search', params.search);
  8690. const query = searchParams.toString();
  8691. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8692. },
  8693. clearLogs: () =>
  8694. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8695. };
  8696. // SpoolBuddy types
  8697. export interface SpoolBuddyDevice {
  8698. id: number;
  8699. device_id: string;
  8700. hostname: string;
  8701. ip_address: string;
  8702. backend_url?: string | null;
  8703. firmware_version: string | null;
  8704. has_nfc: boolean;
  8705. has_scale: boolean;
  8706. tare_offset: number;
  8707. calibration_factor: number;
  8708. nfc_reader_type: string | null;
  8709. nfc_connection: string | null;
  8710. display_brightness: number;
  8711. display_blank_timeout: number;
  8712. has_backlight: boolean;
  8713. last_calibrated_at: string | null;
  8714. last_seen: string | null;
  8715. pending_command: string | null;
  8716. nfc_ok: boolean;
  8717. scale_ok: boolean;
  8718. uptime_s: number;
  8719. update_status: string | null;
  8720. update_message: string | null;
  8721. system_stats: {
  8722. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8723. cpu_temp_c?: number;
  8724. cpu_count?: number;
  8725. load_avg?: number[];
  8726. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8727. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8728. system_uptime_s?: number;
  8729. } | null;
  8730. online: boolean;
  8731. }
  8732. export interface DaemonUpdateCheck {
  8733. current_version: string;
  8734. latest_version: string | null;
  8735. update_available: boolean;
  8736. }
  8737. // SpoolBuddy API
  8738. export const spoolbuddyApi = {
  8739. getDevices: () =>
  8740. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  8741. deleteDevice: (deviceId: string) =>
  8742. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  8743. method: 'DELETE',
  8744. }),
  8745. tare: (deviceId: string) =>
  8746. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  8747. method: 'POST',
  8748. body: '{}',
  8749. }),
  8750. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  8751. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  8752. method: 'POST',
  8753. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  8754. }),
  8755. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  8756. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  8757. method: 'POST',
  8758. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  8759. }),
  8760. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  8761. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  8762. method: 'PUT',
  8763. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  8764. }),
  8765. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  8766. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  8767. method: 'POST',
  8768. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  8769. }),
  8770. checkDaemonUpdate: (deviceId: string) =>
  8771. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  8772. triggerUpdate: (deviceId: string) =>
  8773. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  8774. method: 'POST',
  8775. body: '{}',
  8776. }),
  8777. getSSHPublicKey: () =>
  8778. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  8779. writeTag: (deviceId: string, spoolId: number) =>
  8780. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  8781. method: 'POST',
  8782. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  8783. }),
  8784. cancelWrite: (deviceId: string) =>
  8785. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  8786. method: 'POST',
  8787. body: '{}',
  8788. }),
  8789. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  8790. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  8791. method: 'POST',
  8792. body: JSON.stringify({ command }),
  8793. }),
  8794. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  8795. request<{ status: string; diagnostic: string; message: string }>(
  8796. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  8797. { method: 'POST', body: '{}' }
  8798. ),
  8799. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  8800. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  8801. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  8802. { method: 'GET' }
  8803. ),
  8804. };
  8805. export interface BugReportRequest {
  8806. description: string;
  8807. email?: string;
  8808. screenshot_base64?: string;
  8809. include_support_info?: boolean;
  8810. debug_logs?: string;
  8811. }
  8812. export interface BugReportResponse {
  8813. success: boolean;
  8814. message: string;
  8815. issue_url?: string;
  8816. issue_number?: number;
  8817. }
  8818. export const bugReportApi = {
  8819. submit: (data: BugReportRequest) =>
  8820. request<BugReportResponse>('/bug-report/submit', {
  8821. method: 'POST',
  8822. body: JSON.stringify(data),
  8823. }),
  8824. startLogging: () =>
  8825. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  8826. method: 'POST',
  8827. }),
  8828. stopLogging: (wasDebug: boolean) =>
  8829. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  8830. method: 'POST',
  8831. }),
  8832. };
  8833. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  8834. export interface AnnouncementText {
  8835. title: string;
  8836. body: string;
  8837. link_label?: string;
  8838. }
  8839. // One message from the Bambuddy maintainers. `texts` holds every language the
  8840. // message was written in; English is always there.
  8841. export interface Announcement {
  8842. id: string;
  8843. level: AnnouncementLevel;
  8844. texts: Record<string, AnnouncementText>;
  8845. link_url: string | null;
  8846. published_at: string | null;
  8847. expires_at: string | null;
  8848. // Past its expiry: kept as history, listed under "Earlier", never unread.
  8849. archived: boolean;
  8850. read: boolean;
  8851. }
  8852. // `visible` says whether this user may see announcements at all (switched on,
  8853. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  8854. // is published.
  8855. export interface AnnouncementList {
  8856. visible: boolean;
  8857. announcements: Announcement[];
  8858. }
  8859. export const announcementsApi = {
  8860. list: () => request<AnnouncementList>('/announcements'),
  8861. markRead: (id: string) =>
  8862. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  8863. };
  8864. export interface SponsorPromptCheckResponse {
  8865. show: boolean;
  8866. milestone?: string;
  8867. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  8868. threshold?: number;
  8869. payload?: Record<string, unknown>;
  8870. }
  8871. export const sponsorPromptApi = {
  8872. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  8873. dismiss: (milestone: string) =>
  8874. request<void>('/sponsor-prompt/dismiss', {
  8875. method: 'POST',
  8876. body: JSON.stringify({ milestone }),
  8877. }),
  8878. };