client.ts 341 KB

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