client.ts 351 KB

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