client.ts 340 KB

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