client.ts 329 KB

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