client.ts 341 KB

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