client.ts 347 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface Printer {
  395. id: number;
  396. name: string;
  397. serial_number: string;
  398. ip_address: string;
  399. // Optional because the backend only returns access_code when the caller has
  400. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  401. // API keys receive a Printer without this field.
  402. access_code?: string;
  403. model: string | null;
  404. location: string | null; // Group/location name
  405. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  406. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  407. // flow type is a real choice. Derived from the model, not the nozzle count —
  408. // only the A-series has a single variant.
  409. supports_nozzle_flow_type: boolean;
  410. is_active: boolean;
  411. auto_archive: boolean;
  412. external_camera_url: string | null;
  413. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  414. external_camera_enabled: boolean;
  415. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  416. camera_rotation: number; // 0, 90, 180, 270 degrees
  417. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  418. plate_detection_enabled: boolean; // Check plate before print
  419. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  420. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  421. created_at: string;
  422. updated_at: string;
  423. }
  424. export interface HMSError {
  425. code: string;
  426. attr: number; // Attribute value for constructing wiki URL
  427. module: number;
  428. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  429. // 3 notification, 0 invalid (#2728).
  430. severity: number;
  431. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  432. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  433. // Canonical hex identifier the firmware matches against — 8 chars for
  434. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  435. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  436. // identifier into the silent-rejection short code (#1830).
  437. full_code?: string;
  438. // The backend's catalogue sentence for this fault (#2926), from the table
  439. // generated out of Bambu Studio for this printer model (#2728). English only.
  440. // Null when Bambu publishes no text for the code. The frontend has no table of
  441. // its own: this field decides both the text and whether the fault counts.
  442. description?: string | null;
  443. }
  444. export interface HMSActionBody {
  445. print_error: string; // HMS error code (e.g. "05000070")
  446. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  447. job_id: string | null; // Optional job ID for context (if applicable)
  448. }
  449. export interface AMSTray {
  450. id: number;
  451. tray_color: string | null;
  452. tray_type: string | null;
  453. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  454. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  455. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  456. remain: number;
  457. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  458. cali_idx: number | null; // Calibration index for K-profile lookup
  459. tag_uid: string | null; // RFID tag UID (any tag)
  460. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  461. nozzle_temp_min: number | null; // Min nozzle temperature
  462. nozzle_temp_max: number | null; // Max nozzle temperature
  463. drying_temp: number | null; // RFID-recommended drying temp
  464. drying_time: number | null; // RFID-recommended drying time (hours)
  465. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  466. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  467. }
  468. export interface AMSUnit {
  469. id: number;
  470. humidity: number | null;
  471. temp: number | null;
  472. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  473. tray: AMSTray[];
  474. serial_number: string; // AMS unit serial number (from MQTT sn field)
  475. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  476. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  477. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  478. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  479. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  480. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  481. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  482. dry_filament: string | null; // Active-cycle filament name we sent
  483. module_type: string; // "ams", "ams_f1", "n3f", "n3s"
  484. }
  485. export interface ScheduledDrying {
  486. id: number;
  487. printer_id: number;
  488. ams_id: number;
  489. temp: number;
  490. duration_hours: number;
  491. filament: string;
  492. rotate_tray: boolean;
  493. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  494. status: string;
  495. waiting_reason: string | null;
  496. error_message: string | null;
  497. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  498. // rows that failed before codes existed, which show error_message instead.
  499. error_code?: string | null;
  500. created_at: string;
  501. started_at: string | null;
  502. completed_at: string | null;
  503. }
  504. export interface NozzleInfo {
  505. // Two vocabularies live in this field, by printer generation. Legacy
  506. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  507. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  508. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  509. // latter and treats anything else as "unknown", which is what makes the
  510. // material spelling harmless here.
  511. nozzle_type: string;
  512. nozzle_diameter: string; // e.g., "0.4"
  513. }
  514. export interface NozzleRackSlot {
  515. id: number;
  516. nozzle_type: string;
  517. nozzle_diameter: string;
  518. wear: number | null;
  519. stat: number | null; // Nozzle status (e.g. mounted/docked)
  520. max_temp: number;
  521. serial_number: string;
  522. filament_color: string; // RGBA hex ("00000000" = no filament)
  523. filament_id: string;
  524. filament_type: string; // Material type (e.g. "PLA", "PETG")
  525. }
  526. export interface PrintOptions {
  527. // Core AI detectors
  528. spaghetti_detector: boolean;
  529. print_halt: boolean;
  530. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  531. first_layer_inspector: boolean;
  532. printing_monitor: boolean;
  533. buildplate_marker_detector: boolean;
  534. allow_skip_parts: boolean;
  535. // Additional AI detectors (decoded from cfg bitmask)
  536. nozzle_clumping_detector: boolean;
  537. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  538. pileup_detector: boolean;
  539. pileup_sensitivity: string; // "low", "medium", "high"
  540. airprint_detector: boolean;
  541. airprint_sensitivity: string; // "low", "medium", "high"
  542. auto_recovery_step_loss: boolean;
  543. filament_tangle_detect: boolean;
  544. }
  545. export interface FilaSwitchState {
  546. installed: boolean;
  547. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  548. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  549. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  550. // 0xE when unset. Neither array says which inlet is currently routed to which
  551. // outlet — that pairing is not reported. For per-AMS side information use
  552. // PrinterStatus.ams_switch_inlet instead.
  553. in_slots: number[];
  554. out_extruders: number[];
  555. stat: number;
  556. info: number;
  557. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  558. // the switch cannot route a load anywhere and the printer has to be set up
  559. // first ("Manual AMS Setup" on its screen).
  560. ready: boolean;
  561. }
  562. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  563. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  564. // tray_now cannot answer this — it is one value for the whole printer, so on a
  565. // dual-nozzle machine it names only one of the two loaded hotends.
  566. export interface ExtruderSlot {
  567. ams_id: number | null;
  568. slot_id: number | null;
  569. has_filament: boolean;
  570. }
  571. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  572. export type FtsInlet = 'A' | 'B';
  573. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  574. export interface UsbCamera {
  575. device: string;
  576. name: string;
  577. capabilities: string[];
  578. driver?: string;
  579. formats?: string[];
  580. }
  581. export interface PrinterStatus {
  582. id: number;
  583. name: string;
  584. connected: boolean;
  585. state: string | null;
  586. current_print: string | null;
  587. subtask_name: string | null;
  588. current_archive_id: number | null;
  589. current_plate_id: number | null;
  590. gcode_file: string | null;
  591. progress: number | null;
  592. remaining_time: number | null;
  593. layer_num: number | null;
  594. total_layers: number | null;
  595. temperatures: {
  596. bed?: number;
  597. bed_target?: number;
  598. bed_heating?: boolean; // Actual heater state from MQTT
  599. nozzle?: number;
  600. nozzle_target?: number;
  601. nozzle_heating?: boolean; // Actual heater state from MQTT
  602. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  603. nozzle_2_target?: number;
  604. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  605. chamber?: number;
  606. chamber_target?: number;
  607. chamber_heating?: boolean; // Actual heater state from MQTT
  608. } | null;
  609. cover_url: string | null;
  610. hms_errors: HMSError[];
  611. // Live updates send null when no AMS is attached; the REST status sends [].
  612. ams: AMSUnit[] | null;
  613. ams_exists: boolean;
  614. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  615. store_to_sdcard: boolean; // Store sent files on SD card
  616. timelapse: boolean; // Timelapse recording active
  617. ipcam: boolean; // Live view enabled
  618. wifi_signal: number | null; // WiFi signal strength in dBm
  619. wired_network: boolean; // Ethernet connection detected
  620. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  621. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  622. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  623. // utils/amsHelpers rather than indexing it directly.
  624. nozzles: NozzleInfo[];
  625. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  626. print_options: PrintOptions | null; // AI detection and print options
  627. // Calibration stage tracking
  628. stg_cur: number; // Current stage number (-1 = not calibrating)
  629. stg_cur_name: string | null; // Human-readable current stage name
  630. stg: number[]; // List of stage numbers in calibration sequence
  631. // Air conditioning mode (0=cooling, 1=heating)
  632. airduct_mode: number;
  633. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  634. speed_level: number;
  635. // Chamber light on/off
  636. chamber_light: boolean;
  637. // Active extruder for dual nozzle (0=right, 1=left)
  638. active_extruder: number;
  639. // AMS mapping - which AMS is connected to which nozzle
  640. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  641. ams_mapping: number[];
  642. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  643. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  644. // Note: JSON keys are always strings
  645. ams_extruder_map: Record<string, number>;
  646. // Filament Track Switch accessory — null when not installed. When present,
  647. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  648. // either extruder, so per-extruder slot filtering must be skipped.
  649. fila_switch: FilaSwitchState | null;
  650. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  651. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  652. // an entry here reaches BOTH nozzles through the switch, which is why it has
  653. // no ams_extruder_map entry and must not be badged left or right.
  654. ams_switch_inlet: Record<string, FtsInlet>;
  655. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  656. // Empty on printers that don't report it (everything but the H2/X2 series).
  657. extruder_slots: Record<string, ExtruderSlot>;
  658. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  659. tray_now: number;
  660. // The trays this print has drawn from, in order: [global tray ID, layer of the
  661. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  662. // switched to (AMS Filament Backup). Reset at the start of each print.
  663. tray_change_log?: [number, number][];
  664. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  665. // Global tray IDs (ams_id*4+slot, 128-135 = AMS-HT, 254 = external), matching
  666. // the same numbering as tray_now so the AMS graphic can highlight them.
  667. // expected_tray = the slot the firmware now expects filament in (null = idle,
  668. // not paused, or unresolvable → "check the printer").
  669. // previous_tray = the slot that ran out (null = unknown).
  670. expected_tray: number | null;
  671. previous_tray: number | null;
  672. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  673. ams_status_main: number;
  674. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  675. ams_status_sub: number;
  676. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  677. mc_print_sub_stage: number;
  678. // Timestamp of last AMS data update (for RFID refresh detection)
  679. last_ams_update: number;
  680. // Number of printable objects in current print (for skip objects feature)
  681. printable_objects_count: number;
  682. // The next pause the slicer put into the running print (#2984). minutes is
  683. // null while the printer reports no time left yet.
  684. next_pause?: { layer: number; minutes: number | null } | null;
  685. // Fan speeds (0-100 percentage, null if not available for this model)
  686. cooling_fan_speed: number | null; // Part cooling fan
  687. big_fan1_speed: number | null; // Auxiliary fan
  688. big_fan2_speed: number | null; // Chamber/exhaust fan
  689. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  690. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  691. // null = not installed / not reported by this model.
  692. left_aux_fan_speed: number | null;
  693. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  694. exhaust_fan_present: boolean;
  695. firmware_version: string | null; // Firmware version from MQTT
  696. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  697. developer_mode: boolean | null;
  698. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  699. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  700. ams_filament_backup: boolean | null;
  701. // Queue: printer is awaiting user ack that the build plate was cleared after a
  702. // finished/failed print. Persisted across restarts (#961).
  703. awaiting_plate_clear: boolean;
  704. // AMS drying support
  705. supports_drying: boolean;
  706. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  707. drying_screen_only?: boolean;
  708. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  709. supports_chamber_heater?: boolean;
  710. }
  711. export interface PrinterCreate {
  712. name: string;
  713. serial_number: string;
  714. ip_address: string;
  715. access_code: string;
  716. model?: string;
  717. location?: string | null;
  718. auto_archive?: boolean;
  719. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  720. // scheduler, metrics and the print picker on this; toggling via PATCH
  721. // /printers/{id} disconnects or reconnects MQTT accordingly.
  722. is_active?: boolean;
  723. external_camera_url?: string | null;
  724. external_camera_type?: string | null;
  725. external_camera_enabled?: boolean;
  726. external_camera_snapshot_url?: string | null;
  727. camera_rotation?: number;
  728. camera_light_auto?: boolean;
  729. plate_detection_enabled?: boolean;
  730. plate_detection_roi?: PlateDetectionROI;
  731. wear_cost_per_hour?: number | null;
  732. }
  733. // Plate Detection
  734. export interface PlateDetectionROI {
  735. x: number; // X start % (0.0-1.0)
  736. y: number; // Y start % (0.0-1.0)
  737. w: number; // Width % (0.0-1.0)
  738. h: number; // Height % (0.0-1.0)
  739. }
  740. export interface PlateDetectionResult {
  741. is_empty: boolean;
  742. confidence: number;
  743. difference_percent: number;
  744. message: string;
  745. has_debug_image: boolean;
  746. debug_image_url?: string;
  747. needs_calibration: boolean;
  748. light_warning?: boolean;
  749. reference_count?: number;
  750. max_references?: number;
  751. roi?: PlateDetectionROI;
  752. }
  753. export interface PlateDetectionStatus {
  754. available: boolean;
  755. calibrated: boolean;
  756. reference_count: number;
  757. max_references: number;
  758. message: string;
  759. }
  760. export interface CalibrationResult {
  761. success: boolean;
  762. message: string;
  763. }
  764. export interface PlateReference {
  765. index: number;
  766. label: string;
  767. timestamp: string;
  768. has_image: boolean;
  769. thumbnail_url: string;
  770. }
  771. // Archive types
  772. export interface ArchiveDuplicate {
  773. id: number;
  774. print_name: string | null;
  775. created_at: string;
  776. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  777. }
  778. export interface ArchivePrinterMediaFile {
  779. name: string;
  780. path: string;
  781. size: number;
  782. mtime: string | null;
  783. kind: 'timelapse' | 'ipcam';
  784. }
  785. export interface ArchivePrinterMedia {
  786. archive_id: number;
  787. printer_id: number | null;
  788. local_timelapse: { name: string; size: number } | null;
  789. remote_files: ArchivePrinterMediaFile[];
  790. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  791. }
  792. /** A timelapse editor re-encode, run in the background. */
  793. export interface TimelapseJob {
  794. status: 'running' | 'completed' | 'failed' | 'cancelled';
  795. /** Share done, 0 to 1; null before ffmpeg's first report. */
  796. progress: number | null;
  797. output_path: string | null;
  798. message: string | null;
  799. error: string | null;
  800. }
  801. /** How a post-print outcome verdict reached the archive (#1898). */
  802. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  803. export interface Archive {
  804. id: number;
  805. printer_id: number | null;
  806. project_id: number | null;
  807. project_name: string | null;
  808. filename: string;
  809. file_path: string;
  810. file_size: number;
  811. content_hash: string | null;
  812. thumbnail_path: string | null;
  813. timelapse_path: string | null;
  814. source_3mf_path: string | null;
  815. f3d_path: string | null;
  816. duplicates: ArchiveDuplicate[] | null;
  817. duplicate_count: number;
  818. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  819. original_archive_id: number | null; // ID of the first/original archive
  820. object_count: number | null;
  821. print_name: string | null;
  822. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  823. print_time_seconds: number | null;
  824. actual_time_seconds: number | null; // Computed from started_at/completed_at
  825. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  826. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  827. filament_used_grams: number | null;
  828. filament_type: string | null;
  829. filament_color: string | null;
  830. layer_height: number | null;
  831. total_layers: number | null;
  832. nozzle_diameter: number | null;
  833. bed_temperature: number | null;
  834. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  835. nozzle_temperature: number | null;
  836. sliced_for_model: string | null; // Printer model this file was sliced for
  837. status: string;
  838. started_at: string | null;
  839. completed_at: string | null;
  840. extra_data: Record<string, unknown> | null;
  841. makerworld_url: string | null;
  842. designer: string | null;
  843. external_url: string | null;
  844. is_favorite: boolean;
  845. tags: string | null;
  846. notes: string | null;
  847. cost: number | null;
  848. photos: string[] | null;
  849. failure_reason: string | null;
  850. // Post-print outcome confirmation (#1898)
  851. user_verdict: 'good' | 'reject' | null;
  852. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  853. // handler (#3046) and is labelled here so it reads correctly once that lands.
  854. user_verdict_source: VerdictSource | null;
  855. user_verdict_at: string | null;
  856. confirm_requested: boolean;
  857. // The run whose outcome this shows, when it shows one run of the archive
  858. // (a plate printed on its own) rather than its latest (#1898).
  859. run_id?: number | null;
  860. // The latest print of the archive (among those the caller may see), whose
  861. // figures the per-print fields show (archive redesign).
  862. latest_run_id?: number | null;
  863. // How many videos its prints have; timelapse_path is the latest print's only.
  864. timelapse_count?: number;
  865. quantity: number;
  866. energy_kwh: number | null;
  867. energy_cost: number | null;
  868. wear_cost: number | null; // Printer wear (#694)
  869. created_at: string;
  870. // User tracking (Issue #206)
  871. created_by_id: number | null;
  872. created_by_username: string | null;
  873. // Per-archive run aggregates from PrintLogEntry (#1378)
  874. run_count: number;
  875. last_run_at: string | null;
  876. total_filament_actual_grams: number | null;
  877. successful_run_count: number;
  878. failed_run_count: number;
  879. }
  880. export interface ArchiveSlim {
  881. printer_id: number | null;
  882. print_name: string | null;
  883. print_time_seconds: number | null;
  884. actual_time_seconds: number | null;
  885. filament_used_grams: number | null;
  886. filament_type: string | null;
  887. filament_color: string | null;
  888. status: string;
  889. started_at: string | null;
  890. completed_at: string | null;
  891. cost: number | null;
  892. energy_kwh: number | null;
  893. energy_cost: number | null;
  894. wear_cost: number | null; // Printer wear (#694)
  895. quantity: number;
  896. created_at: string;
  897. }
  898. export interface PrintLogEntry {
  899. id: number;
  900. archive_id: number | null;
  901. print_name: string | null;
  902. plate_id?: number | null;
  903. printer_name: string | null;
  904. printer_id: number | null;
  905. status: string;
  906. started_at: string | null;
  907. completed_at: string | null;
  908. duration_seconds: number | null;
  909. filament_type: string | null;
  910. filament_color: string | null;
  911. filament_used_grams: number | null;
  912. cost: number | null;
  913. energy_kwh: number | null;
  914. energy_cost: number | null;
  915. wear_cost: number | null; // Printer wear (#694)
  916. failure_reason: string | null;
  917. user_verdict?: 'good' | 'reject' | null;
  918. user_verdict_source?: string | null;
  919. confirm_requested?: boolean | null;
  920. duration_unmeasured?: boolean | null;
  921. quantity?: number | null;
  922. // This print's own (archive redesign): note, finish photos, video.
  923. notes?: string | null;
  924. photos?: string[] | null;
  925. timelapse_path?: string | null;
  926. // The slicer's estimate for the plate it printed; in an archive's runs list.
  927. estimate_seconds?: number | null;
  928. estimate_grams?: number | null;
  929. thumbnail_path: string | null;
  930. created_by_id: number | null;
  931. created_by_username: string | null;
  932. created_at: string;
  933. }
  934. export interface PrintLogResponse {
  935. items: PrintLogEntry[];
  936. total: number;
  937. // The print log only: archives of its prints that were deleted.
  938. deleted_archive_ids?: number[];
  939. }
  940. export interface ArchiveStats {
  941. total_prints: number;
  942. successful_prints: number;
  943. failed_prints: number;
  944. cancelled_prints: number;
  945. total_print_time_hours: number;
  946. total_filament_grams: number;
  947. total_cost: number;
  948. prints_by_filament_type: Record<string, number>;
  949. prints_by_printer: Record<string, number>;
  950. // Name each printer id was last recorded under in the print log, so history
  951. // belonging to a deleted printer keeps its label.
  952. printer_names?: Record<string, string>;
  953. average_time_accuracy: number | null;
  954. time_accuracy_by_printer: Record<string, number> | null;
  955. total_energy_kwh: number;
  956. total_energy_cost: number;
  957. total_wear_cost: number; // Printer wear (#694)
  958. // True when a date-filtered total-consumption query is running on incomplete
  959. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  960. // a baseline). UI should explain why the number may undercount.
  961. energy_data_warming_up?: boolean;
  962. }
  963. export interface TagInfo {
  964. name: string;
  965. count: number;
  966. }
  967. export interface FailureAnalysis {
  968. period_days: number;
  969. total_prints: number;
  970. failed_prints: number;
  971. failure_rate: number;
  972. // Quality dimension (#1898): completed prints the user rejected. Optional
  973. // so a frontend build against an older backend degrades gracefully.
  974. rejected_prints?: number;
  975. yield_rate?: number;
  976. rejects_by_reason?: Record<string, number>;
  977. failures_by_reason: Record<string, number>;
  978. failures_by_filament: Record<string, number>;
  979. failures_by_printer: Record<string, number>;
  980. failures_by_hour: Record<number, number>;
  981. recent_failures: Array<{
  982. id: number;
  983. print_name: string;
  984. failure_reason: string | null;
  985. filament_type: string | null;
  986. printer_id: number | null;
  987. created_at: string | null;
  988. }>;
  989. trend: Array<{
  990. week_start: string;
  991. total_prints: number;
  992. failed_prints: number;
  993. failure_rate: number;
  994. }>;
  995. }
  996. /**
  997. * Send the browser's zone with calendar dates: the server reads a date as a
  998. * day in it, else in its own TZ, which shifted every day for a browser away
  999. * from the server (DB-C12). Only when a date is set.
  1000. */
  1001. function addDayZone(params: URLSearchParams): void {
  1002. if (!params.has('date_from') && !params.has('date_to')) return;
  1003. try {
  1004. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1005. if (zone) params.set('tz', zone);
  1006. } catch {
  1007. // No Intl zone: the server's TZ applies.
  1008. }
  1009. }
  1010. export interface BulkUploadResult {
  1011. uploaded: number;
  1012. failed: number;
  1013. /** `index` is the file's position in the request. */
  1014. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1015. errors: Array<{ index: number; filename: string; error: string }>;
  1016. }
  1017. // Archive Comparison types
  1018. export interface ComparisonArchiveInfo {
  1019. id: number;
  1020. print_name: string;
  1021. status: string;
  1022. created_at: string | null;
  1023. printer_id: number | null;
  1024. project_name: string | null;
  1025. }
  1026. export interface ComparisonField {
  1027. field: string;
  1028. label: string;
  1029. unit: string | null;
  1030. values: (string | number | null)[];
  1031. raw_values: (string | number | null)[];
  1032. has_difference: boolean;
  1033. }
  1034. export interface SuccessCorrelationInsight {
  1035. field: string;
  1036. label: string;
  1037. insight: string;
  1038. success_avg?: number;
  1039. failed_avg?: number;
  1040. success_values?: string[];
  1041. failed_values?: string[];
  1042. }
  1043. export interface SuccessCorrelation {
  1044. has_both_outcomes: boolean;
  1045. message?: string;
  1046. successful_count?: number;
  1047. failed_count?: number;
  1048. insights?: SuccessCorrelationInsight[];
  1049. }
  1050. export interface ArchiveComparison {
  1051. archives: ComparisonArchiveInfo[];
  1052. comparison: ComparisonField[];
  1053. differences: ComparisonField[];
  1054. success_correlation: SuccessCorrelation;
  1055. }
  1056. // Project types
  1057. export interface ProjectStats {
  1058. total_archives: number;
  1059. total_items: number; // Sum of quantities (total items printed)
  1060. completed_prints: number; // Sum of quantities for completed prints (parts)
  1061. failed_prints: number;
  1062. queued_prints: number;
  1063. in_progress_prints: number;
  1064. total_print_time_hours: number;
  1065. total_filament_grams: number;
  1066. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1067. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1068. estimated_cost: number;
  1069. total_energy_kwh: number;
  1070. total_energy_cost: number;
  1071. total_wear_cost: number; // Printer wear (#694)
  1072. remaining_prints: number | null; // Remaining plates
  1073. remaining_parts: number | null; // Remaining parts
  1074. bom_total_items: number;
  1075. bom_completed_items: number;
  1076. bom_cost: number;
  1077. }
  1078. // A sub-project as listed on its parent's page. The figures cover the child's
  1079. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1080. // parent's own prints (#1264).
  1081. export interface ProjectChildPreview {
  1082. id: number;
  1083. name: string;
  1084. color: string | null;
  1085. status: string;
  1086. progress_percent: number | null;
  1087. descendant_count: number;
  1088. total_archives: number;
  1089. completed_prints: number;
  1090. total_print_time_hours: number;
  1091. total_filament_grams: number;
  1092. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1093. }
  1094. export interface Project {
  1095. id: number;
  1096. name: string;
  1097. description: string | null;
  1098. color: string | null;
  1099. status: string; // active, completed, archived
  1100. target_count: number | null; // Target number of plates/print jobs
  1101. target_parts_count: number | null; // Target number of parts/objects
  1102. target_sets: number | null; // Copies-per-file target (#1897)
  1103. notes: string | null;
  1104. attachments: ProjectAttachment[] | null;
  1105. tags: string | null;
  1106. due_date: string | null;
  1107. priority: string; // low, normal, high, urgent
  1108. budget: number | null;
  1109. is_template: boolean;
  1110. template_source_id: number | null;
  1111. parent_id: number | null;
  1112. parent_name: string | null;
  1113. children: ProjectChildPreview[];
  1114. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1115. created_at: string;
  1116. updated_at: string;
  1117. stats?: ProjectStats;
  1118. // This project's numbers combined with every sub-project's. Null when there
  1119. // are none, since it would only repeat `stats` (#1264).
  1120. rollup_stats?: ProjectStats | null;
  1121. url: string | null; // External link rendered next to project name on the card (#1155)
  1122. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1123. }
  1124. export interface ProjectAttachment {
  1125. filename: string;
  1126. original_name: string;
  1127. size: number;
  1128. uploaded_at: string;
  1129. }
  1130. // Completed-run count for one library file inside a project (#1897)
  1131. export interface ProjectFileProgress {
  1132. file_id: number;
  1133. completed_count: number;
  1134. }
  1135. export interface ArchivePreview {
  1136. id: number;
  1137. print_name: string | null;
  1138. thumbnail_path: string | null;
  1139. status: string;
  1140. filament_type: string | null;
  1141. filament_color: string | null;
  1142. }
  1143. export interface ProjectListItem {
  1144. id: number;
  1145. name: string;
  1146. description: string | null;
  1147. color: string | null;
  1148. status: string;
  1149. target_count: number | null; // Target number of plates/print jobs
  1150. target_parts_count: number | null; // Target number of parts/objects
  1151. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1152. budget: number | null;
  1153. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1154. due_date: string | null; // #2536
  1155. priority: string; // #2536
  1156. created_at: string;
  1157. archive_count: number; // Number of print jobs (plates)
  1158. total_items: number; // Sum of quantities (total items printed, including failed)
  1159. completed_count: number; // Sum of quantities for completed prints only (parts)
  1160. failed_count: number; // Sum of quantities for failed prints
  1161. queue_count: number;
  1162. progress_percent: number | null; // Plates progress
  1163. parent_id: number | null; // #1264 — set when this is a sub-project
  1164. child_count: number; // #1264 — direct sub-projects only
  1165. archives: ArchivePreview[];
  1166. url: string | null; // #1155
  1167. cover_image_filename: string | null; // #1155
  1168. }
  1169. export interface ProjectCreate {
  1170. name: string;
  1171. description?: string;
  1172. color?: string;
  1173. target_count?: number;
  1174. target_parts_count?: number;
  1175. target_sets?: number;
  1176. notes?: string;
  1177. tags?: string;
  1178. due_date?: string;
  1179. priority?: string;
  1180. budget?: number | null;
  1181. parent_id?: number;
  1182. url?: string | null; // #1155
  1183. }
  1184. export interface ProjectUpdate {
  1185. name?: string;
  1186. description?: string;
  1187. color?: string;
  1188. status?: string;
  1189. target_count?: number;
  1190. target_parts_count?: number;
  1191. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1192. notes?: string;
  1193. tags?: string | null; // #2536 — explicit null clears the tags
  1194. due_date?: string | null; // #2536 — explicit null clears the due date
  1195. priority?: string;
  1196. budget?: number | null;
  1197. parent_id?: number;
  1198. url?: string | null; // #1155 — explicit null clears the URL
  1199. }
  1200. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1201. export interface BOMItem {
  1202. id: number;
  1203. project_id: number;
  1204. name: string;
  1205. quantity_needed: number;
  1206. quantity_acquired: number;
  1207. unit_price: number | null;
  1208. sourcing_url: string | null;
  1209. archive_id: number | null;
  1210. archive_name: string | null;
  1211. stl_filename: string | null;
  1212. remarks: string | null;
  1213. sort_order: number;
  1214. is_complete: boolean;
  1215. created_at: string;
  1216. updated_at: string;
  1217. }
  1218. export interface BOMItemCreate {
  1219. name: string;
  1220. quantity_needed?: number;
  1221. unit_price?: number;
  1222. sourcing_url?: string;
  1223. archive_id?: number;
  1224. stl_filename?: string;
  1225. remarks?: string;
  1226. }
  1227. export interface BOMItemUpdate {
  1228. name?: string;
  1229. quantity_needed?: number;
  1230. quantity_acquired?: number;
  1231. unit_price?: number;
  1232. sourcing_url?: string;
  1233. archive_id?: number;
  1234. stl_filename?: string;
  1235. remarks?: string;
  1236. }
  1237. // Project Export/Import Types
  1238. export interface BOMItemExport {
  1239. name: string;
  1240. quantity_needed: number;
  1241. quantity_acquired: number;
  1242. unit_price: number | null;
  1243. sourcing_url: string | null;
  1244. stl_filename: string | null;
  1245. remarks: string | null;
  1246. }
  1247. export interface LinkedFolderExport {
  1248. name: string;
  1249. }
  1250. export interface ProjectExport {
  1251. name: string;
  1252. description: string | null;
  1253. color: string | null;
  1254. status: string;
  1255. target_count: number | null;
  1256. target_parts_count: number | null;
  1257. target_sets: number | null; // #1897
  1258. notes: string | null;
  1259. tags: string | null;
  1260. due_date: string | null;
  1261. priority: string;
  1262. budget: number | null;
  1263. bom_items: BOMItemExport[];
  1264. linked_folders: LinkedFolderExport[];
  1265. }
  1266. export interface ProjectImport {
  1267. name: string;
  1268. description?: string;
  1269. color?: string;
  1270. status?: string;
  1271. target_count?: number;
  1272. target_parts_count?: number;
  1273. target_sets?: number; // #1897
  1274. notes?: string;
  1275. tags?: string;
  1276. due_date?: string;
  1277. priority?: string;
  1278. budget?: number | null;
  1279. bom_items?: BOMItemExport[];
  1280. linked_folders?: LinkedFolderExport[];
  1281. }
  1282. // Timeline Types
  1283. export interface TimelineEvent {
  1284. event_type: string;
  1285. timestamp: string;
  1286. title: string;
  1287. description: string | null;
  1288. metadata: Record<string, unknown> | null;
  1289. }
  1290. // API Key types
  1291. export interface APIKey {
  1292. id: number;
  1293. name: string;
  1294. key_prefix: string;
  1295. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1296. can_queue: boolean;
  1297. can_control_printer: boolean;
  1298. can_read_status: boolean;
  1299. can_manage_library: boolean;
  1300. can_manage_inventory: boolean;
  1301. can_manage_maintenance: boolean;
  1302. can_manage_archives: boolean;
  1303. can_manage_projects: boolean;
  1304. can_access_cloud: boolean;
  1305. can_update_energy_cost: boolean;
  1306. can_send_notifications: boolean;
  1307. printer_ids: number[] | null;
  1308. enabled: boolean;
  1309. last_used: string | null;
  1310. created_at: string;
  1311. expires_at: string | null;
  1312. }
  1313. export interface APIKeyCreate {
  1314. name: string;
  1315. can_queue?: boolean;
  1316. can_control_printer?: boolean;
  1317. can_read_status?: boolean;
  1318. can_manage_library?: boolean;
  1319. can_manage_inventory?: boolean;
  1320. can_manage_maintenance?: boolean;
  1321. can_manage_archives?: boolean;
  1322. can_manage_projects?: boolean;
  1323. can_access_cloud?: boolean;
  1324. can_update_energy_cost?: boolean;
  1325. can_send_notifications?: boolean;
  1326. printer_ids?: number[] | null;
  1327. expires_at?: string | null;
  1328. }
  1329. export interface APIKeyCreateResponse extends APIKey {
  1330. key: string; // Full key, only shown on creation
  1331. }
  1332. /**
  1333. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1334. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1335. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1336. */
  1337. export type CalibrationMode = 'off' | 'on' | 'auto';
  1338. // Settings types
  1339. export interface AppSettings {
  1340. auto_archive: boolean;
  1341. save_thumbnails: boolean;
  1342. capture_finish_photo: boolean;
  1343. finish_photo_restore_plate: boolean;
  1344. default_filament_cost: number;
  1345. currency: string;
  1346. energy_cost_per_kwh: number;
  1347. energy_tracking_mode: 'print' | 'total';
  1348. // Where the electricity price comes from (#1251). With 'homeassistant',
  1349. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1350. energy_price_source: 'fixed' | 'homeassistant';
  1351. energy_price_ha_entity: string;
  1352. check_updates: boolean;
  1353. check_printer_firmware: boolean;
  1354. include_beta_updates: boolean;
  1355. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1356. announcements_enabled?: boolean;
  1357. announcements_all_users?: boolean;
  1358. // #1589: false hides the local username/password form on the login page;
  1359. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1360. // true so the env-var recovery path is visible to the SPA.
  1361. local_login_enabled: boolean;
  1362. language: string;
  1363. notification_language: string;
  1364. // AMS threshold settings
  1365. ams_humidity_good: number; // <= this is green
  1366. ams_humidity_fair: number; // <= this is orange, > is red
  1367. ams_temp_good: number; // <= this is green/blue
  1368. ams_temp_fair: number; // <= this is orange, > is red
  1369. // Separate from the display band (#2905). null = unset, which the backend
  1370. // resolves to ams_temp_fair so existing installs are unaffected.
  1371. ams_temp_alarm: number | null;
  1372. ams_history_retention_days: number; // days to keep AMS sensor history
  1373. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1374. // Queue auto-drying settings
  1375. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1376. queue_drying_block: boolean; // Block queue until drying completes
  1377. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1378. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1379. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1380. drying_presets: string; // JSON blob of drying presets per filament type
  1381. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1382. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1383. // Scheduled local backup
  1384. local_backup_enabled: boolean;
  1385. local_backup_schedule: string;
  1386. local_backup_time: string;
  1387. local_backup_retention: number;
  1388. local_backup_path: string;
  1389. // Print modal settings
  1390. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1391. // Date/time format settings
  1392. date_format: 'system' | 'us' | 'eu' | 'iso';
  1393. time_format: 'system' | '12h' | '24h';
  1394. // Filament tracking
  1395. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1396. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1397. 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
  1398. 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
  1399. spoolman_url: string;
  1400. // Default printer
  1401. default_printer_id: number | null;
  1402. pipeline_max_copies: number;
  1403. // Dark mode theme settings
  1404. dark_style: 'classic' | 'glow' | 'vibrant';
  1405. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1406. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1407. // Light mode theme settings
  1408. light_style: 'classic' | 'glow' | 'vibrant';
  1409. light_background: 'neutral' | 'warm' | 'cool';
  1410. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1411. // FTP retry settings
  1412. ftp_retry_enabled: boolean;
  1413. ftp_retry_count: number;
  1414. ftp_retry_delay: number;
  1415. ftp_timeout: number;
  1416. // MQTT relay settings
  1417. mqtt_enabled: boolean;
  1418. mqtt_broker: string;
  1419. mqtt_port: number;
  1420. mqtt_username: string;
  1421. mqtt_password: string;
  1422. mqtt_topic_prefix: string;
  1423. mqtt_use_tls: boolean;
  1424. // External URL for notifications
  1425. external_url: string;
  1426. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1427. docker_compose_dir: string;
  1428. // Home Assistant integration
  1429. ha_enabled: boolean;
  1430. ha_url: string;
  1431. ha_token: string;
  1432. ha_url_from_env: boolean;
  1433. ha_token_from_env: boolean;
  1434. ha_env_managed: boolean;
  1435. // File Manager / Library settings
  1436. library_disk_warning_gb: number;
  1437. // Camera view settings
  1438. camera_view_mode: 'window' | 'embedded';
  1439. // Chamber light while the camera is in use (#1655)
  1440. camera_light_mode: 'off' | 'all' | 'selected';
  1441. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1442. // Preferred slicer (server-side API / sidecar)
  1443. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1444. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1445. // preferred_slicer so existing installs behave identically.
  1446. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1447. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1448. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1449. slice_engine: 'sidecar' | 'browser';
  1450. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1451. use_slicer_api: boolean;
  1452. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1453. orcaslicer_api_url: string;
  1454. bambu_studio_api_url: string;
  1455. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1456. // stalls, not total slicing time — a model that keeps reporting progress
  1457. // runs to completion however long it takes.
  1458. slicer_stall_timeout_minutes: number;
  1459. // Prometheus metrics
  1460. prometheus_enabled: boolean;
  1461. prometheus_token: string;
  1462. // Bed cooled threshold
  1463. bed_cooled_threshold: number;
  1464. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1465. pause_warning_minutes: number;
  1466. // Inventory low stock threshold
  1467. low_stock_threshold: number;
  1468. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1469. session_max_hours: number;
  1470. // User email notifications toggle
  1471. user_notifications_enabled: boolean;
  1472. // Default print options
  1473. default_bed_levelling: CalibrationMode;
  1474. default_flow_cali: CalibrationMode;
  1475. default_vibration_cali: boolean;
  1476. default_layer_inspect: boolean;
  1477. default_timelapse: boolean;
  1478. default_nozzle_offset_cali: CalibrationMode;
  1479. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1480. default_confirm_outcome: boolean;
  1481. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1482. confirm_outcome_external_prints: boolean;
  1483. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1484. confirm_default_good_on_plate_clear: boolean;
  1485. // Staggered batch start defaults
  1486. stagger_group_size: number;
  1487. stagger_interval_minutes: number;
  1488. // Finance budget reset window
  1489. billing_enabled: boolean;
  1490. printer_kill_switch_enabled: boolean;
  1491. finance_budget_reset_day: number;
  1492. finance_budget_reset_timezone: string;
  1493. // Plate-clear confirmation
  1494. require_plate_clear: boolean;
  1495. // Shortest job first scheduling
  1496. queue_shortest_first: boolean;
  1497. // How many printers the queue may upload to at once (#2555). 1 restores the
  1498. // old strictly-serial behaviour, where every printer waited out every other
  1499. // printer's transfer.
  1500. queue_max_concurrent_uploads: number;
  1501. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1502. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1503. // flip the decision per print. Chamber target derives from the loaded AMS
  1504. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1505. // across loaded slots); the per-item override field bypasses derivation.
  1506. preheat_enabled: boolean;
  1507. preheat_filament_targets: string;
  1508. preheat_max_wait_seconds: number;
  1509. preheat_soak_seconds: number;
  1510. queue_keep_bed_warm: boolean;
  1511. queue_keep_warm_bed_temp: number;
  1512. queue_keep_warm_max_minutes: number;
  1513. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1514. // Empty string = use built-in defaults.
  1515. nozzle_temp_presets: string;
  1516. bed_temp_presets: string;
  1517. chamber_temp_presets: string;
  1518. fan_speed_presets: string;
  1519. // Default sidebar order (admin-set for all users)
  1520. default_sidebar_order: string;
  1521. // LDAP authentication
  1522. ldap_enabled: boolean;
  1523. ldap_server_url: string;
  1524. ldap_bind_dn: string;
  1525. ldap_bind_password: string;
  1526. ldap_search_base: string;
  1527. ldap_user_filter: string;
  1528. ldap_security: string;
  1529. ldap_group_mapping: string;
  1530. ldap_auto_provision: boolean;
  1531. ldap_default_group: string;
  1532. obico_enabled: boolean;
  1533. obico_ml_url: string;
  1534. bambuddy_internal_url: string;
  1535. obico_ml_token: string;
  1536. obico_sensitivity: 'low' | 'medium' | 'high';
  1537. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1538. obico_poll_interval: number;
  1539. obico_enabled_printers: string;
  1540. octoeverywhere_enabled: boolean;
  1541. octoeverywhere_api_key: string;
  1542. octoeverywhere_api_key_configured: boolean;
  1543. octoeverywhere_confidence: OctoEverywhereConfidence;
  1544. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1545. octoeverywhere_enabled_printers: string;
  1546. octoeverywhere_poll_interval: number;
  1547. // Inventory forecasting global lead time
  1548. forecast_global_lead_time_days: number;
  1549. location_sensor_poll_interval: number;
  1550. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1551. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1552. // Server-backed so two admins seed the same alert rules and a restore
  1553. // brings them back; see utils/locationSensorDefaults.ts.
  1554. location_sensor_alert_defaults: string;
  1555. }
  1556. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1557. // Settings as a page sees them: everything from GET /settings for a user who
  1558. // may read it, otherwise the subset /settings/ui-preferences and
  1559. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1560. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1561. // MQTT relay status
  1562. export interface MQTTStatus {
  1563. enabled: boolean;
  1564. connected: boolean;
  1565. broker: string;
  1566. port: number;
  1567. topic_prefix: string;
  1568. }
  1569. // Cloud types
  1570. export interface CloudAuthStatus {
  1571. is_authenticated: boolean;
  1572. email: string | null;
  1573. region?: 'global' | 'china' | null;
  1574. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1575. sign_in_expired?: boolean;
  1576. }
  1577. export interface CloudLoginResponse {
  1578. success: boolean;
  1579. needs_verification: boolean;
  1580. message: string;
  1581. verification_type?: 'email' | 'totp' | null;
  1582. tfa_key?: string | null;
  1583. /**
  1584. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1585. * layer is challenging this network and no credential will be accepted until
  1586. * it clears — the UI must explain that in place rather than toast `message`.
  1587. */
  1588. reason?: 'captcha' | string | null;
  1589. }
  1590. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1591. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1592. // flow is paste-based rather than callback-based.
  1593. export interface OrcaDeviceStartResponse {
  1594. user_code: string;
  1595. verification_uri: string;
  1596. verification_uri_complete: string;
  1597. interval: number;
  1598. expires_in: number;
  1599. }
  1600. export type OrcaDevicePollStatus =
  1601. | 'authorization_pending'
  1602. | 'slow_down'
  1603. | 'access_denied'
  1604. | 'expired_token'
  1605. | 'complete';
  1606. export interface OrcaDevicePollResponse {
  1607. status: OrcaDevicePollStatus;
  1608. connected: boolean;
  1609. email: string | null;
  1610. user_id: string | null;
  1611. }
  1612. export interface OrcaAuthStatusResponse {
  1613. connected: boolean;
  1614. email: string | null;
  1615. user_id: string | null;
  1616. }
  1617. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1618. // so the frontend can use the same visual components for both surfaces (cards,
  1619. // grouped sections, filter bar). Backend handles the source-specific
  1620. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1621. export interface OrcaProfileMeta {
  1622. setting_id: string;
  1623. name: string;
  1624. type: string;
  1625. version: string | null;
  1626. user_id: string | null;
  1627. updated_time: string | null;
  1628. is_custom: boolean;
  1629. }
  1630. export interface OrcaProfileListResponse {
  1631. filament: OrcaProfileMeta[];
  1632. printer: OrcaProfileMeta[];
  1633. process: OrcaProfileMeta[];
  1634. }
  1635. export interface OrcaProfileDetail {
  1636. setting_id: string;
  1637. name: string;
  1638. type: string;
  1639. version: string | null;
  1640. base_id: string | null;
  1641. update_time: string | null;
  1642. setting: Record<string, unknown>;
  1643. }
  1644. // MakerWorld integration. Full metadata/instance shapes come back as
  1645. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1646. // pass them through verbatim rather than maintaining a brittle mirror.
  1647. export interface MakerworldStatus {
  1648. has_cloud_token: boolean;
  1649. can_download: boolean;
  1650. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1651. sign_in_expired?: boolean;
  1652. }
  1653. export interface MakerworldResolvedModel {
  1654. model_id: number;
  1655. profile_id: number | null;
  1656. design: Record<string, unknown>;
  1657. instances: Array<Record<string, unknown>>;
  1658. already_imported_library_ids: number[];
  1659. }
  1660. export interface MakerworldImportResponse {
  1661. library_file_id: number;
  1662. filename: string;
  1663. folder_id: number | null;
  1664. profile_id: number | null;
  1665. was_existing: boolean;
  1666. }
  1667. export interface MakerworldRecentImport {
  1668. library_file_id: number;
  1669. filename: string;
  1670. folder_id: number | null;
  1671. thumbnail_path: string | null;
  1672. source_url: string | null;
  1673. created_at: string;
  1674. }
  1675. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1676. // searched, with single files imported into the library.
  1677. export interface ManyfoldConfig {
  1678. url: string;
  1679. client_id: string;
  1680. /** The secret itself is never returned. */
  1681. has_client_secret: boolean;
  1682. configured: boolean;
  1683. }
  1684. export interface ManyfoldConfigInput {
  1685. url: string;
  1686. client_id: string;
  1687. /** Empty or left out keeps the stored secret. */
  1688. client_secret?: string;
  1689. }
  1690. export interface ManyfoldStatus {
  1691. configured: boolean;
  1692. url: string;
  1693. }
  1694. export interface ManyfoldModelSummary {
  1695. id: string;
  1696. name: string;
  1697. }
  1698. export interface ManyfoldModelList {
  1699. total: number;
  1700. page: number;
  1701. has_next: boolean;
  1702. has_previous: boolean;
  1703. models: ManyfoldModelSummary[];
  1704. }
  1705. export interface ManyfoldFile {
  1706. id: string;
  1707. name: string;
  1708. mime: string;
  1709. importable: boolean;
  1710. /** Set while the file imported earlier is still in the library. */
  1711. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1712. }
  1713. export interface ManyfoldModel {
  1714. id: string;
  1715. name: string;
  1716. caption: string | null;
  1717. description: string | null;
  1718. license: string | null;
  1719. tags: string[];
  1720. url: string;
  1721. has_preview: boolean;
  1722. files: ManyfoldFile[];
  1723. }
  1724. export interface ManyfoldImportResponse {
  1725. library_file_id: number;
  1726. filename: string;
  1727. folder_id: number | null;
  1728. was_existing: boolean;
  1729. }
  1730. export interface SlicerSetting {
  1731. setting_id: string;
  1732. name: string;
  1733. type: string;
  1734. version: string | null;
  1735. user_id: string | null;
  1736. updated_time: string | null;
  1737. is_custom: boolean;
  1738. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1739. // from setting_id for every preset (#3387). Absent from older backends.
  1740. filament_id?: string | null;
  1741. }
  1742. export interface SpoolCatalogEntry {
  1743. id: number;
  1744. name: string;
  1745. weight: number;
  1746. is_default: boolean;
  1747. }
  1748. export interface StorageLocation {
  1749. id: number;
  1750. name: string;
  1751. identifier: string | null;
  1752. spool_count: number;
  1753. created_at: string;
  1754. updated_at: string;
  1755. }
  1756. export interface ColorCatalogEntry {
  1757. id: number;
  1758. manufacturer: string;
  1759. color_name: string;
  1760. hex_color: string;
  1761. material: string | null;
  1762. is_default: boolean;
  1763. // #1154: optional multi-colour gradient stops + visual effect.
  1764. extra_colors?: string | null;
  1765. effect_type?: string | null;
  1766. }
  1767. export interface SlicerSettingsResponse {
  1768. filament: SlicerSetting[];
  1769. printer: SlicerSetting[];
  1770. process: SlicerSetting[];
  1771. }
  1772. export interface SlicerSettingDetail {
  1773. message?: string | null;
  1774. code?: string | null;
  1775. error?: string | null;
  1776. public: boolean;
  1777. version?: string | null;
  1778. type: string;
  1779. name: string;
  1780. update_time?: string | null;
  1781. nickname?: string | null;
  1782. base_id?: string | null;
  1783. setting: Record<string, unknown>;
  1784. filament_id?: string | null;
  1785. setting_id?: string | null;
  1786. }
  1787. export interface SlicerSettingCreate {
  1788. type: string; // 'filament', 'print', or 'printer'
  1789. name: string;
  1790. base_id: string;
  1791. setting: Record<string, unknown>;
  1792. }
  1793. export interface SlicerSettingUpdate {
  1794. name?: string;
  1795. setting?: Record<string, unknown>;
  1796. }
  1797. export interface SlicerSettingDeleteResponse {
  1798. success: boolean;
  1799. message: string;
  1800. }
  1801. // Built-in filament fallback (static table from backend)
  1802. export interface BuiltinFilament {
  1803. filament_id: string;
  1804. name: string;
  1805. }
  1806. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1807. //
  1808. // Two preset shapes are accepted per slot:
  1809. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1810. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1811. // across cloud / local / standard tiers. Source-aware refs win when both
  1812. // are present in the same payload.
  1813. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1814. export interface PresetRef {
  1815. source: PresetSource;
  1816. id: string;
  1817. }
  1818. /**
  1819. * Why a preset's effective values are unavailable.
  1820. *
  1821. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1822. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1823. * on, so a user can perfectly well be running a current Bambuddy against a
  1824. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1825. * beats a generic "could not read the values".
  1826. */
  1827. export type SlicerPresetValuesReason =
  1828. | 'ok'
  1829. | 'sidecar_outdated'
  1830. | 'sidecar_unavailable'
  1831. | 'not_configured'
  1832. | 'preset_unresolved';
  1833. export interface SlicerPresetValues {
  1834. /** False when the sidecar could not supply values; `values` is then empty. */
  1835. resolved: boolean;
  1836. /** Flattened key -> value map, in the string forms a process preset stores. */
  1837. values: Record<string, string | string[]>;
  1838. reason: SlicerPresetValuesReason;
  1839. }
  1840. export interface SliceRequest {
  1841. printer_preset_id?: number;
  1842. process_preset_id?: number;
  1843. filament_preset_id?: number;
  1844. printer_preset?: PresetRef;
  1845. process_preset?: PresetRef;
  1846. filament_preset?: PresetRef;
  1847. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1848. // preferred over the singular `filament_preset` when both are sent; the
  1849. // backend validator promotes a singular into a one-element list when this
  1850. // is omitted, so legacy single-color clients keep working unchanged.
  1851. filament_presets?: PresetRef[];
  1852. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1853. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1854. // *preset* -- it is a per-project property -- so without this every sliced
  1855. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1856. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1857. // any position hands that slot back to the backend's fallback chain (the
  1858. // preset's own default_filament_colour, then the source plate's colour).
  1859. filament_colours?: string[];
  1860. plate?: number;
  1861. export_3mf?: boolean;
  1862. // Build-plate override (#1337). When omitted, the slicer uses the process
  1863. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1864. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1865. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1866. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1867. bed_type?: string | null;
  1868. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1869. // project_settings.config (the designer's own wall count, infill, etc.)
  1870. // instead of the picked profile triplet. The preset refs above are still
  1871. // required by the backend validator but go unused on this path.
  1872. use_embedded_settings?: boolean;
  1873. // Process settings the user edited in the slice modal's settings panel,
  1874. // already serialised into the string forms a process preset stores ("1" for
  1875. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1876. // onto the resolved process JSON after the designer's carried tweaks, so an
  1877. // explicit choice here wins. Omitted when the panel is untouched.
  1878. process_overrides?: Record<string, string | string[]>;
  1879. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1880. // file flags as changed from the system preset, not values.
  1881. design_overrides?: string[];
  1882. // Layout passes the slicer runs before slicing (#2548), both off by
  1883. // default because they move or rotate the objects the user laid out.
  1884. // Unlike the fields above these are CLI actions rather than profile
  1885. // values, so they apply on the embedded-settings path too.
  1886. auto_orient?: boolean;
  1887. auto_arrange?: boolean;
  1888. }
  1889. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1890. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1891. export interface UnifiedPreset {
  1892. id: string;
  1893. name: string;
  1894. source: PresetSource;
  1895. // Populated for the filament slot only — used by the SliceModal multi-color
  1896. // pre-pick to score presets against each plate slot's required (type,
  1897. // colour). Optional because the bundled / standard tier rarely carries a
  1898. // colour (colour is a runtime spool attribute on Bambu) and older API
  1899. // responses pre-date these fields entirely.
  1900. filament_type?: string | null;
  1901. filament_colour?: string | null;
  1902. // Printer-preset names a process / filament preset declares itself
  1903. // compatible with. Populated for the local tier (the slicer's own
  1904. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1905. // the process / filament dropdowns by the selected printer using this when
  1906. // present (#1325).
  1907. compatible_printers?: string[] | null;
  1908. // Printer presets only: the preset it was saved from, for the local and
  1909. // OrcaSlicer Cloud tiers (#3250).
  1910. inherits?: string | null;
  1911. }
  1912. export interface UnifiedPresetsBySlot {
  1913. printer: UnifiedPreset[];
  1914. process: UnifiedPreset[];
  1915. filament: UnifiedPreset[];
  1916. }
  1917. // What is loaded in each connected printer, for the SliceModal's
  1918. // "only connected printers" / "only loaded spools" filters (#3172).
  1919. export interface LoadedSpoolPreset {
  1920. preset_id: string;
  1921. preset_name: string;
  1922. preset_source: string;
  1923. tray_info_idx?: string | null;
  1924. }
  1925. export interface LoadedSpoolTray {
  1926. ams_id: number;
  1927. tray_id: number;
  1928. tray_type: string | null;
  1929. tray_sub_brands: string | null;
  1930. tray_color: string | null;
  1931. tray_info_idx: string | null;
  1932. exists: boolean | null;
  1933. state: number | null;
  1934. saved_preset: LoadedSpoolPreset | null;
  1935. }
  1936. export interface LoadedSpoolUnit {
  1937. id: number;
  1938. is_ams_ht: boolean;
  1939. trays: LoadedSpoolTray[];
  1940. }
  1941. export interface LoadedSpoolPrinter {
  1942. id: number;
  1943. name: string;
  1944. model: string | null;
  1945. ams: LoadedSpoolUnit[];
  1946. // Holders with a spool in them; external_holders counts all of them (two
  1947. // on a dual-nozzle printer, labelled left and right).
  1948. external: LoadedSpoolTray[];
  1949. external_holders: number;
  1950. }
  1951. export interface LoadedSpoolsResponse {
  1952. printers: LoadedSpoolPrinter[];
  1953. }
  1954. export interface UnifiedPresetsResponse {
  1955. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1956. // dedup (apart from stock_aliases below) — every tier surfaces its full
  1957. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  1958. orca_cloud: UnifiedPresetsBySlot;
  1959. cloud: UnifiedPresetsBySlot;
  1960. local: UnifiedPresetsBySlot;
  1961. standard: UnifiedPresetsBySlot;
  1962. cloud_status: SlicerCloudStatus;
  1963. orca_cloud_status: SlicerCloudStatus;
  1964. // Standard presets that Bambu Cloud's stock list also has are left out of
  1965. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  1966. stock_aliases?: Record<string, PresetRef>;
  1967. }
  1968. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  1969. // can apply in one click. PR A surfaces only the bundle; target_* and
  1970. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  1971. // them (they come alive in PR B / PR C).
  1972. export interface SlicerPipeline {
  1973. id: number;
  1974. name: string;
  1975. description: string | null;
  1976. printer_preset: PresetRef;
  1977. process_preset: PresetRef;
  1978. filament_presets: PresetRef[];
  1979. bed_type: string | null;
  1980. target_kind: 'specific_printer' | 'printer_class';
  1981. target_printer_id: number | null;
  1982. target_model_class: string | null;
  1983. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  1984. created_by: number | null;
  1985. created_at: string;
  1986. updated_at: string;
  1987. }
  1988. export interface SlicerPipelineCreateRequest {
  1989. name: string;
  1990. description?: string | null;
  1991. printer_preset: PresetRef;
  1992. process_preset: PresetRef;
  1993. filament_presets: PresetRef[];
  1994. bed_type?: string | null;
  1995. }
  1996. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  1997. target_kind?: 'specific_printer' | 'printer_class';
  1998. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  1999. // to null. Use null in TypeScript for the same intent.
  2000. target_printer_id?: number | null;
  2001. target_model_class?: string | null;
  2002. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2003. };
  2004. export interface SlicerPipelinesListResponse {
  2005. pipelines: SlicerPipeline[];
  2006. }
  2007. // Slicer Pipeline runs (#1425 PR B + PR C)
  2008. export type PipelineEligibilityKind =
  2009. | 'printer_not_set'
  2010. | 'printer_not_found'
  2011. | 'printer_disabled'
  2012. | 'printer_offline'
  2013. | 'filament_type_mismatch'
  2014. | 'filament_color_mismatch'
  2015. | 'ams_slot_missing'
  2016. | 'filament_unverified'
  2017. | 'no_class_matches'
  2018. | 'class_not_set';
  2019. export interface PipelineEligibilityIssue {
  2020. kind: PipelineEligibilityKind;
  2021. slot_index: number | null;
  2022. expected: string | null;
  2023. actual: string | null;
  2024. }
  2025. export interface PipelinePerPrinterReport {
  2026. printer_id: number;
  2027. printer_name: string;
  2028. ok: boolean;
  2029. issues: PipelineEligibilityIssue[];
  2030. }
  2031. export interface PipelineEligibilityReport {
  2032. ok: boolean;
  2033. target_kind: 'specific_printer' | 'printer_class';
  2034. target_printer_id: number | null;
  2035. target_printer_name: string | null;
  2036. target_model_class: string | null;
  2037. issues: PipelineEligibilityIssue[];
  2038. printer_reports: PipelinePerPrinterReport[];
  2039. }
  2040. export interface PipelineJob {
  2041. id: number;
  2042. pipeline_run_id: number;
  2043. copy_index: number;
  2044. assigned_printer_id: number | null;
  2045. assigned_printer_name: string | null;
  2046. queue_entry_id: number | null;
  2047. status:
  2048. | 'pending'
  2049. | 'awaiting_printer'
  2050. | 'queued'
  2051. | 'printing'
  2052. | 'completed'
  2053. | 'failed'
  2054. | 'cancelled'
  2055. | 'unknown';
  2056. error_message: string | null;
  2057. dispatched_at: string | null;
  2058. completed_at: string | null;
  2059. }
  2060. export interface PipelineRun {
  2061. id: number;
  2062. pipeline_id: number | null;
  2063. pipeline_name: string | null;
  2064. source_library_file_id: number | null;
  2065. source_archive_id: number | null;
  2066. source_filename: string | null;
  2067. parent_run_id: number | null;
  2068. copies: number;
  2069. copies_completed: number;
  2070. copies_failed: number;
  2071. copies_cancelled: number;
  2072. copies_in_progress: number;
  2073. status:
  2074. | 'queued'
  2075. | 'slicing'
  2076. | 'dispatching'
  2077. | 'in_progress'
  2078. | 'completed'
  2079. | 'failed'
  2080. | 'partial_failure'
  2081. | 'cancelled';
  2082. slice_job_id: number | null;
  2083. sliced_library_file_id: number | null;
  2084. eligibility_overridden: boolean;
  2085. error_message: string | null;
  2086. created_by: number | null;
  2087. created_at: string;
  2088. started_at: string | null;
  2089. completed_at: string | null;
  2090. jobs: PipelineJob[];
  2091. target_kind: 'specific_printer' | 'printer_class' | null;
  2092. target_printer_id: number | null;
  2093. target_model_class: string | null;
  2094. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2095. }
  2096. export interface PipelineRunListResponse {
  2097. runs: PipelineRun[];
  2098. total: number;
  2099. }
  2100. export interface SliceResponse {
  2101. library_file_id: number;
  2102. name: string;
  2103. print_time_seconds: number;
  2104. filament_used_g: number;
  2105. filament_used_mm: number;
  2106. used_embedded_settings: boolean;
  2107. /** Why the result could not be written to the external folder the source
  2108. * lives in, and so went to managed storage instead. Null on every normal
  2109. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2110. * with no signal is what made #2810 invisible from the UI. */
  2111. external_write_fallback?: string | null;
  2112. }
  2113. export interface SliceArchiveResponse {
  2114. archive_id: number;
  2115. name: string;
  2116. print_time_seconds: number;
  2117. filament_used_g: number;
  2118. filament_used_mm: number;
  2119. used_embedded_settings: boolean;
  2120. }
  2121. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2122. // the frontend polls /slice-jobs/{id} until status is terminal.
  2123. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2124. export interface SliceJobEnqueueResponse {
  2125. job_id: number;
  2126. status: SliceJobStatus;
  2127. status_url: string;
  2128. }
  2129. export interface SliceJobProgress {
  2130. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2131. stage: string;
  2132. total_percent: number;
  2133. plate_percent: number;
  2134. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2135. plate_index: number;
  2136. plate_count: number;
  2137. updated_at: number;
  2138. /** When the backend is in the cross-class slice-all loop (#1493), each
  2139. * per-plate sub-slice's progress is augmented with the loop position
  2140. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2141. * fields are absent on a single-plate slice. */
  2142. multi_plate_index?: number;
  2143. multi_plate_count?: number;
  2144. }
  2145. export interface SliceJobState {
  2146. job_id: number;
  2147. status: SliceJobStatus;
  2148. kind: 'library_file' | 'archive';
  2149. source_id: number;
  2150. source_name: string;
  2151. created_at: string;
  2152. started_at: string | null;
  2153. completed_at: string | null;
  2154. /** Live progress fed by the sidecar's --pipe channel; null until the
  2155. * slicer emits its first frame (early "Initializing" phase) or when
  2156. * the sidecar doesn't support progress. */
  2157. progress: SliceJobProgress | null;
  2158. result?: SliceResponse | SliceArchiveResponse;
  2159. error_status?: number;
  2160. error_detail?: string;
  2161. }
  2162. // Local preset types (OrcaSlicer imports)
  2163. export interface LocalPreset {
  2164. id: number;
  2165. name: string;
  2166. preset_type: string;
  2167. source: string;
  2168. filament_type: string | null;
  2169. filament_vendor: string | null;
  2170. nozzle_temp_min: number | null;
  2171. nozzle_temp_max: number | null;
  2172. pressure_advance: string | null;
  2173. default_filament_colour: string | null;
  2174. filament_cost: string | null;
  2175. filament_density: string | null;
  2176. compatible_printers: string | null;
  2177. inherits: string | null;
  2178. version: string | null;
  2179. created_at: string;
  2180. updated_at: string;
  2181. }
  2182. export interface LocalPresetDetail extends LocalPreset {
  2183. setting: Record<string, unknown>;
  2184. }
  2185. export interface LocalPresetsResponse {
  2186. filament: LocalPreset[];
  2187. printer: LocalPreset[];
  2188. process: LocalPreset[];
  2189. }
  2190. export interface ImportResponse {
  2191. success: boolean;
  2192. imported: number;
  2193. skipped: number;
  2194. errors: string[];
  2195. }
  2196. export interface FieldOption {
  2197. value: string;
  2198. label: string;
  2199. }
  2200. export interface FieldDefinition {
  2201. key: string;
  2202. label: string;
  2203. type: 'text' | 'number' | 'boolean' | 'select';
  2204. category: string;
  2205. description?: string;
  2206. options?: FieldOption[];
  2207. unit?: string;
  2208. min?: number;
  2209. max?: number;
  2210. step?: number;
  2211. }
  2212. export interface FieldDefinitionsResponse {
  2213. version: string;
  2214. description: string;
  2215. fields: FieldDefinition[];
  2216. }
  2217. export interface CloudDevice {
  2218. dev_id: string;
  2219. name: string;
  2220. dev_model_name: string | null;
  2221. dev_product_name: string | null;
  2222. online: boolean;
  2223. }
  2224. // Smart Plug types
  2225. export interface SmartPlug {
  2226. id: number;
  2227. name: string;
  2228. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2229. ip_address: string | null; // Required for Tasmota
  2230. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2231. // Home Assistant energy sensor entities (optional)
  2232. ha_power_entity: string | null;
  2233. ha_energy_today_entity: string | null;
  2234. ha_energy_total_entity: string | null;
  2235. // MQTT fields (required when plug_type="mqtt")
  2236. // Legacy field - kept for backward compatibility
  2237. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2238. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2239. // Power monitoring
  2240. mqtt_power_topic: string | null; // Topic for power data
  2241. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2242. mqtt_power_multiplier: number; // Unit conversion for power
  2243. // Energy monitoring
  2244. mqtt_energy_topic: string | null; // Topic for energy data
  2245. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2246. mqtt_energy_multiplier: number; // Unit conversion for energy
  2247. // State monitoring
  2248. mqtt_state_topic: string | null; // Topic for state data
  2249. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2250. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2251. // REST/Webhook fields (required when plug_type="rest")
  2252. rest_on_url: string | null;
  2253. rest_on_body: string | null;
  2254. rest_off_url: string | null;
  2255. rest_off_body: string | null;
  2256. rest_method: string | null;
  2257. rest_headers: string | null;
  2258. rest_status_url: string | null;
  2259. rest_status_path: string | null;
  2260. rest_status_on_value: string | null;
  2261. rest_power_url: string | null;
  2262. rest_power_path: string | null;
  2263. rest_power_multiplier: number;
  2264. rest_energy_url: string | null;
  2265. rest_energy_path: string | null;
  2266. rest_energy_multiplier: number;
  2267. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2268. // this; Today and Yesterday are derived from its hourly snapshots.
  2269. rest_energy_total_path: string | null;
  2270. rest_energy_total_multiplier: number;
  2271. printer_id: number | null;
  2272. // #2629: only a plug that really feeds the printer may mark it offline when
  2273. // switched off. Accessory plugs follow the print cycle without powering it.
  2274. controls_printer_power: boolean;
  2275. enabled: boolean;
  2276. auto_on: boolean;
  2277. auto_off: boolean;
  2278. auto_off_persistent: boolean;
  2279. off_delay_mode: 'time' | 'temperature';
  2280. off_delay_minutes: number;
  2281. off_temp_threshold: number;
  2282. // #1349: auto-off after AMS drying completes.
  2283. auto_off_after_drying: boolean;
  2284. off_delay_after_drying_minutes: number;
  2285. username: string | null;
  2286. password: string | null;
  2287. // Power alerts
  2288. power_alert_enabled: boolean;
  2289. power_alert_high: number | null;
  2290. power_alert_low: number | null;
  2291. power_alert_last_triggered: string | null;
  2292. // Schedule
  2293. schedule_enabled: boolean;
  2294. schedule_on_time: string | null;
  2295. schedule_off_time: string | null;
  2296. // Visibility options
  2297. show_in_switchbar: boolean;
  2298. show_on_printer_card: boolean; // For scripts: show on printer card
  2299. // Status
  2300. last_state: string | null;
  2301. last_checked: string | null;
  2302. auto_off_executed: boolean; // True when auto-off was triggered after print
  2303. created_at: string;
  2304. updated_at: string;
  2305. }
  2306. export interface SmartPlugCreate {
  2307. name: string;
  2308. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2309. ip_address?: string | null; // Required for Tasmota
  2310. ha_entity_id?: string | null; // Required for Home Assistant
  2311. // Home Assistant energy sensor entities (optional)
  2312. ha_power_entity?: string | null;
  2313. ha_energy_today_entity?: string | null;
  2314. ha_energy_total_entity?: string | null;
  2315. // MQTT fields (required when plug_type="mqtt")
  2316. // Legacy fields - kept for backward compatibility
  2317. mqtt_topic?: string | null;
  2318. mqtt_multiplier?: number;
  2319. // Power monitoring
  2320. mqtt_power_topic?: string | null;
  2321. mqtt_power_path?: string | null;
  2322. mqtt_power_multiplier?: number;
  2323. // Energy monitoring
  2324. mqtt_energy_topic?: string | null;
  2325. mqtt_energy_path?: string | null;
  2326. mqtt_energy_multiplier?: number;
  2327. // State monitoring
  2328. mqtt_state_topic?: string | null;
  2329. mqtt_state_path?: string | null;
  2330. mqtt_state_on_value?: string | null;
  2331. // REST fields
  2332. rest_on_url?: string | null;
  2333. rest_on_body?: string | null;
  2334. rest_off_url?: string | null;
  2335. rest_off_body?: string | null;
  2336. rest_method?: string | null;
  2337. rest_headers?: string | null;
  2338. rest_status_url?: string | null;
  2339. rest_status_path?: string | null;
  2340. rest_status_on_value?: string | null;
  2341. rest_power_url?: string | null;
  2342. rest_power_path?: string | null;
  2343. rest_power_multiplier?: number;
  2344. rest_energy_url?: string | null;
  2345. rest_energy_path?: string | null;
  2346. rest_energy_multiplier?: number;
  2347. rest_energy_total_path?: string | null;
  2348. rest_energy_total_multiplier?: number;
  2349. printer_id?: number | null;
  2350. // #2629
  2351. controls_printer_power?: boolean;
  2352. enabled?: boolean;
  2353. auto_on?: boolean;
  2354. auto_off?: boolean;
  2355. auto_off_persistent?: boolean;
  2356. off_delay_mode?: 'time' | 'temperature';
  2357. off_delay_minutes?: number;
  2358. off_temp_threshold?: number;
  2359. // #1349
  2360. auto_off_after_drying?: boolean;
  2361. off_delay_after_drying_minutes?: number;
  2362. username?: string | null;
  2363. password?: string | null;
  2364. // Power alerts
  2365. power_alert_enabled?: boolean;
  2366. power_alert_high?: number | null;
  2367. power_alert_low?: number | null;
  2368. // Schedule
  2369. schedule_enabled?: boolean;
  2370. schedule_on_time?: string | null;
  2371. schedule_off_time?: string | null;
  2372. // Visibility options
  2373. show_in_switchbar?: boolean;
  2374. show_on_printer_card?: boolean;
  2375. }
  2376. export interface SmartPlugUpdate {
  2377. name?: string;
  2378. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2379. ip_address?: string | null;
  2380. ha_entity_id?: string | null;
  2381. // Home Assistant energy sensor entities (optional)
  2382. ha_power_entity?: string | null;
  2383. ha_energy_today_entity?: string | null;
  2384. ha_energy_total_entity?: string | null;
  2385. // MQTT fields (legacy)
  2386. mqtt_topic?: string | null;
  2387. mqtt_multiplier?: number;
  2388. // MQTT power fields
  2389. mqtt_power_topic?: string | null;
  2390. mqtt_power_path?: string | null;
  2391. mqtt_power_multiplier?: number;
  2392. // MQTT energy fields
  2393. mqtt_energy_topic?: string | null;
  2394. mqtt_energy_path?: string | null;
  2395. mqtt_energy_multiplier?: number;
  2396. // MQTT state fields
  2397. mqtt_state_topic?: string | null;
  2398. mqtt_state_path?: string | null;
  2399. mqtt_state_on_value?: string | null;
  2400. // REST fields
  2401. rest_on_url?: string | null;
  2402. rest_on_body?: string | null;
  2403. rest_off_url?: string | null;
  2404. rest_off_body?: string | null;
  2405. rest_method?: string | null;
  2406. rest_headers?: string | null;
  2407. rest_status_url?: string | null;
  2408. rest_status_path?: string | null;
  2409. rest_status_on_value?: string | null;
  2410. rest_power_url?: string | null;
  2411. rest_power_path?: string | null;
  2412. rest_power_multiplier?: number;
  2413. rest_energy_url?: string | null;
  2414. rest_energy_path?: string | null;
  2415. rest_energy_multiplier?: number;
  2416. rest_energy_total_path?: string | null;
  2417. rest_energy_total_multiplier?: number;
  2418. printer_id?: number | null;
  2419. // #2629
  2420. controls_printer_power?: boolean;
  2421. enabled?: boolean;
  2422. auto_on?: boolean;
  2423. auto_off?: boolean;
  2424. auto_off_persistent?: boolean;
  2425. off_delay_mode?: 'time' | 'temperature';
  2426. off_delay_minutes?: number;
  2427. off_temp_threshold?: number;
  2428. // #1349
  2429. auto_off_after_drying?: boolean;
  2430. off_delay_after_drying_minutes?: number;
  2431. username?: string | null;
  2432. password?: string | null;
  2433. // Power alerts
  2434. power_alert_enabled?: boolean;
  2435. power_alert_high?: number | null;
  2436. power_alert_low?: number | null;
  2437. // Schedule
  2438. schedule_enabled?: boolean;
  2439. schedule_on_time?: string | null;
  2440. schedule_off_time?: string | null;
  2441. // Visibility options
  2442. show_in_switchbar?: boolean;
  2443. show_on_printer_card?: boolean;
  2444. }
  2445. // Home Assistant entity for smart plug selection
  2446. export interface HAEntity {
  2447. entity_id: string;
  2448. friendly_name: string;
  2449. state: string | null;
  2450. domain: string; // "switch", "light", "input_boolean", "script"
  2451. }
  2452. // Home Assistant sensor entity for energy monitoring
  2453. export interface HASensorEntity {
  2454. entity_id: string;
  2455. friendly_name: string;
  2456. state: string | null;
  2457. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2458. }
  2459. export interface HATestConnectionResult {
  2460. success: boolean;
  2461. message: string | null;
  2462. error: string | null;
  2463. }
  2464. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2465. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2466. export interface PrinterHASensor {
  2467. id: number;
  2468. printer_id: number;
  2469. name: string;
  2470. entity_id: string;
  2471. kind: 'binary' | 'numeric';
  2472. device_class: string | null; // HA's own class: "door", "temperature", ...
  2473. unit: string | null; // numeric sensors only
  2474. // What counts as needing attention. Binary sensors use alert_state, numeric
  2475. // ones the thresholds; all null means the sensor is display-only.
  2476. alert_state: 'on' | 'off' | null;
  2477. alert_above: number | null;
  2478. alert_below: number | null;
  2479. block_print: boolean; // hold the printer's queue while alerting
  2480. notify_on_alert: boolean;
  2481. show_on_printer_card: boolean;
  2482. sort_order: number;
  2483. last_state: string | null;
  2484. last_changed: string | null;
  2485. last_checked: string | null;
  2486. created_at: string;
  2487. updated_at: string;
  2488. }
  2489. export interface PrinterHASensorReading {
  2490. id: number;
  2491. name: string;
  2492. entity_id: string;
  2493. kind: 'binary' | 'numeric';
  2494. device_class: string | null;
  2495. unit: string | null;
  2496. state: string | null; // null when unreadable or not yet polled
  2497. value: number | null; // numeric sensors only
  2498. alerting: boolean;
  2499. block_print: boolean;
  2500. reachable: boolean;
  2501. last_changed: string | null;
  2502. }
  2503. export interface PrinterHASensorCreate {
  2504. printer_id: number;
  2505. name: string;
  2506. entity_id: string;
  2507. kind: 'binary' | 'numeric';
  2508. device_class?: string | null;
  2509. unit?: string | null;
  2510. alert_state?: 'on' | 'off' | null;
  2511. alert_above?: number | null;
  2512. alert_below?: number | null;
  2513. block_print?: boolean;
  2514. notify_on_alert?: boolean;
  2515. show_on_printer_card?: boolean;
  2516. sort_order?: number;
  2517. }
  2518. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2519. export interface LocationHASensor {
  2520. id: number;
  2521. location_id: number;
  2522. name: string;
  2523. entity_id: string;
  2524. kind: 'binary' | 'numeric';
  2525. device_class: string | null;
  2526. unit: string | null;
  2527. alert_state: 'on' | 'off' | null;
  2528. alert_above: number | null;
  2529. alert_below: number | null;
  2530. notify_on_alert: boolean;
  2531. show_on_card: boolean;
  2532. sort_order: number;
  2533. last_state: string | null;
  2534. last_changed: string | null;
  2535. last_checked: string | null;
  2536. created_at: string;
  2537. updated_at: string;
  2538. }
  2539. export interface LocationHASensorReading {
  2540. id: number;
  2541. name: string;
  2542. entity_id: string;
  2543. kind: 'binary' | 'numeric';
  2544. device_class: string | null;
  2545. unit: string | null;
  2546. state: string | null;
  2547. value: number | null;
  2548. alerting: boolean;
  2549. reachable: boolean;
  2550. alert_state: string | null;
  2551. alert_above: number | null;
  2552. alert_below: number | null;
  2553. last_changed: string | null;
  2554. show_on_card: boolean;
  2555. }
  2556. export interface LocationHASensorCreate {
  2557. location_id: number;
  2558. name: string;
  2559. entity_id: string;
  2560. kind: 'binary' | 'numeric';
  2561. device_class?: string | null;
  2562. unit?: string | null;
  2563. alert_state?: 'on' | 'off' | null;
  2564. alert_above?: number | null;
  2565. alert_below?: number | null;
  2566. notify_on_alert?: boolean;
  2567. show_on_card?: boolean;
  2568. sort_order?: number;
  2569. }
  2570. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2571. // An entity offered by the binding picker.
  2572. export interface HADisplayEntity {
  2573. entity_id: string;
  2574. friendly_name: string;
  2575. state: string | null;
  2576. domain: string; // "binary_sensor" | "sensor"
  2577. device_class: string | null;
  2578. unit_of_measurement: string | null;
  2579. }
  2580. export interface SmartPlugEnergy {
  2581. power: number | null; // Current watts
  2582. voltage: number | null; // Volts
  2583. current: number | null; // Amps
  2584. today: number | null; // kWh used today
  2585. yesterday: number | null; // kWh used yesterday
  2586. total: number | null; // Total kWh
  2587. factor: number | null; // Power factor (0-1)
  2588. apparent_power: number | null; // VA
  2589. reactive_power: number | null; // VAr
  2590. }
  2591. export interface SmartPlugStatus {
  2592. state: string | null;
  2593. reachable: boolean;
  2594. device_name: string | null;
  2595. energy: SmartPlugEnergy | null;
  2596. }
  2597. export interface SmartPlugTestResult {
  2598. success: boolean;
  2599. state: string | null;
  2600. device_name: string | null;
  2601. }
  2602. // Tasmota Discovery types
  2603. export interface TasmotaScanStatus {
  2604. running: boolean;
  2605. scanned: number;
  2606. total: number;
  2607. }
  2608. export interface DiscoveredTasmotaDevice {
  2609. ip_address: string;
  2610. name: string;
  2611. module: number | null;
  2612. state: string | null;
  2613. discovered_at: string | null;
  2614. }
  2615. // Print Queue types
  2616. export interface PrintQueueItem {
  2617. id: number;
  2618. printer_id: number | null; // null = unassigned
  2619. target_model: string | null; // Target printer model for model-based assignment
  2620. target_location: string | null; // Target location filter for model-based assignment
  2621. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2622. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2623. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2624. // items. Present until dispatch resolves one, after which library_file_id and
  2625. // target_model name the candidate that actually ran.
  2626. variants?: Array<{
  2627. library_file_id: number;
  2628. filename: string;
  2629. target_model: string;
  2630. position: number;
  2631. }>;
  2632. // Either archive_id OR library_file_id must be set (archive created at print start)
  2633. archive_id: number | null;
  2634. library_file_id: number | null;
  2635. cost_center_id: number | null;
  2636. estimated_cost: number | null;
  2637. position: number;
  2638. scheduled_time: string | null;
  2639. require_previous_success: boolean;
  2640. auto_off_after: boolean;
  2641. manual_start: boolean; // Requires manual trigger to start (staged)
  2642. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2643. // any required slot's grams (#1496). Surfaced on the queue row as a
  2644. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2645. filament_short: boolean;
  2646. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2647. // skips the deficit check for this item (#1698-followup). Set by the
  2648. // start route when skip_filament_check=true, or at queue creation if
  2649. // PrintModal's deficit warning was acknowledged.
  2650. skip_filament_check: boolean;
  2651. // True when the source archive carries the slicer's own live-resolved
  2652. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2653. // exact physical spool instead of re-deriving one from type/color.
  2654. archive_has_slicer_ams_mapping: boolean;
  2655. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2656. 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
  2657. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2658. // Print options
  2659. bed_levelling: CalibrationMode;
  2660. flow_cali: CalibrationMode;
  2661. vibration_cali: boolean;
  2662. layer_inspect: boolean;
  2663. timelapse: boolean;
  2664. use_ams: boolean;
  2665. nozzle_offset_cali: CalibrationMode;
  2666. // Ask for a post-print outcome verdict when this job completes (#1898)
  2667. confirm_outcome: boolean;
  2668. preheat_override: 'inherit' | 'on' | 'off';
  2669. preheat_chamber_target_override: number | null;
  2670. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2671. started_at: string | null;
  2672. completed_at: string | null;
  2673. error_message: string | null;
  2674. created_at: string;
  2675. archive_name?: string | null;
  2676. archive_thumbnail?: string | null;
  2677. // True when the linked archive has been soft-deleted; archive_name /
  2678. // archive_thumbnail / downstream metadata are left null in that case so
  2679. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2680. archive_deleted?: boolean;
  2681. library_file_name?: string | null;
  2682. library_file_thumbnail?: string | null;
  2683. printer_name?: string | null;
  2684. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2685. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2686. filament_type?: string | null; // e.g. "PLA", "PETG"
  2687. filament_color?: string | null; // Hex RGBA from the slicer
  2688. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2689. // User tracking (Issue #206)
  2690. created_by_id?: number | null;
  2691. created_by_username?: string | null;
  2692. // Batch grouping
  2693. batch_id?: number | null;
  2694. batch_name?: string | null;
  2695. // Shortest-job-first scheduling
  2696. been_jumped?: boolean;
  2697. // Auto-print G-code injection
  2698. gcode_injection?: boolean;
  2699. cleanup_library_after_dispatch?: boolean;
  2700. /** Which rack position each filament group prints from, on a nozzle-rack
  2701. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2702. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2703. nozzle_rack_choice?: Record<number, number> | null;
  2704. /** Slots sent with a spool of another colour than the file asks for
  2705. * (#3279). Worked out when the job is sent; null when every slot got its
  2706. * colour or nothing could be compared. */
  2707. color_substitutions?: ColorSubstitution[] | null;
  2708. }
  2709. /** One slot printed in another colour than the file asked for (#3279). */
  2710. export interface ColorSubstitution {
  2711. slot_id: number;
  2712. type: string;
  2713. /** `#RRGGBB` the file asks for, after overrides. */
  2714. wanted: string;
  2715. /** `#RRGGBB` of the spool the slot was sent with. */
  2716. got: string;
  2717. tray: number;
  2718. }
  2719. export interface PrintBatchPlateTarget {
  2720. plate_id: number | null;
  2721. plate_name?: string | null;
  2722. quantity_target: number;
  2723. sort_order?: number;
  2724. }
  2725. export interface PrintBatchPlateProgress {
  2726. plate_id: number | null;
  2727. plate_name: string | null;
  2728. quantity_target: number;
  2729. dispatched: number;
  2730. remaining: number;
  2731. pending_count: number;
  2732. printing_count: number;
  2733. completed_count: number;
  2734. failed_count: number;
  2735. cancelled_count: number;
  2736. skipped_count: number;
  2737. /** Measured from finished runs; null until one has produced a cost. */
  2738. actual_cost: number | null;
  2739. estimated_remaining_cost: number | null;
  2740. filament_used_grams: number | null;
  2741. print_time_seconds: number;
  2742. /** False when this plate owes runs but has no queue item left to clone
  2743. * their configuration from, so queueing it could only fail (#2960). */
  2744. can_dispatch: boolean;
  2745. }
  2746. export interface PrintBatch {
  2747. id: number;
  2748. name: string;
  2749. archive_id: number | null;
  2750. library_file_id: number | null;
  2751. quantity: number;
  2752. status: string;
  2753. created_at: string;
  2754. completed_at: string | null;
  2755. created_by_id: number | null;
  2756. created_by_username: string | null;
  2757. project_id: number | null;
  2758. due_date: string | null;
  2759. notes: string | null;
  2760. /** Set when an integration (e.g. a shop connector) created the batch. */
  2761. external_source: string | null;
  2762. external_ref: string | null;
  2763. pending_count: number;
  2764. printing_count: number;
  2765. completed_count: number;
  2766. failed_count: number;
  2767. cancelled_count: number;
  2768. skipped_count: number;
  2769. /** False for batches created before per-plate targets existed (#342):
  2770. * they report progress but owe nothing and cannot be dispatched from. */
  2771. has_targets: boolean;
  2772. target_count: number;
  2773. remaining_count: number;
  2774. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2775. dispatchable_count: number;
  2776. actual_cost: number | null;
  2777. estimated_remaining_cost: number | null;
  2778. filament_used_grams: number | null;
  2779. print_time_seconds: number;
  2780. plates: PrintBatchPlateProgress[];
  2781. }
  2782. export interface PrintQueueItemCreate {
  2783. printer_id?: number | null; // null = unassigned
  2784. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2785. target_location?: string | null; // Target location filter (only used with target_model)
  2786. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2787. archive_id?: number | null;
  2788. library_file_id?: number | null;
  2789. scheduled_time?: string | null;
  2790. require_previous_success?: boolean;
  2791. auto_off_after?: boolean;
  2792. manual_start?: boolean; // Requires manual trigger to start (staged)
  2793. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2794. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2795. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2796. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2797. skip_filament_check?: boolean;
  2798. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2799. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2800. // Print options
  2801. bed_levelling?: CalibrationMode;
  2802. flow_cali?: CalibrationMode;
  2803. vibration_cali?: boolean;
  2804. layer_inspect?: boolean;
  2805. timelapse?: boolean;
  2806. use_ams?: boolean;
  2807. nozzle_offset_cali?: CalibrationMode;
  2808. // Ask for a post-print outcome verdict when this job completes (#1898)
  2809. confirm_outcome?: boolean;
  2810. preheat_override?: 'inherit' | 'on' | 'off';
  2811. preheat_chamber_target_override?: number | null;
  2812. // Auto-print G-code injection
  2813. gcode_injection?: boolean;
  2814. // Batch: create multiple copies (creates a batch if > 1)
  2815. quantity?: number;
  2816. // Existing batch to add this item into (multi-plate auto-batch flow).
  2817. batch_id?: number | null;
  2818. // Project to associate the resulting archive with
  2819. project_id?: number;
  2820. cost_center_id?: number | null;
  2821. estimated_cost?: number | null;
  2822. // Delete transient uploaded library file after scheduler creates the archive
  2823. cleanup_library_after_dispatch?: boolean;
  2824. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2825. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2826. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2827. // Order is priority — index 0 wins when several printers are idle at once.
  2828. variants?: QueueVariantCreate[];
  2829. /** Which rack position each filament group prints from, on a nozzle-rack
  2830. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2831. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2832. nozzle_rack_choice?: Record<number, number> | null;
  2833. }
  2834. /** One candidate file for a cross-model queue item (#671). */
  2835. export interface QueueVariantCreate {
  2836. library_file_id: number;
  2837. /** Read from the file's own sliced_for_model unless it declares none. */
  2838. target_model?: string | null;
  2839. plate_id?: number | null;
  2840. ams_mapping?: number[] | null;
  2841. nozzle_mapping?: number[] | null;
  2842. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2843. }
  2844. export interface PrintBatchCreate {
  2845. name: string;
  2846. archive_id?: number | null;
  2847. library_file_id?: number | null;
  2848. /** When set, the listed pending items are assigned to the new batch
  2849. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2850. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2851. item_ids?: number[];
  2852. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2853. plates?: PrintBatchPlateTarget[];
  2854. project_id?: number | null;
  2855. due_date?: string | null;
  2856. notes?: string | null;
  2857. }
  2858. export interface PrintBatchUpdate {
  2859. name?: string;
  2860. status?: 'active' | 'cancelled';
  2861. /** Replaces the full target set — a plate omitted here is removed. */
  2862. plates?: PrintBatchPlateTarget[];
  2863. project_id?: number | null;
  2864. due_date?: string | null;
  2865. notes?: string | null;
  2866. }
  2867. export interface PrintBatchDispatchRequest {
  2868. plate_id?: number | null;
  2869. only_plate?: boolean;
  2870. /** Cap on items created across all plates; omit to queue everything owed. */
  2871. limit?: number;
  2872. }
  2873. export interface PrintQueueItemUpdate {
  2874. printer_id?: number | null; // null = unassign
  2875. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2876. skip_filament_check?: boolean;
  2877. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2878. target_location?: string | null; // Target location filter (only used with target_model)
  2879. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2880. position?: number;
  2881. scheduled_time?: string | null;
  2882. require_previous_success?: boolean;
  2883. auto_off_after?: boolean;
  2884. manual_start?: boolean;
  2885. ams_mapping?: number[];
  2886. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2887. // Print options
  2888. bed_levelling?: CalibrationMode;
  2889. flow_cali?: CalibrationMode;
  2890. vibration_cali?: boolean;
  2891. layer_inspect?: boolean;
  2892. timelapse?: boolean;
  2893. use_ams?: boolean;
  2894. nozzle_offset_cali?: CalibrationMode;
  2895. // Ask for a post-print outcome verdict when this job completes (#1898)
  2896. confirm_outcome?: boolean;
  2897. preheat_override?: 'inherit' | 'on' | 'off';
  2898. preheat_chamber_target_override?: number | null;
  2899. // Auto-print G-code injection
  2900. gcode_injection?: boolean;
  2901. cost_center_id?: number | null;
  2902. estimated_cost?: number | null;
  2903. /** Which rack position each filament group prints from, on a nozzle-rack
  2904. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2905. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2906. nozzle_rack_choice?: Record<number, number> | null;
  2907. }
  2908. export interface PrintQueueBulkUpdate {
  2909. item_ids: number[];
  2910. printer_id?: number | null;
  2911. scheduled_time?: string | null;
  2912. require_previous_success?: boolean;
  2913. auto_off_after?: boolean;
  2914. manual_start?: boolean;
  2915. // Print options
  2916. bed_levelling?: CalibrationMode;
  2917. flow_cali?: CalibrationMode;
  2918. vibration_cali?: boolean;
  2919. layer_inspect?: boolean;
  2920. timelapse?: boolean;
  2921. use_ams?: boolean;
  2922. nozzle_offset_cali?: CalibrationMode;
  2923. // Ask for a post-print outcome verdict when this job completes (#1898)
  2924. confirm_outcome?: boolean;
  2925. preheat_override?: 'inherit' | 'on' | 'off';
  2926. preheat_chamber_target_override?: number | null;
  2927. // Auto-print G-code injection
  2928. gcode_injection?: boolean;
  2929. cost_center_id?: number | null;
  2930. estimated_cost?: number | null;
  2931. }
  2932. export interface PrintQueueBulkUpdateResponse {
  2933. updated_count: number;
  2934. skipped_count: number;
  2935. message: string;
  2936. }
  2937. // MQTT Logging types
  2938. export interface MQTTLogEntry {
  2939. timestamp: string;
  2940. topic: string;
  2941. direction: 'in' | 'out';
  2942. payload: Record<string, unknown>;
  2943. }
  2944. export interface MQTTLogsResponse {
  2945. logging_enabled: boolean;
  2946. logs: MQTTLogEntry[];
  2947. }
  2948. // K-Profile types
  2949. export interface KProfile {
  2950. slot_id: number;
  2951. extruder_id: number;
  2952. nozzle_id: string;
  2953. nozzle_diameter: string;
  2954. filament_id: string;
  2955. name: string;
  2956. k_value: string;
  2957. n_coef: string;
  2958. ams_id: number;
  2959. tray_id: number;
  2960. setting_id: string | null;
  2961. }
  2962. export interface KProfileCreate {
  2963. slot_id?: number; // Storage slot, 0 for new profiles
  2964. extruder_id?: number;
  2965. nozzle_id: string;
  2966. nozzle_diameter: string;
  2967. filament_id: string;
  2968. name: string;
  2969. k_value: string;
  2970. n_coef?: string;
  2971. ams_id?: number;
  2972. tray_id?: number;
  2973. setting_id?: string | null;
  2974. }
  2975. export interface KProfileDelete {
  2976. slot_id: number; // cali_idx - calibration index to delete
  2977. extruder_id: number;
  2978. nozzle_id: string; // e.g., "HH00-0.4"
  2979. nozzle_diameter: string; // e.g., "0.4"
  2980. filament_id: string; // Bambu filament identifier
  2981. setting_id?: string | null; // Setting ID (for X1C series)
  2982. }
  2983. export interface KProfilesResponse {
  2984. profiles: KProfile[];
  2985. nozzle_diameter: string;
  2986. }
  2987. export interface KProfileNote {
  2988. setting_id: string;
  2989. note: string;
  2990. }
  2991. export interface KProfileNotesResponse {
  2992. notes: Record<string, string>; // setting_id -> note
  2993. }
  2994. // Slot Preset Mapping
  2995. export interface SlotPresetMapping {
  2996. ams_id: number;
  2997. tray_id: number;
  2998. preset_id: string;
  2999. preset_name: string;
  3000. // Filament id the slot was configured with alongside this preset; null for
  3001. // rows that predate it or whose writer did not know it (#3216).
  3002. tray_info_idx?: string | null;
  3003. }
  3004. // Filament types
  3005. export interface Filament {
  3006. id: number;
  3007. name: string;
  3008. type: string; // PLA, PETG, ABS, etc.
  3009. brand: string | null;
  3010. color: string | null;
  3011. color_hex: string | null;
  3012. cost_per_kg: number;
  3013. spool_weight_g: number;
  3014. currency: string;
  3015. density: number | null;
  3016. print_temp_min: number | null;
  3017. print_temp_max: number | null;
  3018. bed_temp_min: number | null;
  3019. bed_temp_max: number | null;
  3020. created_at: string;
  3021. updated_at: string;
  3022. }
  3023. // Notification Provider types
  3024. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3025. // How a Telegram provider collects the outcome verdict (#3046)
  3026. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3027. export interface NotificationProvider {
  3028. id: number;
  3029. name: string;
  3030. provider_type: ProviderType;
  3031. enabled: boolean;
  3032. config: Record<string, unknown>;
  3033. attach_photo: boolean;
  3034. // Print lifecycle events
  3035. on_print_start: boolean;
  3036. on_print_complete: boolean;
  3037. on_print_failed: boolean;
  3038. on_print_stopped: boolean;
  3039. on_print_progress: boolean;
  3040. on_print_missing_spool_assignment: boolean;
  3041. on_billing_charge_failed: boolean;
  3042. // Printer status events
  3043. on_printer_offline: boolean;
  3044. on_printer_error: boolean;
  3045. on_ai_failure_detection: boolean;
  3046. on_filament_low: boolean;
  3047. on_maintenance_due: boolean;
  3048. // AMS environmental alarms (regular AMS)
  3049. on_ams_humidity_high: boolean;
  3050. on_ams_temperature_high: boolean;
  3051. on_ams_drying_suspended: boolean;
  3052. // AMS-HT environmental alarms
  3053. on_ams_ht_humidity_high: boolean;
  3054. on_ams_ht_temperature_high: boolean;
  3055. // Build plate detection
  3056. on_plate_not_empty: boolean;
  3057. on_plate_clear_required: boolean;
  3058. // Post-print outcome confirmation (#1898)
  3059. on_print_confirm_request: boolean;
  3060. telegram_verdict_mode: TelegramVerdictMode;
  3061. // Bed cooled
  3062. on_bed_cooled: boolean;
  3063. on_ha_sensor_alert: boolean;
  3064. on_location_ha_sensor_alert: boolean;
  3065. // First layer complete
  3066. on_first_layer_complete: boolean;
  3067. on_print_pause_upcoming: boolean;
  3068. on_app_message: boolean;
  3069. // Inventory stock alerts
  3070. on_stock_reorder_alert: boolean;
  3071. on_stock_break_alert: boolean;
  3072. // Print queue events
  3073. on_queue_job_added: boolean;
  3074. on_queue_job_assigned: boolean;
  3075. on_queue_job_started: boolean;
  3076. on_queue_job_waiting: boolean;
  3077. on_queue_job_skipped: boolean;
  3078. on_queue_job_failed: boolean;
  3079. on_queue_completed: boolean;
  3080. // Quiet hours
  3081. quiet_hours_enabled: boolean;
  3082. quiet_hours_start: string | null;
  3083. quiet_hours_end: string | null;
  3084. // Daily digest
  3085. daily_digest_enabled: boolean;
  3086. daily_digest_time: string | null;
  3087. // Printer filter
  3088. printer_id: number | null;
  3089. // Status tracking
  3090. last_success: string | null;
  3091. last_error: string | null;
  3092. last_error_at: string | null;
  3093. // Timestamps
  3094. created_at: string;
  3095. updated_at: string;
  3096. }
  3097. export interface NotificationProviderCreate {
  3098. name: string;
  3099. provider_type: ProviderType;
  3100. enabled?: boolean;
  3101. config: Record<string, unknown>;
  3102. attach_photo?: boolean;
  3103. // Print lifecycle events
  3104. on_print_start?: boolean;
  3105. on_print_complete?: boolean;
  3106. on_print_failed?: boolean;
  3107. on_print_stopped?: boolean;
  3108. on_print_progress?: boolean;
  3109. on_print_missing_spool_assignment?: boolean;
  3110. on_billing_charge_failed?: boolean;
  3111. // Printer status events
  3112. on_printer_offline?: boolean;
  3113. on_printer_error?: boolean;
  3114. on_ai_failure_detection?: boolean;
  3115. on_filament_low?: boolean;
  3116. on_maintenance_due?: boolean;
  3117. // AMS environmental alarms (regular AMS)
  3118. on_ams_humidity_high?: boolean;
  3119. on_ams_temperature_high?: boolean;
  3120. on_ams_drying_suspended?: boolean;
  3121. // AMS-HT environmental alarms
  3122. on_ams_ht_humidity_high?: boolean;
  3123. on_ams_ht_temperature_high?: boolean;
  3124. // Build plate detection
  3125. on_plate_not_empty?: boolean;
  3126. on_plate_clear_required?: boolean;
  3127. // Post-print outcome confirmation (#1898)
  3128. on_print_confirm_request?: boolean;
  3129. telegram_verdict_mode?: TelegramVerdictMode;
  3130. // Bed cooled
  3131. on_bed_cooled?: boolean;
  3132. on_ha_sensor_alert?: boolean;
  3133. on_location_ha_sensor_alert?: boolean;
  3134. // First layer complete
  3135. on_first_layer_complete?: boolean;
  3136. on_print_pause_upcoming?: boolean;
  3137. on_app_message?: boolean;
  3138. // Inventory stock alerts
  3139. on_stock_reorder_alert?: boolean;
  3140. on_stock_break_alert?: boolean;
  3141. // Print queue events
  3142. on_queue_job_added?: boolean;
  3143. on_queue_job_assigned?: boolean;
  3144. on_queue_job_started?: boolean;
  3145. on_queue_job_waiting?: boolean;
  3146. on_queue_job_skipped?: boolean;
  3147. on_queue_job_failed?: boolean;
  3148. on_queue_completed?: boolean;
  3149. // Quiet hours
  3150. quiet_hours_enabled?: boolean;
  3151. quiet_hours_start?: string | null;
  3152. quiet_hours_end?: string | null;
  3153. // Daily digest
  3154. daily_digest_enabled?: boolean;
  3155. daily_digest_time?: string | null;
  3156. // Printer filter
  3157. printer_id?: number | null;
  3158. }
  3159. export interface NotificationProviderUpdate {
  3160. name?: string;
  3161. provider_type?: ProviderType;
  3162. enabled?: boolean;
  3163. config?: Record<string, unknown>;
  3164. attach_photo?: boolean;
  3165. // Print lifecycle events
  3166. on_print_start?: boolean;
  3167. on_print_complete?: boolean;
  3168. on_print_failed?: boolean;
  3169. on_print_stopped?: boolean;
  3170. on_print_progress?: boolean;
  3171. on_print_missing_spool_assignment?: boolean;
  3172. on_billing_charge_failed?: boolean;
  3173. // Printer status events
  3174. on_printer_offline?: boolean;
  3175. on_printer_error?: boolean;
  3176. on_ai_failure_detection?: boolean;
  3177. on_filament_low?: boolean;
  3178. on_maintenance_due?: boolean;
  3179. // AMS environmental alarms (regular AMS)
  3180. on_ams_humidity_high?: boolean;
  3181. on_ams_temperature_high?: boolean;
  3182. on_ams_drying_suspended?: boolean;
  3183. // AMS-HT environmental alarms
  3184. on_ams_ht_humidity_high?: boolean;
  3185. on_ams_ht_temperature_high?: boolean;
  3186. // Build plate detection
  3187. on_plate_not_empty?: boolean;
  3188. on_plate_clear_required?: boolean;
  3189. // Post-print outcome confirmation (#1898)
  3190. on_print_confirm_request?: boolean;
  3191. telegram_verdict_mode?: TelegramVerdictMode;
  3192. // Bed cooled
  3193. on_bed_cooled?: boolean;
  3194. on_ha_sensor_alert?: boolean;
  3195. on_location_ha_sensor_alert?: boolean;
  3196. // First layer complete
  3197. on_first_layer_complete?: boolean;
  3198. on_print_pause_upcoming?: boolean;
  3199. on_app_message?: boolean;
  3200. // Inventory stock alerts
  3201. on_stock_reorder_alert?: boolean;
  3202. on_stock_break_alert?: boolean;
  3203. // Print queue events
  3204. on_queue_job_added?: boolean;
  3205. on_queue_job_assigned?: boolean;
  3206. on_queue_job_started?: boolean;
  3207. on_queue_job_waiting?: boolean;
  3208. on_queue_job_skipped?: boolean;
  3209. on_queue_job_failed?: boolean;
  3210. on_queue_completed?: boolean;
  3211. // Quiet hours
  3212. quiet_hours_enabled?: boolean;
  3213. quiet_hours_start?: string | null;
  3214. quiet_hours_end?: string | null;
  3215. // Daily digest
  3216. daily_digest_enabled?: boolean;
  3217. daily_digest_time?: string | null;
  3218. // Printer filter
  3219. printer_id?: number | null;
  3220. }
  3221. // GitHub Backup types
  3222. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3223. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3224. /** How many cloud accounts a backup would collect presets from. Counts only —
  3225. * with auth enabled the accounts belong to individual users, so the backup
  3226. * administrator sees how many, never whose. */
  3227. export interface CloudAccountCounts {
  3228. bambu: number;
  3229. orca: number;
  3230. }
  3231. export interface GitHubBackupConfig {
  3232. id: number;
  3233. repository_url: string;
  3234. has_token: boolean;
  3235. branch: string;
  3236. provider: GitProviderType;
  3237. allow_insecure_http: boolean;
  3238. schedule_enabled: boolean;
  3239. schedule_type: ScheduleType;
  3240. backup_kprofiles: boolean;
  3241. backup_cloud_profiles: boolean;
  3242. backup_settings: boolean;
  3243. backup_spools: boolean;
  3244. backup_archives: boolean;
  3245. enabled: boolean;
  3246. last_backup_at: string | null;
  3247. last_backup_status: string | null;
  3248. last_backup_message: string | null;
  3249. last_backup_commit_sha: string | null;
  3250. next_scheduled_run: string | null;
  3251. created_at: string;
  3252. updated_at: string;
  3253. }
  3254. export interface GitHubBackupConfigCreate {
  3255. repository_url: string;
  3256. access_token: string;
  3257. branch?: string;
  3258. provider?: GitProviderType;
  3259. allow_insecure_http?: boolean;
  3260. schedule_enabled?: boolean;
  3261. schedule_type?: ScheduleType;
  3262. backup_kprofiles?: boolean;
  3263. backup_cloud_profiles?: boolean;
  3264. backup_settings?: boolean;
  3265. backup_spools?: boolean;
  3266. backup_archives?: boolean;
  3267. enabled?: boolean;
  3268. }
  3269. export interface GitHubBackupLog {
  3270. id: number;
  3271. config_id: number;
  3272. started_at: string;
  3273. completed_at: string | null;
  3274. status: string;
  3275. trigger: string;
  3276. commit_sha: string | null;
  3277. files_changed: number;
  3278. error_message: string | null;
  3279. }
  3280. export interface GitHubBackupStatus {
  3281. configured: boolean;
  3282. enabled: boolean;
  3283. is_running: boolean;
  3284. restore_running: boolean;
  3285. progress: string | null;
  3286. last_backup_at: string | null;
  3287. last_backup_status: string | null;
  3288. next_scheduled_run: string | null;
  3289. }
  3290. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3291. // the backup collector never writes them, so there is nothing to restore.
  3292. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3293. export interface GitHubCommitInfo {
  3294. sha: string;
  3295. message: string;
  3296. author: string;
  3297. date: string;
  3298. }
  3299. export interface GitHubCommitListResponse {
  3300. success: boolean;
  3301. message: string;
  3302. branch: string;
  3303. commits: GitHubCommitInfo[];
  3304. }
  3305. /**
  3306. * Values the server interpolates into a translated note or preview detail.
  3307. * Kept to strings and numbers on purpose — anything richer would have to be
  3308. * formatted server-side and could not be translated.
  3309. */
  3310. export type GitHubRestoreParams = Record<string, string | number>;
  3311. export interface GitHubRestorePreviewCategory {
  3312. category: RestoreCategory;
  3313. available: boolean;
  3314. item_count: number;
  3315. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3316. detail: string | null;
  3317. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3318. detail_code: string | null;
  3319. detail_params: GitHubRestoreParams;
  3320. }
  3321. export interface GitHubRestorePreview {
  3322. success: boolean;
  3323. message: string;
  3324. ref: string;
  3325. commit: GitHubCommitInfo | null;
  3326. metadata_version: string | null;
  3327. categories: GitHubRestorePreviewCategory[];
  3328. }
  3329. export interface GitHubRestoreRequest {
  3330. ref?: string;
  3331. categories: RestoreCategory[];
  3332. overwrite_existing?: boolean;
  3333. }
  3334. /**
  3335. * One tally note, as a translation code plus its parameters (#2656).
  3336. *
  3337. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3338. * the code and supplies typed params, and the client renders
  3339. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3340. * A code the client does not know yet falls back to the English `message`
  3341. * rather than showing the raw key.
  3342. */
  3343. export interface GitHubRestoreNote {
  3344. code: string;
  3345. params: GitHubRestoreParams;
  3346. message: string;
  3347. }
  3348. export interface GitHubRestoreCategoryResult {
  3349. restored: number;
  3350. skipped: number;
  3351. failed: number;
  3352. notes: GitHubRestoreNote[];
  3353. }
  3354. export interface GitHubRestoreResponse {
  3355. success: boolean;
  3356. message: string;
  3357. log_id: number | null;
  3358. ref: string | null;
  3359. results: Record<string, GitHubRestoreCategoryResult>;
  3360. }
  3361. export interface LocalBackupStatus {
  3362. enabled: boolean;
  3363. schedule: string;
  3364. time: string;
  3365. retention: number;
  3366. path: string;
  3367. default_path: string;
  3368. is_running: boolean;
  3369. last_backup_at: string | null;
  3370. last_status: string | null;
  3371. last_message: string | null;
  3372. next_run: string | null;
  3373. timezone: string;
  3374. }
  3375. export interface LocalBackupFile {
  3376. filename: string;
  3377. size: number;
  3378. created_at: string;
  3379. }
  3380. /** Result of writing a probe file into the configured backup directory (#2544). */
  3381. export interface LocalBackupPathCheck {
  3382. writable: boolean;
  3383. path: string;
  3384. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3385. code: string;
  3386. /** Raw OS error, shown as-is under the translated explanation. */
  3387. detail: string | null;
  3388. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3389. remedy: string | null;
  3390. message: string;
  3391. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3392. warning: string | null;
  3393. }
  3394. export interface ObicoDetectionEvent {
  3395. printer_id: number;
  3396. task_name: string;
  3397. timestamp: string;
  3398. current_p: number;
  3399. score: number;
  3400. class: 'safe' | 'warning' | 'failure';
  3401. detections: number;
  3402. }
  3403. export interface ObicoStatus {
  3404. is_running: boolean;
  3405. last_error: string | null;
  3406. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3407. thresholds: { low: number; high: number; pause?: number };
  3408. history: ObicoDetectionEvent[];
  3409. enabled: boolean;
  3410. ml_url: string;
  3411. sensitivity: 'low' | 'medium' | 'high';
  3412. action: 'notify' | 'pause' | 'pause_and_off';
  3413. poll_interval: number;
  3414. external_url_configured: boolean;
  3415. }
  3416. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3417. export interface ObicoPrinterStatus {
  3418. enabled: boolean;
  3419. // null = all printers are monitored
  3420. monitored_printers: number[] | null;
  3421. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3422. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3423. last_error: string | null;
  3424. }
  3425. export interface ObicoTestConnection {
  3426. ok: boolean;
  3427. status_code: number | null;
  3428. body: string | null;
  3429. error: string | null;
  3430. // Whether the ML API accepted the token. null = not determined (the health
  3431. // check failed first, or the token probe itself errored).
  3432. auth_ok: boolean | null;
  3433. }
  3434. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3435. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3436. export interface OctoEverywhereDetection {
  3437. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3438. print_quality: number | null;
  3439. frame_count: number;
  3440. error?: string | null;
  3441. error_code: string | null;
  3442. }
  3443. export interface OctoEverywhereDetectionEvent {
  3444. timestamp: string;
  3445. printer_id: number;
  3446. class: OctoEverywhereDetection['class'];
  3447. print_quality: number | null;
  3448. }
  3449. export interface OctoEverywhereStatus {
  3450. enabled: boolean;
  3451. api_key_configured: boolean;
  3452. confidence: OctoEverywhereConfidence;
  3453. action: 'notify' | 'pause' | 'pause_and_off';
  3454. poll_interval: number;
  3455. is_running: boolean;
  3456. last_error: string | null;
  3457. last_error_code: string | null;
  3458. per_printer: Record<string, OctoEverywhereDetection>;
  3459. history: OctoEverywhereDetectionEvent[];
  3460. notifications: { configured: boolean; uncovered_printers: number[] };
  3461. }
  3462. export interface OctoEverywherePrinterStatus {
  3463. enabled: boolean;
  3464. // null = all printers are monitored
  3465. monitored_printers: number[] | null;
  3466. per_printer: Record<string, OctoEverywhereDetection>;
  3467. last_error: string | null;
  3468. last_error_code: string | null;
  3469. }
  3470. export interface OctoEverywhereTestConnection {
  3471. ok: boolean;
  3472. status_code: number | null;
  3473. error: string | null;
  3474. error_code: string | null;
  3475. }
  3476. export interface GitHubTestConnectionResponse {
  3477. success: boolean;
  3478. message: string;
  3479. repo_name: string | null;
  3480. permissions: Record<string, boolean> | null;
  3481. // true = confirmed private, false = confirmed public/internal,
  3482. // null = could not determine. Backend rejects save unless true.
  3483. is_private: boolean | null;
  3484. }
  3485. export interface GitHubBackupTriggerResponse {
  3486. success: boolean;
  3487. message: string;
  3488. log_id: number | null;
  3489. commit_sha: string | null;
  3490. files_changed: number;
  3491. }
  3492. export interface NotificationTestRequest {
  3493. provider_type: ProviderType;
  3494. config: Record<string, unknown>;
  3495. attach_photo?: boolean;
  3496. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3497. provider_id?: number;
  3498. }
  3499. export interface NotificationTestResponse {
  3500. success: boolean;
  3501. message: string;
  3502. }
  3503. // Provider-specific config types for reference
  3504. export interface CallMeBotConfig {
  3505. phone: string;
  3506. apikey: string;
  3507. }
  3508. export interface NtfyConfig {
  3509. server?: string;
  3510. topic: string;
  3511. auth_token?: string | null;
  3512. }
  3513. export interface PushoverConfig {
  3514. user_key: string;
  3515. app_token: string;
  3516. priority?: number;
  3517. }
  3518. export interface NotifyConfig {
  3519. device_id: string;
  3520. token: string;
  3521. icon_url?: string;
  3522. group_type?: string;
  3523. live_activities?: boolean;
  3524. lock_screen_widgets?: boolean;
  3525. live_activity_privacy?: boolean;
  3526. live_activity_stage?: boolean;
  3527. live_activity_style?: 'bar' | 'segments' | 'none';
  3528. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3529. live_activity_button_url?: string;
  3530. live_activity_symbol?: string;
  3531. live_activity_tint?: string;
  3532. time_sensitive?: boolean;
  3533. }
  3534. export interface TelegramConfig {
  3535. bot_token: string;
  3536. chat_id: string;
  3537. }
  3538. export interface EmailConfig {
  3539. smtp_server: string;
  3540. smtp_port?: number;
  3541. username: string;
  3542. password: string;
  3543. from_email: string;
  3544. to_email: string;
  3545. use_tls?: boolean;
  3546. }
  3547. // Notification Template types
  3548. export interface NotificationTemplate {
  3549. id: number;
  3550. event_type: string;
  3551. name: string;
  3552. title_template: string;
  3553. body_template: string;
  3554. is_default: boolean;
  3555. created_at: string;
  3556. updated_at: string;
  3557. }
  3558. export interface NotificationTemplateUpdate {
  3559. title_template?: string;
  3560. body_template?: string;
  3561. }
  3562. export interface EventVariablesResponse {
  3563. event_type: string;
  3564. event_name: string;
  3565. variables: string[];
  3566. supports_photo: boolean;
  3567. }
  3568. export interface TemplatePreviewRequest {
  3569. event_type: string;
  3570. title_template: string;
  3571. body_template: string;
  3572. }
  3573. export interface TemplatePreviewResponse {
  3574. title: string;
  3575. body: string;
  3576. }
  3577. // Notification Log types
  3578. export interface NotificationLogEntry {
  3579. id: number;
  3580. provider_id: number;
  3581. provider_name: string | null;
  3582. provider_type: string | null;
  3583. event_type: string;
  3584. title: string;
  3585. message: string;
  3586. success: boolean;
  3587. error_message: string | null;
  3588. printer_id: number | null;
  3589. printer_name: string | null;
  3590. created_at: string;
  3591. }
  3592. export interface NotificationLogStats {
  3593. total: number;
  3594. success_count: number;
  3595. failure_count: number;
  3596. by_event_type: Record<string, number>;
  3597. by_provider: Record<string, number>;
  3598. }
  3599. // Spoolman types
  3600. export interface SpoolmanStatus {
  3601. enabled: boolean;
  3602. connected: boolean;
  3603. url: string | null;
  3604. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3605. }
  3606. export interface SpoolmanTagMigrationReport {
  3607. dry_run: boolean;
  3608. moved: number[];
  3609. already: number;
  3610. slot_ids: number;
  3611. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3612. }
  3613. export interface SkippedSpool {
  3614. location: string;
  3615. reason: string;
  3616. filament_type: string | null;
  3617. color: string | null;
  3618. }
  3619. export interface SpoolmanSyncResult {
  3620. success: boolean;
  3621. synced_count: number;
  3622. skipped_count: number;
  3623. skipped: SkippedSpool[];
  3624. errors: string[];
  3625. }
  3626. export interface UnlinkedSpool {
  3627. id: number;
  3628. filament_name: string | null;
  3629. filament_vendor: string | null;
  3630. filament_material: string | null;
  3631. filament_color_hex: string | null;
  3632. remaining_weight: number | null;
  3633. location: string | null;
  3634. }
  3635. export interface LinkedSpoolInfo {
  3636. id: number;
  3637. remaining_weight: number | null;
  3638. filament_weight: number | null;
  3639. }
  3640. export interface LinkedSpoolsMap {
  3641. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3642. }
  3643. export interface SpoolmanVendor {
  3644. id: number;
  3645. name: string;
  3646. }
  3647. export interface SpoolmanFilamentEntry {
  3648. id: number;
  3649. name: string;
  3650. material: string | null;
  3651. color_hex: string | null;
  3652. color_name: string | null;
  3653. weight: number | null;
  3654. spool_weight: number | null;
  3655. vendor: SpoolmanVendor | null;
  3656. }
  3657. // Inventory types
  3658. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3659. export type SpoolLabelTemplate =
  3660. | 'ams_holder_74x33'
  3661. | 'ams_holder_75x55'
  3662. | 'box_40x30'
  3663. | 'box_62x29'
  3664. | 'avery_5160'
  3665. | 'avery_l7160';
  3666. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3667. export const SPOOL_LABEL_FIELDS = [
  3668. 'brand',
  3669. 'material',
  3670. 'hex',
  3671. 'name',
  3672. 'location',
  3673. 'material_number',
  3674. 'temps',
  3675. 'weight',
  3676. 'note',
  3677. 'added',
  3678. 'qr',
  3679. 'spool_id',
  3680. ] as const;
  3681. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3682. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3683. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3684. 'brand',
  3685. 'material',
  3686. 'hex',
  3687. 'name',
  3688. 'location',
  3689. 'qr',
  3690. 'spool_id',
  3691. ];
  3692. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3693. // backend.app.schemas.label_template.SheetLayoutSpec.
  3694. export type LabelPageSize = 'a4' | 'letter';
  3695. export interface LabelSheetLayout {
  3696. page: LabelPageSize;
  3697. label_w_mm: number;
  3698. label_h_mm: number;
  3699. cols: number;
  3700. rows: number;
  3701. top_mm: number;
  3702. left_mm: number;
  3703. col_gap_mm: number;
  3704. row_gap_mm: number;
  3705. }
  3706. // A custom sheet saved under a name, shared by everyone on the install.
  3707. export interface SavedLabelTemplate {
  3708. id: number;
  3709. name: string;
  3710. layout: LabelSheetLayout;
  3711. created_at: string;
  3712. updated_at: string;
  3713. }
  3714. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3715. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3716. export interface PrintSpoolLabelsRequest {
  3717. spool_ids: number[];
  3718. template: SpoolLabelRequestTemplate;
  3719. layout?: LabelSheetLayout;
  3720. monochrome: boolean;
  3721. starting_position: number;
  3722. fields?: SpoolLabelField[];
  3723. format?: 'pdf' | 'png';
  3724. dpi?: 203 | 300 | 600;
  3725. }
  3726. export interface PreviewSpoolLabelRequest {
  3727. spool_id: number;
  3728. template: SpoolLabelRequestTemplate;
  3729. layout?: LabelSheetLayout;
  3730. monochrome: boolean;
  3731. fields: SpoolLabelField[];
  3732. }
  3733. export interface InventorySpool {
  3734. id: number;
  3735. material: string;
  3736. subtype: string | null;
  3737. color_name: string | null;
  3738. // True when color_name was synthesised from subtype because Spoolman has no
  3739. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3740. // leave the input blank, so the user doesn't round-trip the synth value
  3741. // back to Spoolman as if it were a real user-set color_name (#1319).
  3742. color_name_is_synthesized?: boolean;
  3743. rgba: string | null;
  3744. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3745. extra_colors: string | null;
  3746. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3747. effect_type: string | null;
  3748. brand: string | null;
  3749. label_weight: number;
  3750. core_weight: number;
  3751. // Spoolman-backed inventory only: true when the spool has no tare of its
  3752. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3753. core_weight_is_inherited?: boolean;
  3754. core_weight_catalog_id: number | null;
  3755. weight_used: number;
  3756. // Anchor for the resettable "Total Consumed" display (#1390). The
  3757. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3758. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3759. // zeroes the counter without disturbing remaining. Optional for back-compat
  3760. // with rows from a pre-migration DB snapshot — default to 0.
  3761. weight_used_baseline?: number;
  3762. slicer_filament: string | null;
  3763. slicer_filament_name: string | null;
  3764. nozzle_temp_min: number | null;
  3765. nozzle_temp_max: number | null;
  3766. note: string | null;
  3767. added_full: boolean | null;
  3768. last_used: string | null;
  3769. // Spoolman mode: when the spool was first printed with (#3407).
  3770. first_used?: string | null;
  3771. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3772. // length ends, or set by hand. Temperature and hours are null when unknown.
  3773. last_dried_at?: string | null;
  3774. last_dried_temp?: number | null;
  3775. last_dried_hours?: number | null;
  3776. encode_time: string | null;
  3777. tag_uid: string | null;
  3778. tray_uuid: string | null;
  3779. data_origin: string | null;
  3780. tag_type: string | null;
  3781. archived_at: string | null;
  3782. created_at: string;
  3783. updated_at: string;
  3784. cost_per_kg: number | null;
  3785. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3786. // else its filament's. Display only; the form edits cost_per_kg.
  3787. effective_cost_per_kg?: number | null;
  3788. last_scale_weight: number | null;
  3789. last_weighed_at: string | null;
  3790. // User-defined category + per-spool low-stock threshold override (#729).
  3791. category: string | null;
  3792. low_stock_threshold_pct: number | null;
  3793. // Internal material / article number (#2870) — the purchasing identifier
  3794. // shared by all spools of the same product.
  3795. material_number: string | null;
  3796. k_profiles?: SpoolKProfile[];
  3797. storage_location?: string | null;
  3798. location_id?: number | null;
  3799. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3800. // vendor is the manufacturer, not the seller, so there is no mapping.
  3801. suppliers?: SpoolSupplierLink[];
  3802. }
  3803. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3804. /** Where filament is bought — distinct from brand (who made it). */
  3805. export interface Supplier {
  3806. id: number;
  3807. name: string;
  3808. website: string | null;
  3809. customer_number: string | null;
  3810. note: string | null;
  3811. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3812. spool_count: number;
  3813. created_at: string;
  3814. updated_at: string;
  3815. }
  3816. export interface SupplierInput {
  3817. name: string;
  3818. website?: string | null;
  3819. customer_number?: string | null;
  3820. note?: string | null;
  3821. }
  3822. /** One spool-to-supplier assignment as written by the spool dialog. */
  3823. export interface SpoolSupplierLinkInput {
  3824. supplier_id: number;
  3825. /** The supplier's own article number — NOT the internal material number. */
  3826. supplier_article_number?: string | null;
  3827. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3828. quoted_price_per_kg?: number | null;
  3829. /** Marks where this concrete spool was actually bought. */
  3830. is_purchase_source?: boolean;
  3831. }
  3832. export interface SpoolSupplierLink {
  3833. id: number;
  3834. supplier_id: number;
  3835. supplier_name: string;
  3836. supplier_article_number: string | null;
  3837. quoted_price_per_kg: number | null;
  3838. is_purchase_source: boolean;
  3839. }
  3840. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3841. export interface SupplierStats {
  3842. supplier_id: number;
  3843. supplier_name: string;
  3844. spool_count: number;
  3845. remaining_g: number;
  3846. consumed_g: number;
  3847. cost: number;
  3848. }
  3849. /** Per-material-number inventory aggregate (#2870). */
  3850. export interface MaterialNumberStats {
  3851. material_number: string;
  3852. spool_count: number;
  3853. remaining_g: number;
  3854. consumed_g: number;
  3855. cost: number;
  3856. }
  3857. export interface SpoolmanBulkCreateResult {
  3858. created: InventorySpool[];
  3859. requested_count: number;
  3860. failed_count: number;
  3861. }
  3862. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3863. /** One row's outcome from the import preview / real import. */
  3864. export interface CsvImportRow {
  3865. row_number: number;
  3866. status: 'valid' | 'error' | 'skipped';
  3867. reason: string | null;
  3868. material: string | null;
  3869. brand: string | null;
  3870. color_name: string | null;
  3871. rgba: string | null;
  3872. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3873. resolved_color: boolean;
  3874. /** The catalog match came from a different material's variant (no exact
  3875. * material match). Shown as a warning in the preview. */
  3876. cross_material_color: boolean;
  3877. /** An active spool with the same material+brand+color already exists.
  3878. * Informational only — the import still creates the row. */
  3879. duplicate_of_existing: boolean;
  3880. }
  3881. /** Dry-run preview: per-row classification, no rows written. */
  3882. export interface CsvImportPreview {
  3883. columns: string[];
  3884. total: number;
  3885. valid_count: number;
  3886. error_count: number;
  3887. skipped_count: number;
  3888. rows: CsvImportRow[];
  3889. warnings: string[];
  3890. }
  3891. /** Summary returned after a real (non-dry-run) import. */
  3892. export interface CsvImportResult {
  3893. created: number;
  3894. skipped: number;
  3895. errors: number;
  3896. error_rows: CsvImportRow[];
  3897. }
  3898. export interface SpoolUsageRecord {
  3899. id: number;
  3900. // null: the spool was deleted, its usage kept
  3901. spool_id: number | null;
  3902. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  3903. spoolman_spool_id?: number | null;
  3904. printer_id: number | null;
  3905. print_name: string | null;
  3906. weight_used: number;
  3907. percent_used: number;
  3908. status: string;
  3909. cost: number | null;
  3910. created_at: string;
  3911. }
  3912. export interface SpoolKProfile {
  3913. id: number;
  3914. spool_id: number;
  3915. printer_id: number;
  3916. extruder: number;
  3917. nozzle_diameter: string;
  3918. nozzle_type: string | null;
  3919. k_value: number;
  3920. name: string | null;
  3921. cali_idx: number | null;
  3922. setting_id: string | null;
  3923. created_at: string;
  3924. }
  3925. export interface SpoolKProfileInput {
  3926. printer_id: number;
  3927. extruder?: number;
  3928. nozzle_diameter?: string;
  3929. nozzle_type?: string | null;
  3930. k_value: number;
  3931. name?: string | null;
  3932. cali_idx?: number | null;
  3933. setting_id?: string | null;
  3934. }
  3935. /**
  3936. * One per-printer-model override of a spool's slicer filament preset.
  3937. *
  3938. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  3939. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  3940. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  3941. * decimal ("0.2") for a per-hotend exception; the backend resolves
  3942. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  3943. */
  3944. export interface SlotSpoolDefaults {
  3945. slicer_filament: string | null;
  3946. slicer_filament_name: string | null;
  3947. cali_idx: number | null;
  3948. k_value: number | null;
  3949. profile_name: string | null;
  3950. extruder: number | null;
  3951. nozzle_diameter: string;
  3952. }
  3953. export interface SpoolFilamentPresetInput {
  3954. printer_model: string;
  3955. nozzle_diameter: string;
  3956. slicer_filament: string | null;
  3957. slicer_filament_name: string | null;
  3958. }
  3959. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  3960. id: number;
  3961. spool_id: number;
  3962. created_at: string;
  3963. }
  3964. /**
  3965. * What a new spool of one product starts with (#1326): the slicer preset, the
  3966. * per-model preset overrides and the K profiles. `color_name` "" is the
  3967. * default for every colour of the product; one with a colour wins over it per
  3968. * preset and per hotend. Shared by both inventory modes.
  3969. */
  3970. export interface ProfileDefaultKey {
  3971. brand: string;
  3972. material: string;
  3973. subtype: string;
  3974. color_name: string;
  3975. }
  3976. export interface ProfileDefaultInput extends ProfileDefaultKey {
  3977. slicer_filament: string | null;
  3978. slicer_filament_name: string | null;
  3979. presets: SpoolFilamentPresetInput[];
  3980. k_profiles: SpoolKProfileInput[];
  3981. }
  3982. export interface ProfileDefault extends ProfileDefaultInput {
  3983. id: number;
  3984. updated_at: string;
  3985. }
  3986. /** Both levels of a product's default merged, as a create applies them. */
  3987. export interface ResolvedProfileDefault {
  3988. slicer_filament: string | null;
  3989. slicer_filament_name: string | null;
  3990. presets: SpoolFilamentPresetInput[];
  3991. k_profiles: SpoolKProfileInput[];
  3992. default_ids: number[];
  3993. }
  3994. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  3995. export interface SlotMaterial {
  3996. ams_id: number;
  3997. tray_id: number;
  3998. global_tray_id: number;
  3999. /** Opaque grouping key from the backend. Two slots back each other up under
  4000. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4001. * Never parse it — the format belongs to the backend's identity rule. */
  4002. material_key: string;
  4003. remaining_g: number;
  4004. /** 0 = right / single nozzle, 1 = left. */
  4005. extruder: number;
  4006. /** How the bound spool should be *named* — display only, never matched on.
  4007. * The printer has no brand field and reports no sub-brand for a
  4008. * third-party spool, so this is the only place a slot's real identity
  4009. * exists. Null when the binding resolves to a spool we cannot describe. */
  4010. spool?: SlotSpoolIdentity | null;
  4011. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4012. * which is charged at the default rate. Optional for an older backend. */
  4013. cost_per_kg?: number | null;
  4014. }
  4015. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4016. export interface SlotSpoolIdentity {
  4017. brand: string | null;
  4018. material: string | null;
  4019. subtype: string | null;
  4020. color_name: string | null;
  4021. rgba: string | null;
  4022. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4023. * overlay — the two things a tray record cannot carry, so a slot swatch
  4024. * can be drawn the way the inventory row draws it (#3159).
  4025. *
  4026. * Optional rather than required: the backend sends both keys on every
  4027. * binding, but a frontend running against an older one gets neither, and
  4028. * every reader here already falls back to a solid swatch. */
  4029. extra_colors?: string | null;
  4030. effect_type?: string | null;
  4031. }
  4032. export interface InventoryRemainResponse {
  4033. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4034. inventory_remain_g: Record<string, number>;
  4035. /** Every inventory binding on the printer, with identity + extruder side. */
  4036. slot_materials: SlotMaterial[];
  4037. }
  4038. export interface SpoolAssignment {
  4039. id: number;
  4040. spool_id: number;
  4041. printer_id: number;
  4042. printer_name: string | null;
  4043. ams_id: number;
  4044. tray_id: number;
  4045. fingerprint_color: string | null;
  4046. fingerprint_type: string | null;
  4047. spool?: InventorySpool | null;
  4048. configured: boolean;
  4049. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4050. created_at: string;
  4051. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4052. }
  4053. export interface FilamentSkuSettings {
  4054. id: number;
  4055. material: string;
  4056. subtype: string | null;
  4057. brand: string | null;
  4058. color_name: string | null;
  4059. lead_time_days: number;
  4060. safety_margin_value: number;
  4061. safety_margin_unit: 'days' | 'g';
  4062. alerts_snoozed: boolean;
  4063. }
  4064. export interface ShoppingListItem {
  4065. id: number;
  4066. material: string;
  4067. subtype: string | null;
  4068. brand: string | null;
  4069. color_name: string | null;
  4070. quantity_spools: number;
  4071. note: string | null;
  4072. status: 'pending' | 'purchased' | 'received';
  4073. purchased_at: string | null;
  4074. added_at: string;
  4075. }
  4076. export interface ShoppingListItemCreate {
  4077. material: string;
  4078. subtype: string | null;
  4079. brand: string | null;
  4080. color_name: string | null;
  4081. quantity_spools: number;
  4082. note?: string | null;
  4083. }
  4084. // Update types
  4085. export interface VersionInfo {
  4086. version: string;
  4087. repo: string;
  4088. }
  4089. export interface UpdateCheckResult {
  4090. update_available: boolean;
  4091. current_version: string;
  4092. latest_version: string | null;
  4093. release_name?: string;
  4094. release_notes?: string;
  4095. release_url?: string;
  4096. published_at?: string;
  4097. error?: string;
  4098. message?: string;
  4099. is_docker?: boolean;
  4100. is_ha_addon?: boolean;
  4101. is_windows_installer?: boolean;
  4102. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4103. installer_download_url?: string | null;
  4104. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4105. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4106. // that field falls back to this guess instead of resurrecting the old value.
  4107. compose_dir_detected?: string | null;
  4108. }
  4109. export interface UpdateStatus {
  4110. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4111. progress: number;
  4112. message: string;
  4113. error: string | null;
  4114. }
  4115. // Maintenance types
  4116. export interface MaintenanceType {
  4117. id: number;
  4118. name: string;
  4119. description: string | null;
  4120. default_interval_hours: number;
  4121. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4122. icon: string | null;
  4123. wiki_url: string | null; // Documentation link
  4124. is_system: boolean;
  4125. created_at: string;
  4126. }
  4127. export interface MaintenanceTypeCreate {
  4128. name: string;
  4129. description?: string | null;
  4130. default_interval_hours?: number;
  4131. interval_type?: 'hours' | 'days';
  4132. icon?: string | null;
  4133. wiki_url?: string | null;
  4134. }
  4135. export interface MaintenanceStatus {
  4136. id: number;
  4137. printer_id: number;
  4138. printer_name: string;
  4139. printer_model: string | null;
  4140. maintenance_type_id: number;
  4141. maintenance_type_name: string;
  4142. maintenance_type_icon: string | null;
  4143. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4144. enabled: boolean;
  4145. interval_hours: number; // For hours type: print hours; for days type: number of days
  4146. interval_type: 'hours' | 'days';
  4147. current_hours: number;
  4148. hours_since_maintenance: number;
  4149. hours_until_due: number;
  4150. days_since_maintenance: number | null; // For days type
  4151. days_until_due: number | null; // For days type
  4152. is_due: boolean;
  4153. is_warning: boolean;
  4154. last_performed_at: string | null;
  4155. }
  4156. export interface PrinterMaintenanceOverview {
  4157. printer_id: number;
  4158. printer_name: string;
  4159. printer_model: string | null;
  4160. total_print_hours: number;
  4161. maintenance_items: MaintenanceStatus[];
  4162. due_count: number;
  4163. warning_count: number;
  4164. }
  4165. // External Links (sidebar)
  4166. export interface ExternalLink {
  4167. id: number;
  4168. name: string;
  4169. url: string;
  4170. icon: string;
  4171. open_in_new_tab: boolean;
  4172. custom_icon: string | null;
  4173. sort_order: number;
  4174. created_at: string;
  4175. updated_at: string;
  4176. /** Count reported by the app the link points to, while it keeps reporting. */
  4177. badge_count?: number | null;
  4178. }
  4179. export interface ExternalLinkCreate {
  4180. name: string;
  4181. url: string;
  4182. icon: string;
  4183. open_in_new_tab?: boolean;
  4184. }
  4185. export interface ExternalLinkUpdate {
  4186. name?: string;
  4187. url?: string;
  4188. icon?: string;
  4189. open_in_new_tab?: boolean;
  4190. }
  4191. // Finance types
  4192. export interface CostCenterSummary {
  4193. id: number;
  4194. name: string;
  4195. is_private: boolean;
  4196. owner_user_id: number | null;
  4197. is_active: boolean;
  4198. total_balance: number;
  4199. total_budget: number | null;
  4200. monthly_budget: number | null;
  4201. budget_mode: 'none' | 'total' | 'monthly';
  4202. budget_limit: number | null;
  4203. budget_used: number | null;
  4204. budget_available: number | null;
  4205. can_print: boolean;
  4206. }
  4207. export interface CostCenterCreateRequest {
  4208. name: string;
  4209. total_budget?: number | null;
  4210. monthly_budget?: number | null;
  4211. is_active?: boolean;
  4212. }
  4213. export interface CostCenterBudgetUpdateRequest {
  4214. total_budget?: number | null;
  4215. monthly_budget?: number | null;
  4216. }
  4217. export interface CostCenterUpdateRequest {
  4218. name?: string;
  4219. is_active?: boolean;
  4220. }
  4221. export interface CostCenterMemberRequest {
  4222. user_id: number;
  4223. can_print?: boolean;
  4224. }
  4225. export interface CostCenterMemberResponse {
  4226. id: number;
  4227. cost_center_id: number;
  4228. user_id: number;
  4229. can_print: boolean;
  4230. created_at: string;
  4231. }
  4232. export interface CostCenterDetail extends CostCenterSummary {
  4233. members: CostCenterMemberResponse[];
  4234. }
  4235. export interface WalletBalance {
  4236. user_id: number;
  4237. balance: number;
  4238. currency: string;
  4239. updated_at: string | null;
  4240. }
  4241. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4242. export interface WalletTransaction {
  4243. id: number;
  4244. user_id: number | null; // null once the user is deleted
  4245. cost_center_id: number | null;
  4246. transaction_type: WalletTransactionType;
  4247. amount: number;
  4248. balance_after: number | null;
  4249. description: string | null;
  4250. created_by_user_id: number | null;
  4251. print_run_id: string | null;
  4252. print_archive_id: number | null;
  4253. print_queue_id: number | null;
  4254. created_at: string;
  4255. }
  4256. export interface WalletTransactionListResponse {
  4257. items: WalletTransaction[];
  4258. total: number;
  4259. limit: number;
  4260. offset: number;
  4261. }
  4262. export interface WalletAdjustmentRequest {
  4263. amount: number;
  4264. description?: string;
  4265. cost_center_id?: number | null;
  4266. }
  4267. export interface WalletAdjustmentResponse {
  4268. transaction: WalletTransaction;
  4269. balance: WalletBalance;
  4270. }
  4271. export interface TransactionEditRequest {
  4272. user_id?: number | null;
  4273. cost_center_id?: number | null;
  4274. amount?: number | null;
  4275. description?: string | null;
  4276. }
  4277. export interface ManualPrintRequest {
  4278. user_id: number;
  4279. cost_center_id: number;
  4280. amount: number;
  4281. description?: string | null;
  4282. created_at?: string | null;
  4283. }
  4284. // Permission type - all available permissions
  4285. export type Permission =
  4286. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4287. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4288. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4289. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4290. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4291. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4292. | 'queue:reorder' | 'queue:start_unreviewed'
  4293. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4294. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4295. | 'library:purge'
  4296. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4297. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4298. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4299. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4300. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4301. | 'camera:view'
  4302. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4303. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4304. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4305. | 'notification_templates:read' | 'notification_templates:update'
  4306. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4307. | 'discovery:scan'
  4308. | 'firmware:read' | 'firmware:update'
  4309. | 'ams_history:read'
  4310. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4311. | 'stats:read' | 'stats:filter_by_user'
  4312. | 'system:read'
  4313. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4314. | 'github:backup' | 'github:restore'
  4315. | 'cloud:auth' | 'orca_cloud:auth'
  4316. | 'makerworld:view' | 'makerworld:import'
  4317. | 'manyfold:view' | 'manyfold:import'
  4318. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4319. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4320. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4321. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4322. | 'websocket:connect';
  4323. // Group types
  4324. export interface GroupBrief {
  4325. id: number;
  4326. name: string;
  4327. }
  4328. export interface Group {
  4329. id: number;
  4330. name: string;
  4331. description: string | null;
  4332. permissions: Permission[];
  4333. is_system: boolean;
  4334. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4335. restrict_printers: boolean;
  4336. printer_ids: number[];
  4337. /** Matched against Printer.location, so printers added there later are included */
  4338. locations: string[];
  4339. user_count: number;
  4340. created_at: string;
  4341. updated_at: string;
  4342. }
  4343. export interface GroupDetail extends Group {
  4344. users: Array<{ id: number; username: string; is_active: boolean }>;
  4345. }
  4346. export interface GroupCreate {
  4347. name: string;
  4348. description?: string;
  4349. permissions: Permission[];
  4350. restrict_printers?: boolean;
  4351. printer_ids?: number[];
  4352. locations?: string[];
  4353. }
  4354. export interface GroupUpdate {
  4355. name?: string;
  4356. description?: string;
  4357. permissions?: Permission[];
  4358. restrict_printers?: boolean;
  4359. printer_ids?: number[];
  4360. locations?: string[];
  4361. }
  4362. export interface PermissionInfo {
  4363. value: Permission;
  4364. label: string;
  4365. }
  4366. export interface PermissionCategory {
  4367. name: string;
  4368. permissions: PermissionInfo[];
  4369. }
  4370. export interface PermissionsListResponse {
  4371. categories: PermissionCategory[];
  4372. all_permissions: Permission[];
  4373. }
  4374. // User email notification preferences
  4375. export interface UserEmailPreferences {
  4376. notify_print_start: boolean;
  4377. notify_print_complete: boolean;
  4378. notify_print_failed: boolean;
  4379. notify_print_stopped: boolean;
  4380. }
  4381. // Auth types
  4382. export interface LoginRequest {
  4383. username: string;
  4384. password: string;
  4385. }
  4386. export interface LoginResponse {
  4387. access_token?: string;
  4388. token_type?: string;
  4389. user?: UserResponse;
  4390. /** Set when 2FA verification is required before a full token is issued. */
  4391. requires_2fa?: boolean;
  4392. pre_auth_token?: string;
  4393. two_fa_methods?: string[];
  4394. }
  4395. export interface UserResponse {
  4396. id: number;
  4397. username: string;
  4398. email?: string;
  4399. role: string; // Deprecated, kept for backward compatibility
  4400. is_active: boolean;
  4401. is_admin: boolean; // Computed from role and group membership
  4402. auth_source: string; // "local" or "ldap"
  4403. groups: GroupBrief[];
  4404. permissions: Permission[]; // All permissions from groups
  4405. created_at: string;
  4406. }
  4407. /**
  4408. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4409. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4410. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4411. * name, so operators are not forced into the full listing to get one.
  4412. */
  4413. export interface UserSlim {
  4414. id: number;
  4415. username: string;
  4416. }
  4417. export interface UserCreate {
  4418. username: string;
  4419. password?: string; // Optional when advanced auth is enabled
  4420. email?: string;
  4421. role: string;
  4422. group_ids?: number[];
  4423. }
  4424. export interface UserUpdate {
  4425. username?: string;
  4426. password?: string;
  4427. email?: string;
  4428. role?: string;
  4429. is_active?: boolean;
  4430. group_ids?: number[];
  4431. }
  4432. export interface SetupRequest {
  4433. auth_enabled: boolean;
  4434. admin_username?: string;
  4435. admin_password?: string;
  4436. }
  4437. export interface ForgotPasswordRequest {
  4438. email: string;
  4439. }
  4440. export interface ForgotPasswordResponse {
  4441. message: string;
  4442. }
  4443. export interface ResetPasswordRequest {
  4444. user_id: number;
  4445. }
  4446. export interface ResetPasswordResponse {
  4447. message: string;
  4448. }
  4449. export interface SMTPSettings {
  4450. smtp_host: string;
  4451. smtp_port: number;
  4452. smtp_username?: string;
  4453. smtp_password?: string;
  4454. smtp_security: 'starttls' | 'ssl' | 'none';
  4455. smtp_auth_enabled: boolean;
  4456. smtp_from_email: string;
  4457. smtp_from_name: string;
  4458. }
  4459. // 2FA / MFA interfaces
  4460. export interface TwoFAStatus {
  4461. totp_enabled: boolean;
  4462. email_otp_enabled: boolean;
  4463. backup_codes_remaining: number;
  4464. }
  4465. export interface TOTPSetupResponse {
  4466. secret: string;
  4467. qr_code_b64: string;
  4468. issuer: string;
  4469. }
  4470. export interface TOTPEnableResponse {
  4471. message: string;
  4472. backup_codes: string[];
  4473. }
  4474. export interface BackupCodesResponse {
  4475. backup_codes: string[];
  4476. message: string;
  4477. }
  4478. export interface TwoFAVerifyRequest {
  4479. pre_auth_token: string;
  4480. code: string;
  4481. method: 'totp' | 'email' | 'backup';
  4482. }
  4483. /**
  4484. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4485. *
  4486. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4487. * can be distinguished from arbitrary strings at the type level. The brand
  4488. * is compile-time only; at runtime these are plain strings.
  4489. *
  4490. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4491. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4492. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4493. * that no external URL slips through.
  4494. */
  4495. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4496. // OIDC interfaces
  4497. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4498. * what the login page renders. The full provider, group sync config
  4499. * included, needs the admin-only /auth/oidc/providers/all. */
  4500. export interface OIDCProviderPublic {
  4501. id: number;
  4502. name: string;
  4503. has_icon: boolean;
  4504. is_autologin: boolean;
  4505. }
  4506. export interface OIDCProvider {
  4507. id: number;
  4508. name: string;
  4509. issuer_url: string;
  4510. client_id: string;
  4511. scopes: string;
  4512. is_enabled: boolean;
  4513. auto_create_users: boolean;
  4514. auto_link_existing_accounts: boolean;
  4515. email_claim: string;
  4516. require_email_verified: boolean;
  4517. // #3107 — group sync. Empty mapping = sync off (default).
  4518. group_claim?: string;
  4519. group_mapping?: Record<string, string>;
  4520. icon_url?: string | null;
  4521. default_group_id?: number | null;
  4522. // True when the backend has cached icon bytes for this provider.
  4523. // Login page / admin preview consume this via the proxy URL
  4524. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4525. // hotlinks the external icon URL — that would require loosening
  4526. // the strict img-src CSP. Required, not optional: the backend always
  4527. // includes this field in the response (Pydantic default-False is
  4528. // populated unconditionally in the route handler).
  4529. has_icon: boolean;
  4530. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4531. // straight to this provider on mount. At most one provider may carry this.
  4532. is_autologin: boolean;
  4533. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4534. // every boot. The API answers 409 to any write, so the settings UI must not
  4535. // offer edit/delete controls that cannot succeed. Optional so a response
  4536. // from an older backend still type-checks.
  4537. is_env_managed?: boolean;
  4538. }
  4539. export interface OIDCProviderCreate {
  4540. name: string;
  4541. issuer_url: string;
  4542. client_id: string;
  4543. client_secret: string;
  4544. scopes?: string;
  4545. is_enabled?: boolean;
  4546. auto_create_users?: boolean;
  4547. auto_link_existing_accounts?: boolean;
  4548. email_claim?: string;
  4549. require_email_verified?: boolean;
  4550. // #3107 — group sync. Omit both to leave them unchanged on update.
  4551. group_claim?: string;
  4552. group_mapping?: Record<string, string>;
  4553. icon_url?: string | null;
  4554. default_group_id?: number | null;
  4555. is_autologin?: boolean; // #1589
  4556. }
  4557. export interface OIDCLink {
  4558. id: number;
  4559. provider_id: number;
  4560. provider_name: string;
  4561. provider_email?: string | null;
  4562. created_at: string;
  4563. }
  4564. export interface TestSMTPRequest {
  4565. test_recipient: string;
  4566. // The form's settings, tested before they are saved. An empty password
  4567. // keeps the saved one.
  4568. smtp?: SMTPSettings;
  4569. }
  4570. export interface TestSMTPResponse {
  4571. success: boolean;
  4572. message: string;
  4573. }
  4574. export interface AdvancedAuthStatus {
  4575. advanced_auth_enabled: boolean;
  4576. smtp_configured: boolean;
  4577. // #1589: false hides the username/password form on the LoginPage; the env
  4578. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4579. // the recovery path remains visible.
  4580. local_login_enabled: boolean;
  4581. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4582. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4583. autologin_provider_id: number | null;
  4584. }
  4585. export interface LDAPStatus {
  4586. ldap_enabled: boolean;
  4587. ldap_configured: boolean;
  4588. }
  4589. export interface EncryptionRowCounts {
  4590. oidc_providers: number;
  4591. user_totp: number;
  4592. }
  4593. export interface EncryptionStatus {
  4594. key_configured: boolean;
  4595. key_source: 'env' | 'file' | 'generated' | 'none';
  4596. legacy_plaintext_rows: EncryptionRowCounts;
  4597. encrypted_rows: EncryptionRowCounts;
  4598. decryption_broken: boolean;
  4599. // B2: count of rows skipped during the last legacy re-encryption migration.
  4600. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4601. migration_error_count: number;
  4602. }
  4603. export interface LDAPTestRequest {
  4604. ldap_server_url?: string;
  4605. ldap_bind_dn?: string;
  4606. ldap_bind_password?: string;
  4607. ldap_search_base?: string;
  4608. ldap_user_filter?: string;
  4609. ldap_security?: string;
  4610. }
  4611. export interface LDAPTestResponse {
  4612. success: boolean;
  4613. message: string;
  4614. }
  4615. export interface LDAPSearchResult {
  4616. username: string;
  4617. email: string | null;
  4618. display_name: string | null;
  4619. dn: string;
  4620. already_provisioned: boolean;
  4621. }
  4622. export interface SetupResponse {
  4623. auth_enabled: boolean;
  4624. admin_created?: boolean;
  4625. }
  4626. export interface AuthStatus {
  4627. auth_enabled: boolean;
  4628. requires_setup: boolean;
  4629. }
  4630. // API functions
  4631. export interface QueueHistoryFilters {
  4632. printerId?: number | null;
  4633. status?: string;
  4634. location?: string;
  4635. }
  4636. export interface QueueHistoryParams extends QueueHistoryFilters {
  4637. sortBy?: 'date' | 'name' | 'printer';
  4638. // Flips the default order: newest first by date, A to Z by name or printer.
  4639. reverse?: boolean;
  4640. limit?: number;
  4641. offset?: number;
  4642. }
  4643. export interface QueueHistoryPage {
  4644. // The page in display order, then any other runs of the batches on it.
  4645. items: PrintQueueItem[];
  4646. total: number;
  4647. locations: string[];
  4648. }
  4649. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4650. const search = new URLSearchParams();
  4651. if (params.printerId) search.set('printer_id', String(params.printerId));
  4652. if (params.status) search.set('status', params.status);
  4653. if (params.location) search.set('location', params.location);
  4654. if (params.sortBy) search.set('sort_by', params.sortBy);
  4655. if (params.reverse) search.set('reverse', 'true');
  4656. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4657. if (params.offset) search.set('offset', String(params.offset));
  4658. return search;
  4659. }
  4660. // Per-printer reads that a page showing every printer makes once per printer,
  4661. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4662. // keeps its single-printer request for a lone id.
  4663. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4664. const printerStatusBatch = batched(
  4665. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4666. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4667. );
  4668. const slotPresetsBatch = batched(
  4669. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4670. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4671. );
  4672. const amsLabelsBatch = batched(
  4673. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4674. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4675. );
  4676. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4677. const cardPlugs = async (ids: number[]) =>
  4678. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4679. const smartPlugBatch = batched(
  4680. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4681. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4682. );
  4683. const scriptPlugsBatch = batched(
  4684. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4685. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4686. );
  4687. const haSensorReadingsBatch = batched(
  4688. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4689. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4690. );
  4691. const firmwareUpdateBatch = batched(
  4692. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4693. async (ids) =>
  4694. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4695. );
  4696. // One batcher per status asked for: the bulk route takes a single status list.
  4697. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4698. const printerQueueBatch = (status: string) => {
  4699. let batch = printerQueueBatches.get(status);
  4700. if (!batch) {
  4701. batch = batched(
  4702. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4703. async (ids) =>
  4704. byId(
  4705. await request<Record<string, PrintQueueItem[]>>(
  4706. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4707. ),
  4708. ),
  4709. );
  4710. printerQueueBatches.set(status, batch);
  4711. }
  4712. return batch;
  4713. };
  4714. const foldersByArchiveBatch = batched(
  4715. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4716. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4717. );
  4718. export const api = {
  4719. // Overlay branding
  4720. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4721. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4722. const response = await fetch(`${API_BASE}${endpoint}`, {
  4723. signal, cache: 'no-store',
  4724. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4725. });
  4726. if (response.status === 404) return null;
  4727. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4728. return response.blob();
  4729. },
  4730. uploadOverlayLogo: async (file: File): Promise<void> => {
  4731. const body = new FormData();
  4732. body.append('file', file);
  4733. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4734. method: 'POST', body,
  4735. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4736. });
  4737. if (!response.ok) {
  4738. const error = await response.json().catch(() => ({}));
  4739. const detail = error?.detail;
  4740. const message = typeof detail === 'string' ? detail : detail?.message;
  4741. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4742. }
  4743. },
  4744. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4745. // Authentication
  4746. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4747. setupAuth: (data: SetupRequest) =>
  4748. request<SetupResponse>('/auth/setup', {
  4749. method: 'POST',
  4750. body: JSON.stringify(data),
  4751. }),
  4752. login: (data: LoginRequest) =>
  4753. request<LoginResponse>('/auth/login', {
  4754. method: 'POST',
  4755. body: JSON.stringify(data),
  4756. }),
  4757. logout: () =>
  4758. request<{ message: string }>('/auth/logout', {
  4759. method: 'POST',
  4760. }),
  4761. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4762. disableAuth: () =>
  4763. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4764. method: 'POST',
  4765. }),
  4766. // Advanced Authentication
  4767. testSMTP: (data: TestSMTPRequest) =>
  4768. request<TestSMTPResponse>('/auth/smtp/test', {
  4769. method: 'POST',
  4770. body: JSON.stringify(data),
  4771. }),
  4772. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4773. saveSMTPSettings: (data: SMTPSettings) =>
  4774. request<{ message: string }>('/auth/smtp', {
  4775. method: 'POST',
  4776. body: JSON.stringify(data),
  4777. }),
  4778. enableAdvancedAuth: () =>
  4779. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4780. method: 'POST',
  4781. }),
  4782. disableAdvancedAuth: () =>
  4783. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4784. method: 'POST',
  4785. }),
  4786. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4787. // LDAP Authentication
  4788. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4789. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4790. // form: the settings being edited, tested before they are saved. An empty
  4791. // bind password keeps the saved one.
  4792. testLDAP: (form?: LDAPTestRequest) =>
  4793. request<LDAPTestResponse>('/auth/ldap/test', {
  4794. method: 'POST',
  4795. ...(form ? { body: JSON.stringify(form) } : {}),
  4796. }),
  4797. searchLDAPDirectory: (q: string) =>
  4798. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4799. provisionLDAPUser: (username: string) =>
  4800. request<UserResponse>('/auth/ldap/provision', {
  4801. method: 'POST',
  4802. body: JSON.stringify({ username }),
  4803. }),
  4804. forgotPassword: (data: ForgotPasswordRequest) =>
  4805. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4806. method: 'POST',
  4807. body: JSON.stringify(data),
  4808. }),
  4809. // H-6: Confirm password reset using the token from the emailed link
  4810. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4811. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4812. method: 'POST',
  4813. body: JSON.stringify({ token, new_password: newPassword }),
  4814. }),
  4815. resetUserPassword: (data: ResetPasswordRequest) =>
  4816. request<ResetPasswordResponse>('/auth/reset-password', {
  4817. method: 'POST',
  4818. body: JSON.stringify(data),
  4819. }),
  4820. // 2FA - status
  4821. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4822. // 2FA - TOTP
  4823. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4824. enableTOTP: (code: string) =>
  4825. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4826. method: 'POST',
  4827. body: JSON.stringify({ code }),
  4828. }),
  4829. disableTOTP: (code: string) =>
  4830. request<{ message: string }>('/auth/2fa/totp/disable', {
  4831. method: 'POST',
  4832. body: JSON.stringify({ code }),
  4833. }),
  4834. regenerateBackupCodes: (code: string) =>
  4835. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4836. method: 'POST',
  4837. body: JSON.stringify({ code }),
  4838. }),
  4839. // 2FA - Email OTP
  4840. // Step 1: send a verification code to the user's email (proof of possession)
  4841. enableEmailOTP: () =>
  4842. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4843. // Step 2: confirm with the code received by email
  4844. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4845. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4846. method: 'POST',
  4847. body: JSON.stringify({ setup_token, code }),
  4848. }),
  4849. // Disable requires account password for re-auth
  4850. disableEmailOTP: (password: string) =>
  4851. request<{ message: string }>('/auth/2fa/email/disable', {
  4852. method: 'POST',
  4853. body: JSON.stringify({ password }),
  4854. }),
  4855. sendEmailOTP: (preAuthToken: string) =>
  4856. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4857. method: 'POST',
  4858. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4859. }),
  4860. // 2FA - verify (completes login)
  4861. verify2FA: (data: TwoFAVerifyRequest) =>
  4862. request<LoginResponse>('/auth/2fa/verify', {
  4863. method: 'POST',
  4864. body: JSON.stringify(data),
  4865. }),
  4866. // 2FA - admin
  4867. // adminPassword: the calling admin's own password; null for an admin
  4868. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4869. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4870. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4871. method: 'DELETE',
  4872. body: JSON.stringify({ admin_password: adminPassword }),
  4873. }),
  4874. // OIDC providers (public list)
  4875. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4876. // OIDC providers (admin)
  4877. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4878. createOIDCProvider: (data: OIDCProviderCreate) =>
  4879. request<OIDCProvider>('/auth/oidc/providers', {
  4880. method: 'POST',
  4881. body: JSON.stringify(data),
  4882. }),
  4883. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4884. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4885. method: 'PUT',
  4886. body: JSON.stringify(data),
  4887. }),
  4888. deleteOIDCProvider: (id: number) =>
  4889. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4890. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4891. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4892. // so a future caller can't accidentally substitute an attacker-
  4893. // controlled URL where this is consumed.
  4894. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4895. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4896. deleteOIDCProviderIcon: (id: number) =>
  4897. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  4898. refreshOIDCProviderIcon: (id: number) =>
  4899. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  4900. // OIDC authorize URL
  4901. getOIDCAuthorizeUrl: (providerId: number) =>
  4902. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  4903. // OIDC exchange token for JWT
  4904. exchangeOIDCToken: (oidcToken: string) =>
  4905. request<LoginResponse>('/auth/oidc/exchange', {
  4906. method: 'POST',
  4907. body: JSON.stringify({ oidc_token: oidcToken }),
  4908. }),
  4909. // OIDC links for current user
  4910. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  4911. deleteOIDCLink: (providerId: number) =>
  4912. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  4913. // Users
  4914. getUsers: () => request<UserResponse[]>('/users/'),
  4915. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  4916. createUser: (data: UserCreate) =>
  4917. request<UserResponse>('/users/', {
  4918. method: 'POST',
  4919. body: JSON.stringify(data),
  4920. }),
  4921. updateUser: (id: number, data: UserUpdate) =>
  4922. request<UserResponse>(`/users/${id}`, {
  4923. method: 'PATCH',
  4924. body: JSON.stringify(data),
  4925. }),
  4926. deleteUser: (id: number, deleteItems: boolean = false) =>
  4927. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  4928. method: 'DELETE',
  4929. }),
  4930. getUserItemsCount: (id: number) =>
  4931. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  4932. changePassword: (currentPassword: string, newPassword: string) =>
  4933. request<{ message: string }>('/users/me/change-password', {
  4934. method: 'POST',
  4935. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  4936. }),
  4937. // User Email Notifications
  4938. getUserEmailPreferences: () =>
  4939. request<UserEmailPreferences>('/user-notifications/preferences'),
  4940. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  4941. request<UserEmailPreferences>('/user-notifications/preferences', {
  4942. method: 'PUT',
  4943. body: JSON.stringify(data),
  4944. }),
  4945. // Groups
  4946. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  4947. getGroups: () => request<Group[]>('/groups/'),
  4948. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  4949. createGroup: (data: GroupCreate) =>
  4950. request<Group>('/groups/', {
  4951. method: 'POST',
  4952. body: JSON.stringify(data),
  4953. }),
  4954. updateGroup: (id: number, data: GroupUpdate) =>
  4955. request<Group>(`/groups/${id}`, {
  4956. method: 'PATCH',
  4957. body: JSON.stringify(data),
  4958. }),
  4959. deleteGroup: (id: number) =>
  4960. request<void>(`/groups/${id}`, {
  4961. method: 'DELETE',
  4962. }),
  4963. // Printers
  4964. getPrinters: () => request<Printer[]>('/printers/'),
  4965. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  4966. createPrinter: (data: PrinterCreate) =>
  4967. request<Printer>('/printers/', {
  4968. method: 'POST',
  4969. body: JSON.stringify(data),
  4970. }),
  4971. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  4972. request<Printer>(`/printers/${id}`, {
  4973. method: 'PATCH',
  4974. body: JSON.stringify(data),
  4975. }),
  4976. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  4977. request<{ status: string; archives_deleted: boolean }>(
  4978. `/printers/${id}?delete_archives=${deleteArchives}`,
  4979. { method: 'DELETE' }
  4980. ),
  4981. getDeveloperModeWarnings: () =>
  4982. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  4983. getAvailableFilaments: (model: string, location?: string) => {
  4984. const params = new URLSearchParams({ model });
  4985. if (location) params.set('location', location);
  4986. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  4987. },
  4988. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  4989. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  4990. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  4991. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  4992. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  4993. deletePrinterLocations: (names: string[]) =>
  4994. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  4995. method: 'POST',
  4996. body: JSON.stringify({ names }),
  4997. }),
  4998. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  4999. request<{ moved: number }>('/printer-locations/assign', {
  5000. method: 'POST',
  5001. body: JSON.stringify({ printer_ids: printerIds, location }),
  5002. }),
  5003. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5004. refreshPrinterStatus: (id: number) =>
  5005. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5006. method: 'POST',
  5007. }),
  5008. connectPrinter: (id: number) =>
  5009. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5010. method: 'POST',
  5011. }),
  5012. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5013. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5014. // `coalesced` is true when the frame came from a capture that was already
  5015. // running (Obico polling, a snapshot) rather than a connection this test
  5016. // opened — a single-reader camera is shared rather than opened twice, so
  5017. // the result is real but says nothing about reaching the camera just now.
  5018. // `live_view` is true when the tested camera is the one a viewer is
  5019. // watching: the answer comes from the live frame, not a test of its own.
  5020. // In the body: the URL may carry the camera login, and a query string
  5021. // ends up in the server's access log.
  5022. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5023. `/printers/${printerId}/camera/external/test`,
  5024. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5025. ),
  5026. // Print Control
  5027. stopPrint: (printerId: number) =>
  5028. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5029. method: 'POST',
  5030. }),
  5031. pausePrint: (printerId: number) =>
  5032. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5033. method: 'POST',
  5034. }),
  5035. resumePrint: (printerId: number) =>
  5036. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5037. method: 'POST',
  5038. }),
  5039. clearPlate: (printerId: number) =>
  5040. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5041. method: 'POST',
  5042. }),
  5043. // Get current print user (for reprint tracking - Issue #206)
  5044. getCurrentPrintUser: (printerId: number) =>
  5045. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5046. // Print Speed Control
  5047. setPrintSpeed: (printerId: number, mode: number) =>
  5048. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5049. method: 'POST',
  5050. }),
  5051. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5052. request<{ success: boolean; message: string }>(
  5053. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5054. { method: 'POST' }
  5055. ),
  5056. setBedTemperature: (printerId: number, target: number) =>
  5057. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5058. method: 'POST',
  5059. }),
  5060. setChamberTemperature: (printerId: number, target: number) =>
  5061. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5062. method: 'POST',
  5063. }),
  5064. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5065. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5066. method: 'POST',
  5067. }),
  5068. selectExtruder: (printerId: number, extruder: number) =>
  5069. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5070. method: 'POST',
  5071. }),
  5072. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5073. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5074. method: 'POST',
  5075. }),
  5076. // Bed (Z-axis) jog
  5077. bedJog: (printerId: number, distance: number) =>
  5078. request<{ success: boolean; message: string }>(
  5079. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5080. { method: 'POST' }
  5081. ),
  5082. xyJog: (printerId: number, x: number, y: number) =>
  5083. request<{ success: boolean; message: string }>(
  5084. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5085. { method: 'POST' }
  5086. ),
  5087. extruderJog: (printerId: number, distance: number) =>
  5088. request<{ success: boolean; message: string }>(
  5089. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5090. { method: 'POST' }
  5091. ),
  5092. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5093. request<{ success: boolean; message: string }>(
  5094. `/printers/${printerId}/home-axes?axes=${axes}`,
  5095. { method: 'POST' }
  5096. ),
  5097. // Chamber Light Control
  5098. setChamberLight: (printerId: number, on: boolean) =>
  5099. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5100. method: 'POST',
  5101. }),
  5102. // AMS Drying Control
  5103. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5104. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5105. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5106. { method: 'POST' }
  5107. ),
  5108. stopDrying: (printerId: number, amsId: number) =>
  5109. request<{ status: string; ams_id: number }>(
  5110. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5111. { method: 'POST' }
  5112. ),
  5113. // Scheduled (delayed) drying runs (#2638)
  5114. createScheduledDrying: (data: {
  5115. printer_id: number;
  5116. ams_id: number;
  5117. temp: number;
  5118. duration_hours: number;
  5119. filament?: string;
  5120. rotate_tray?: boolean;
  5121. start_after: string | null;
  5122. }) =>
  5123. request<ScheduledDrying>('/scheduled-dryings', {
  5124. method: 'POST',
  5125. body: JSON.stringify(data),
  5126. }),
  5127. // Omit printerId for the whole fleet in one request; the printer cards share
  5128. // that single query rather than each polling for its own id.
  5129. listScheduledDryings: (printerId?: number) =>
  5130. request<ScheduledDrying[]>(
  5131. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5132. ),
  5133. cancelScheduledDrying: (id: number) =>
  5134. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5135. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5136. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5137. request<{ success: boolean; ams_filament_backup: boolean }>(
  5138. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5139. { method: 'POST' }
  5140. ),
  5141. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5142. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5143. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5144. // so internal and Spoolman modes both work uniformly.
  5145. getInventoryRemain: (printerId: number) =>
  5146. request<InventoryRemainResponse>(
  5147. `/printers/${printerId}/inventory-remain`,
  5148. ),
  5149. // Skip Objects
  5150. getPrintableObjects: (printerId: number) =>
  5151. request<{
  5152. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5153. total: number;
  5154. skipped_count: number;
  5155. is_printing: boolean;
  5156. bbox_all: [number, number, number, number] | null;
  5157. }>(`/printers/${printerId}/print/objects`),
  5158. skipObjects: (printerId: number, objectIds: number[]) =>
  5159. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5160. `/printers/${printerId}/print/skip-objects`,
  5161. {
  5162. method: 'POST',
  5163. body: JSON.stringify(objectIds),
  5164. }
  5165. ),
  5166. // HMS Errors
  5167. clearHMSErrors: (printerId: number) =>
  5168. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5169. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5170. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5171. method: 'POST',
  5172. body: JSON.stringify(data),
  5173. }),
  5174. // AMS Control
  5175. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5176. request<{ success: boolean; message: string }>(
  5177. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5178. { method: 'POST' }
  5179. ),
  5180. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 128-135 for an
  5181. // AMS-HT (its unit id), 254 for external spool.
  5182. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5183. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5184. // inlet rather than a hotend, so the firmware cannot work the target out and
  5185. // drops the command. Omit it everywhere else, as BambuStudio does.
  5186. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5187. request<{ success: boolean; message: string }>(
  5188. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5189. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5190. { method: 'POST' }
  5191. ),
  5192. // Unload filament. trayId names the slot to unload, which is what tells a
  5193. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5194. // whatever the printer's single tray_now field names.
  5195. unloadAms: (printerId: number, trayId?: number) =>
  5196. request<{ success: boolean; message: string }>(
  5197. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5198. { method: 'POST' }
  5199. ),
  5200. // MQTT Debug Logging
  5201. enableMQTTLogging: (printerId: number) =>
  5202. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5203. method: 'POST',
  5204. }),
  5205. disableMQTTLogging: (printerId: number) =>
  5206. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5207. method: 'POST',
  5208. }),
  5209. getMQTTLogs: (printerId: number) =>
  5210. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5211. clearMQTTLogs: (printerId: number) =>
  5212. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5213. method: 'DELETE',
  5214. }),
  5215. // Printer File Manager
  5216. getPrinterFiles: (printerId: number, path = '/') =>
  5217. request<{
  5218. path: string;
  5219. files: Array<{
  5220. name: string;
  5221. is_directory: boolean;
  5222. size: number;
  5223. path: string;
  5224. mtime?: string;
  5225. }>;
  5226. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5227. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5228. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5229. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5230. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5231. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5232. getPrinterFilePlates: (printerId: number, path: string) =>
  5233. request<{
  5234. printer_id: number;
  5235. path: string;
  5236. filename: string;
  5237. plates: Array<{
  5238. index: number;
  5239. name: string | null;
  5240. objects: string[];
  5241. has_thumbnail: boolean;
  5242. thumbnail_url: string | null;
  5243. print_time_seconds: number | null;
  5244. filament_used_grams: number | null;
  5245. filaments: Array<{
  5246. slot_id: number;
  5247. type: string;
  5248. color: string;
  5249. used_grams: number;
  5250. used_meters: number;
  5251. }>;
  5252. }>;
  5253. is_multi_plate: boolean;
  5254. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5255. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5256. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5257. downloadPrinterFilesAsZip: async (
  5258. printerId: number,
  5259. paths: string[],
  5260. sizes: Record<string, number>,
  5261. filename = 'printer-files.zip',
  5262. asZip = true,
  5263. signal?: AbortSignal,
  5264. onProgress?: (completed: number, total: number) => void,
  5265. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5266. type JobStatus = {
  5267. job_id: string;
  5268. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5269. requested: number;
  5270. successful: number;
  5271. failed: number;
  5272. token: string | null;
  5273. message: string | null;
  5274. };
  5275. let jobId: string | null = null;
  5276. try {
  5277. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5278. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5279. method: 'POST',
  5280. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5281. signal,
  5282. });
  5283. jobId = status.job_id;
  5284. let polls = 0;
  5285. while (status.state === 'queued' || status.state === 'preparing') {
  5286. onProgress?.(status.successful + status.failed, status.requested);
  5287. // Small selections finish in the first seconds, so poll quickly there.
  5288. // A large one runs for up to half an hour, where half-second polling is
  5289. // thousands of requests that each re-check the caller's credentials.
  5290. const delay = polls < 10 ? 500 : 2000;
  5291. polls += 1;
  5292. await new Promise<void>((resolve, reject) => {
  5293. if (signal?.aborted) {
  5294. reject(new DOMException('Download cancelled', 'AbortError'));
  5295. return;
  5296. }
  5297. const onAbort = () => {
  5298. window.clearTimeout(timer);
  5299. reject(new DOMException('Download cancelled', 'AbortError'));
  5300. };
  5301. const timer = window.setTimeout(() => {
  5302. signal?.removeEventListener('abort', onAbort);
  5303. resolve();
  5304. }, delay);
  5305. signal?.addEventListener('abort', onAbort, { once: true });
  5306. });
  5307. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5308. }
  5309. onProgress?.(status.successful + status.failed, status.requested);
  5310. if (status.state !== 'ready' || !status.token) {
  5311. throw new Error(status.message || (status.state === 'cancelled'
  5312. ? 'Download cancelled'
  5313. : 'Printer download preparation failed'));
  5314. }
  5315. const link = document.createElement('a');
  5316. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5317. link.download = filename;
  5318. document.body.appendChild(link);
  5319. link.click();
  5320. link.remove();
  5321. return {
  5322. requested: status.requested,
  5323. successful: status.successful,
  5324. failed: status.failed,
  5325. };
  5326. } catch (error) {
  5327. if (jobId) {
  5328. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5329. }
  5330. throw error;
  5331. }
  5332. },
  5333. deletePrinterFile: (printerId: number, path: string) =>
  5334. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5335. method: 'DELETE',
  5336. }),
  5337. getPrinterStorage: (printerId: number) =>
  5338. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5339. // Archives
  5340. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5341. const params = new URLSearchParams();
  5342. if (printerId) params.set('printer_id', String(printerId));
  5343. if (projectId) params.set('project_id', String(projectId));
  5344. params.set('limit', String(limit));
  5345. params.set('offset', String(offset));
  5346. if (dateFrom) params.set('date_from', dateFrom);
  5347. if (dateTo) params.set('date_to', dateTo);
  5348. addDayZone(params);
  5349. return request<Archive[]>(`/archives/?${params}`);
  5350. },
  5351. // Latest archive of every printer in one request, for the printer cards.
  5352. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5353. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5354. const params = new URLSearchParams();
  5355. if (dateFrom) params.set('date_from', dateFrom);
  5356. if (dateTo) params.set('date_to', dateTo);
  5357. addDayZone(params);
  5358. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5359. const qs = params.toString();
  5360. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5361. },
  5362. getArchive: (id: number, runId?: number | null) =>
  5363. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5364. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5365. // The prints of the archives the caller sees that ended between two days
  5366. // (archive redesign P4: the calendar), in id order.
  5367. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5368. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5369. if (params.printerId) search.set('printer_id', String(params.printerId));
  5370. if (params.limit) search.set('limit', String(params.limit));
  5371. if (params.offset) search.set('offset', String(params.offset));
  5372. addDayZone(search);
  5373. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5374. },
  5375. /**
  5376. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5377. * related queue items that will be removed along with the archive AND how
  5378. * many are currently printing (server 409s on delete if > 0).
  5379. */
  5380. getArchiveDeleteImpact: (id: number) =>
  5381. request<{ related_queue_items: number; currently_printing: number }>(
  5382. `/archives/${id}/delete-impact`
  5383. ),
  5384. getNo3MFWarning: () =>
  5385. request<{
  5386. has_fallback: boolean;
  5387. reason:
  5388. | 'ftps_cooloff'
  5389. | 'ftp_transfer_failed'
  5390. | 'internal_storage'
  5391. | 'no_external_storage'
  5392. | 'internal_history'
  5393. | null;
  5394. }>(
  5395. '/archives/no-3mf-warning',
  5396. ),
  5397. updateArchive: (id: number, data: {
  5398. printer_id?: number | null;
  5399. project_id?: number | null;
  5400. print_name?: string;
  5401. is_favorite?: boolean;
  5402. tags?: string;
  5403. notes?: string;
  5404. cost?: number;
  5405. failure_reason?: string | null;
  5406. status?: string;
  5407. quantity?: number;
  5408. external_url?: string | null;
  5409. filament_used_grams?: number | null;
  5410. // Post-print outcome verdict (#1898); null clears it
  5411. user_verdict?: 'good' | 'reject' | null;
  5412. // Which surface answered. The backend only accepts the sources a client
  5413. // can honestly claim and defaults to 'api' when none is given.
  5414. user_verdict_source?: 'dialog' | 'printer_card';
  5415. // The run the verdict / outcome is for; omitted means the latest run.
  5416. run_id?: number;
  5417. }) =>
  5418. request<Archive>(`/archives/${id}`, {
  5419. method: 'PATCH',
  5420. body: JSON.stringify(data),
  5421. }),
  5422. toggleFavorite: (id: number) =>
  5423. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5424. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5425. // from listings, but its filament / time / cost / energy contribution
  5426. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5427. // row from statistics too.
  5428. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5429. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5430. // ========== Archive auto-purge (#1008 follow-up) ==========
  5431. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5432. request<ArchivePurgePreview>(
  5433. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5434. ),
  5435. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5436. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5437. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5438. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5439. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5440. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5441. method: 'POST',
  5442. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5443. }),
  5444. // Archives of one file merge into the oldest (archive redesign P2).
  5445. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5446. /** How many duplicate groups there are; cheap, for offering the merge. */
  5447. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5448. mergeArchives: (survivorIds: number[]) =>
  5449. request<ArchiveMergeResult>('/archives/merge', {
  5450. method: 'POST',
  5451. body: JSON.stringify({ survivor_ids: survivorIds }),
  5452. }),
  5453. getArchivePurgeSettings: () =>
  5454. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5455. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5456. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5457. method: 'PUT',
  5458. body: JSON.stringify(body),
  5459. }),
  5460. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5461. const params = new URLSearchParams();
  5462. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5463. if (options?.dateTo) params.set('date_to', options.dateTo);
  5464. addDayZone(params);
  5465. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5466. const qs = params.toString();
  5467. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5468. },
  5469. // Tag management
  5470. getTags: () => request<TagInfo[]>('/archives/tags'),
  5471. renameTag: (oldName: string, newName: string) =>
  5472. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5473. method: 'PUT',
  5474. body: JSON.stringify({ new_name: newName }),
  5475. }),
  5476. deleteTag: (name: string) =>
  5477. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5478. method: 'DELETE',
  5479. }),
  5480. recalculateCosts: () =>
  5481. request<{
  5482. message: string;
  5483. updated: number;
  5484. preserved: number;
  5485. usage_repriced: number;
  5486. spoolman_unreachable: number;
  5487. }>('/archives/recalculate-costs', { method: 'POST' }),
  5488. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5489. const params = new URLSearchParams();
  5490. if (options?.days) params.set('days', String(options.days));
  5491. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5492. if (options?.dateTo) params.set('date_to', options.dateTo);
  5493. addDayZone(params);
  5494. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5495. if (options?.projectId) params.set('project_id', String(options.projectId));
  5496. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5497. const qs = params.toString();
  5498. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5499. },
  5500. compareArchives: (archiveIds: number[]) =>
  5501. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5502. exportArchives: async (options?: {
  5503. format?: 'csv' | 'xlsx';
  5504. fields?: string[];
  5505. printerId?: number;
  5506. projectId?: number;
  5507. status?: string;
  5508. dateFrom?: string;
  5509. dateTo?: string;
  5510. search?: string;
  5511. }): Promise<{ blob: Blob; filename: string }> => {
  5512. const params = new URLSearchParams();
  5513. if (options?.format) params.set('format', options.format);
  5514. if (options?.fields) params.set('fields', options.fields.join(','));
  5515. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5516. if (options?.projectId) params.set('project_id', String(options.projectId));
  5517. if (options?.status) params.set('status', options.status);
  5518. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5519. if (options?.dateTo) params.set('date_to', options.dateTo);
  5520. addDayZone(params);
  5521. if (options?.search) params.set('search', options.search);
  5522. const headers: Record<string, string> = {};
  5523. if (authToken) {
  5524. headers['Authorization'] = `Bearer ${authToken}`;
  5525. }
  5526. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5527. if (!response.ok) {
  5528. const error = await response.json().catch(() => ({}));
  5529. throw new Error(error.detail || `HTTP ${response.status}`);
  5530. }
  5531. const contentDisposition = response.headers.get('Content-Disposition');
  5532. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5533. if (contentDisposition) {
  5534. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5535. if (match) filename = match[1];
  5536. }
  5537. const blob = await response.blob();
  5538. return { blob, filename };
  5539. },
  5540. exportStats: async (options?: {
  5541. format?: 'csv' | 'xlsx';
  5542. days?: number;
  5543. printerId?: number;
  5544. projectId?: number;
  5545. createdById?: number;
  5546. }): Promise<{ blob: Blob; filename: string }> => {
  5547. const params = new URLSearchParams();
  5548. if (options?.format) params.set('format', options.format);
  5549. if (options?.days) params.set('days', String(options.days));
  5550. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5551. if (options?.projectId) params.set('project_id', String(options.projectId));
  5552. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5553. const headers: Record<string, string> = {};
  5554. if (authToken) {
  5555. headers['Authorization'] = `Bearer ${authToken}`;
  5556. }
  5557. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5558. if (!response.ok) {
  5559. const error = await response.json().catch(() => ({}));
  5560. throw new Error(error.detail || `HTTP ${response.status}`);
  5561. }
  5562. const contentDisposition = response.headers.get('Content-Disposition');
  5563. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5564. if (contentDisposition) {
  5565. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5566. if (match) filename = match[1];
  5567. }
  5568. const blob = await response.blob();
  5569. return { blob, filename };
  5570. },
  5571. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5572. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5573. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5574. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5575. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5576. const headers: Record<string, string> = {};
  5577. if (authToken) {
  5578. headers['Authorization'] = `Bearer ${authToken}`;
  5579. }
  5580. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5581. if (!response.ok) {
  5582. const error = await response.json().catch(() => ({}));
  5583. throw new Error(error.detail || `HTTP ${response.status}`);
  5584. }
  5585. const disposition = response.headers.get('Content-Disposition');
  5586. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5587. const blob = await response.blob();
  5588. const url = window.URL.createObjectURL(blob);
  5589. const a = document.createElement('a');
  5590. a.href = url;
  5591. a.download = downloadFilename;
  5592. document.body.appendChild(a);
  5593. a.click();
  5594. document.body.removeChild(a);
  5595. window.URL.revokeObjectURL(url);
  5596. },
  5597. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5598. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5599. getArchiveRunTimelapse: (id: number, runId: number) =>
  5600. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5601. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5602. const prepared = await request<{ token: string; filename: string }>(
  5603. `/archives/${id}/media-download-token`,
  5604. { method: 'POST' },
  5605. );
  5606. const link = document.createElement('a');
  5607. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5608. link.download = filename;
  5609. document.body.appendChild(link);
  5610. link.click();
  5611. link.remove();
  5612. },
  5613. getArchivePrinterMedia: (id: number) =>
  5614. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5615. scanArchiveTimelapse: (id: number) =>
  5616. request<{
  5617. status: string;
  5618. message: string;
  5619. filename?: string;
  5620. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5621. }>(`/archives/${id}/timelapse/scan`, {
  5622. method: 'POST',
  5623. }),
  5624. selectArchiveTimelapse: (id: number, filename: string) =>
  5625. request<{ status: string; message: string; filename: string }>(
  5626. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5627. { method: 'POST' }
  5628. ),
  5629. deleteArchiveTimelapse: (id: number) =>
  5630. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5631. method: 'DELETE',
  5632. }),
  5633. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5634. const formData = new FormData();
  5635. formData.append('file', file);
  5636. const headers: Record<string, string> = {};
  5637. if (authToken) {
  5638. headers['Authorization'] = `Bearer ${authToken}`;
  5639. }
  5640. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5641. method: 'POST',
  5642. headers,
  5643. body: formData,
  5644. });
  5645. if (!response.ok) {
  5646. const error = await response.json().catch(() => ({}));
  5647. throw new Error(error.detail || `HTTP ${response.status}`);
  5648. }
  5649. return response.json();
  5650. },
  5651. // Timelapse Editor
  5652. getTimelapseInfo: (archiveId: number) =>
  5653. request<{
  5654. duration: number;
  5655. width: number;
  5656. height: number;
  5657. fps: number;
  5658. codec: string;
  5659. file_size: number;
  5660. has_audio: boolean;
  5661. }>(`/archives/${archiveId}/timelapse/info`),
  5662. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5663. request<{
  5664. thumbnails: string[];
  5665. timestamps: number[];
  5666. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5667. processTimelapse: async (
  5668. archiveId: number,
  5669. params: {
  5670. trimStart?: number;
  5671. trimEnd?: number;
  5672. speed?: number;
  5673. /** Music volume, 0 to 1. */
  5674. audioVolume?: number;
  5675. saveMode: 'replace' | 'new';
  5676. outputFilename?: string;
  5677. },
  5678. audioFile?: File
  5679. ): Promise<TimelapseJob> => {
  5680. const formData = new FormData();
  5681. formData.append('trim_start', String(params.trimStart ?? 0));
  5682. if (params.trimEnd !== undefined) {
  5683. formData.append('trim_end', String(params.trimEnd));
  5684. }
  5685. formData.append('speed', String(params.speed ?? 1));
  5686. if (params.audioVolume !== undefined) {
  5687. formData.append('audio_volume', String(params.audioVolume));
  5688. }
  5689. formData.append('save_mode', params.saveMode);
  5690. if (params.outputFilename) {
  5691. formData.append('output_filename', params.outputFilename);
  5692. }
  5693. if (audioFile) {
  5694. formData.append('audio', audioFile);
  5695. }
  5696. const headers: Record<string, string> = {};
  5697. if (authToken) {
  5698. headers['Authorization'] = `Bearer ${authToken}`;
  5699. }
  5700. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5701. method: 'POST',
  5702. headers,
  5703. body: formData,
  5704. });
  5705. if (!response.ok) {
  5706. const error = await response.json().catch(() => ({}));
  5707. throw new Error(error.detail || `HTTP ${response.status}`);
  5708. }
  5709. return response.json();
  5710. },
  5711. // The archive's running or last re-encode; null when there has been none.
  5712. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5713. try {
  5714. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5715. } catch (error) {
  5716. if (error instanceof ApiError && error.status === 404) return null;
  5717. throw error;
  5718. }
  5719. },
  5720. cancelTimelapseJob: (archiveId: number) =>
  5721. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5722. // Photos
  5723. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5724. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5725. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5726. const formData = new FormData();
  5727. formData.append('file', file);
  5728. const headers: Record<string, string> = {};
  5729. if (authToken) {
  5730. headers['Authorization'] = `Bearer ${authToken}`;
  5731. }
  5732. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5733. headers,
  5734. method: 'POST',
  5735. body: formData,
  5736. });
  5737. if (!response.ok) {
  5738. const error = await response.json().catch(() => ({}));
  5739. throw new Error(error.detail || `HTTP ${response.status}`);
  5740. }
  5741. return response.json();
  5742. },
  5743. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5744. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5745. method: 'DELETE',
  5746. }),
  5747. // Source 3MF (original slicer project file)
  5748. getSource3mfDownloadUrl: (archiveId: number) =>
  5749. `${API_BASE}/archives/${archiveId}/source`,
  5750. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5751. const headers: Record<string, string> = {};
  5752. if (authToken) {
  5753. headers['Authorization'] = `Bearer ${authToken}`;
  5754. }
  5755. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5756. if (!response.ok) {
  5757. const error = await response.json().catch(() => ({}));
  5758. throw new Error(error.detail || `HTTP ${response.status}`);
  5759. }
  5760. const disposition = response.headers.get('Content-Disposition');
  5761. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5762. const blob = await response.blob();
  5763. const url = window.URL.createObjectURL(blob);
  5764. const a = document.createElement('a');
  5765. a.href = url;
  5766. a.download = filename;
  5767. document.body.appendChild(a);
  5768. a.click();
  5769. document.body.removeChild(a);
  5770. window.URL.revokeObjectURL(url);
  5771. },
  5772. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5773. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5774. const safe = filename.replace(/[/\\?#]/g, '_');
  5775. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5776. },
  5777. createSourceSlicerToken: (archiveId: number) =>
  5778. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5779. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5780. const safe = filename.replace(/[/\\?#]/g, '_');
  5781. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5782. },
  5783. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5784. const formData = new FormData();
  5785. formData.append('file', file);
  5786. const headers: Record<string, string> = {};
  5787. if (authToken) {
  5788. headers['Authorization'] = `Bearer ${authToken}`;
  5789. }
  5790. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5791. method: 'POST',
  5792. headers,
  5793. body: formData,
  5794. });
  5795. if (!response.ok) {
  5796. const error = await response.json().catch(() => ({}));
  5797. throw new Error(error.detail || `HTTP ${response.status}`);
  5798. }
  5799. return response.json();
  5800. },
  5801. deleteSource3mf: (archiveId: number) =>
  5802. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5803. method: 'DELETE',
  5804. }),
  5805. // F3D (Fusion 360 design file)
  5806. downloadF3d: async (archiveId: number): Promise<void> => {
  5807. const headers: Record<string, string> = {};
  5808. if (authToken) {
  5809. headers['Authorization'] = `Bearer ${authToken}`;
  5810. }
  5811. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5812. if (!response.ok) {
  5813. const error = await response.json().catch(() => ({}));
  5814. throw new Error(error.detail || `HTTP ${response.status}`);
  5815. }
  5816. const disposition = response.headers.get('Content-Disposition');
  5817. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5818. const blob = await response.blob();
  5819. const url = window.URL.createObjectURL(blob);
  5820. const a = document.createElement('a');
  5821. a.href = url;
  5822. a.download = filename;
  5823. document.body.appendChild(a);
  5824. a.click();
  5825. document.body.removeChild(a);
  5826. window.URL.revokeObjectURL(url);
  5827. },
  5828. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5829. const formData = new FormData();
  5830. formData.append('file', file);
  5831. const headers: Record<string, string> = {};
  5832. if (authToken) {
  5833. headers['Authorization'] = `Bearer ${authToken}`;
  5834. }
  5835. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5836. method: 'POST',
  5837. headers,
  5838. body: formData,
  5839. });
  5840. if (!response.ok) {
  5841. const error = await response.json().catch(() => ({}));
  5842. throw new Error(error.detail || `HTTP ${response.status}`);
  5843. }
  5844. return response.json();
  5845. },
  5846. deleteF3d: (archiveId: number) =>
  5847. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5848. method: 'DELETE',
  5849. }),
  5850. // QR Code
  5851. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5852. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5853. getArchiveCapabilities: (id: number) =>
  5854. request<{
  5855. has_model: boolean;
  5856. has_gcode: boolean;
  5857. has_source: boolean;
  5858. build_volume: { x: number; y: number; z: number };
  5859. filament_colors: string[];
  5860. }>(`/archives/${id}/capabilities`),
  5861. // Project Page
  5862. getArchiveProjectPage: (id: number) =>
  5863. request<{
  5864. title: string | null;
  5865. description: string | null;
  5866. designer: string | null;
  5867. designer_user_id: string | null;
  5868. license: string | null;
  5869. copyright: string | null;
  5870. creation_date: string | null;
  5871. modification_date: string | null;
  5872. origin: string | null;
  5873. profile_title: string | null;
  5874. profile_description: string | null;
  5875. profile_cover: string | null;
  5876. profile_user_id: string | null;
  5877. profile_user_name: string | null;
  5878. design_model_id: string | null;
  5879. design_profile_id: string | null;
  5880. design_region: string | null;
  5881. model_pictures: Array<{ name: string; path: string; url: string }>;
  5882. profile_pictures: Array<{ name: string; path: string; url: string }>;
  5883. thumbnails: Array<{ name: string; path: string; url: string }>;
  5884. }>(`/archives/${id}/project-page`),
  5885. updateArchiveProjectPage: (id: number, data: {
  5886. title?: string;
  5887. description?: string;
  5888. designer?: string;
  5889. license?: string;
  5890. copyright?: string;
  5891. profile_title?: string;
  5892. profile_description?: string;
  5893. }) =>
  5894. request(`/archives/${id}/project-page`, {
  5895. method: 'PATCH',
  5896. body: JSON.stringify(data),
  5897. }),
  5898. getArchiveForSlicer: (id: number, filename: string) => {
  5899. const safe = filename.replace(/[/\\?#]/g, '_');
  5900. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5901. },
  5902. createArchiveSlicerToken: (archiveId: number) =>
  5903. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  5904. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5905. const safe = filename.replace(/[/\\?#]/g, '_');
  5906. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5907. },
  5908. getArchivePlates: (archiveId: number) =>
  5909. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  5910. getArchiveFilamentRequirements: (
  5911. archiveId: number,
  5912. plateId?: number,
  5913. requestId?: string,
  5914. /** Ask for one entry per project slot instead of only the slots this
  5915. * plate consumes. The slice modal needs it: its filament list is
  5916. * positional, so a source whose only used slot is 4 must still present
  5917. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  5918. * AMS matching must NOT set this — it wants the used-only list. */
  5919. fullSlots?: boolean,
  5920. ) => {
  5921. const qs = new URLSearchParams();
  5922. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5923. if (requestId) qs.set('request_id', requestId);
  5924. if (fullSlots) qs.set('full_slots', 'true');
  5925. return request<{
  5926. archive_id: number;
  5927. filename: string;
  5928. plate_id: number | null;
  5929. filaments: Array<{
  5930. slot_id: number;
  5931. type: string;
  5932. color: string;
  5933. used_grams: number;
  5934. used_meters: number;
  5935. used_in_plate?: boolean;
  5936. }>;
  5937. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5938. },
  5939. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  5940. const formData = new FormData();
  5941. files.forEach((file) => formData.append('files', file));
  5942. const url = printerId
  5943. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  5944. : `${API_BASE}/archives/upload-bulk`;
  5945. const headers: Record<string, string> = {};
  5946. if (authToken) {
  5947. headers['Authorization'] = `Bearer ${authToken}`;
  5948. }
  5949. const response = await fetch(url, {
  5950. method: 'POST',
  5951. headers,
  5952. body: formData,
  5953. });
  5954. if (!response.ok) {
  5955. const error = await response.json().catch(() => ({}));
  5956. throw new Error(error.detail || `HTTP ${response.status}`);
  5957. }
  5958. return response.json();
  5959. },
  5960. // Print Log
  5961. getPrintLog: (params?: {
  5962. search?: string;
  5963. printerId?: number;
  5964. username?: string;
  5965. status?: string;
  5966. dateFrom?: string;
  5967. dateTo?: string;
  5968. limit?: number;
  5969. offset?: number;
  5970. // Sorting is server-side because paging is: ordering only the rows the
  5971. // client holds would sort one page, not the log (#2636).
  5972. sortBy?: string;
  5973. sortDir?: 'asc' | 'desc';
  5974. }) => {
  5975. const searchParams = new URLSearchParams();
  5976. if (params?.search) searchParams.set('search', params.search);
  5977. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  5978. if (params?.username) searchParams.set('created_by_username', params.username);
  5979. if (params?.status) searchParams.set('status', params.status);
  5980. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  5981. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  5982. if (params?.limit) searchParams.set('limit', String(params.limit));
  5983. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  5984. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  5985. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  5986. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  5987. },
  5988. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  5989. clearPrintLog: () =>
  5990. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  5991. deletePrintLogEntry: (id: number) =>
  5992. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  5993. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  5994. // Distinct from updateArchive: archives describe the model, log entries
  5995. // describe a single print event. Orphan entries (no archive_id) have no
  5996. // archive to reach through and this is the only path to classify them.
  5997. updatePrintLogEntry: (
  5998. id: number,
  5999. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6000. ) =>
  6001. request<PrintLogEntry>(`/print-log/${id}`, {
  6002. method: 'PATCH',
  6003. body: JSON.stringify(body),
  6004. }),
  6005. // Settings
  6006. getSettings: () => request<AppSettings>('/settings/'),
  6007. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6008. // Public subset of settings for UI rendering — no settings:read required.
  6009. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6010. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6011. // backend/app/api/routes/settings.py.
  6012. getUiPreferences: () =>
  6013. request<{
  6014. require_plate_clear?: boolean;
  6015. check_printer_firmware?: boolean;
  6016. camera_view_mode?: 'window' | 'embedded';
  6017. time_format?: 'system' | '12h' | '24h';
  6018. date_format?: string;
  6019. drying_presets?: string;
  6020. ams_humidity_thresholds?: string;
  6021. ams_humidity_good?: number;
  6022. ams_humidity_fair?: number;
  6023. ams_temp_good?: number;
  6024. ams_temp_fair?: number;
  6025. bed_cooled_threshold?: number;
  6026. nozzle_temp_presets?: string;
  6027. bed_temp_presets?: string;
  6028. chamber_temp_presets?: string;
  6029. fan_speed_presets?: string;
  6030. }>('/settings/ui-preferences'),
  6031. // Install configuration the app shell needs, for any signed-in user. Separate
  6032. // from getUiPreferences: that endpoint is public because its fields are
  6033. // defaults shipped with the app, while these describe how this deployment is
  6034. // configured. Neither requires settings:read -- which is the point, since a
  6035. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6036. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6037. // backend/app/api/routes/settings.py.
  6038. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6039. // The two above together: what a page needs from the settings when its user
  6040. // may not read GET /settings. See useUiSettings.
  6041. getUiSettings: async (): Promise<UiSettings> => {
  6042. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6043. return { ...(preferences as UiSettings), ...flags };
  6044. },
  6045. updateSettings: (data: AppSettingsUpdate) =>
  6046. request<AppSettings>('/settings/', {
  6047. method: 'PUT',
  6048. body: JSON.stringify(data),
  6049. }),
  6050. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6051. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6052. // New simplified backup - complete database + all files
  6053. const url = `${API_BASE}/settings/backup`;
  6054. const headers: Record<string, string> = {};
  6055. if (authToken) {
  6056. headers['Authorization'] = `Bearer ${authToken}`;
  6057. }
  6058. const response = await fetch(url, { headers });
  6059. // Check for errors
  6060. if (!response.ok) {
  6061. const errorText = await response.text();
  6062. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6063. }
  6064. // Get filename from Content-Disposition header
  6065. const contentDisposition = response.headers.get('Content-Disposition');
  6066. let filename = 'bambuddy-backup.zip';
  6067. if (contentDisposition) {
  6068. const match = contentDisposition.match(/filename=([^;]+)/);
  6069. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6070. }
  6071. const blob = await response.blob();
  6072. return { blob, filename };
  6073. },
  6074. importBackup: async (file: File) => {
  6075. // New simplified restore - replaces database + all directories
  6076. const formData = new FormData();
  6077. formData.append('file', file);
  6078. const url = `${API_BASE}/settings/restore`;
  6079. const headers: Record<string, string> = {};
  6080. if (authToken) {
  6081. headers['Authorization'] = `Bearer ${authToken}`;
  6082. }
  6083. const response = await fetch(url, {
  6084. method: 'POST',
  6085. headers,
  6086. body: formData,
  6087. });
  6088. const data = (await response.json().catch(() => null)) as {
  6089. success?: boolean;
  6090. message?: string;
  6091. detail?: string;
  6092. } | null;
  6093. // A refused restore is an HTTPException, so the body is {detail}, not
  6094. // {success, message}. Returning it unmapped made `success` undefined and
  6095. // `message` undefined too — the modal then raised an empty error toast,
  6096. // which is the one case where the reason matters most (e.g. a backup this
  6097. // version cannot import names the columns and both versions).
  6098. if (!response.ok) {
  6099. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6100. }
  6101. return (data ?? { success: false, message: '' }) as {
  6102. success: boolean;
  6103. message: string;
  6104. };
  6105. },
  6106. checkFfmpeg: () =>
  6107. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6108. getNetworkInterfaces: () =>
  6109. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6110. // Cloud
  6111. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6112. cloudLogin: (email: string, password: string, region = 'global') =>
  6113. request<CloudLoginResponse>('/cloud/login', {
  6114. method: 'POST',
  6115. body: JSON.stringify({ email, password, region }),
  6116. }),
  6117. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6118. request<CloudLoginResponse>('/cloud/verify', {
  6119. method: 'POST',
  6120. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6121. }),
  6122. cloudSetToken: (access_token: string, region: string = 'global') =>
  6123. request<CloudAuthStatus>('/cloud/token', {
  6124. method: 'POST',
  6125. body: JSON.stringify({ access_token, region }),
  6126. }),
  6127. cloudLogout: () =>
  6128. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6129. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6130. // user_code + verification link; the user approves it in their Orca Cloud
  6131. // settings while the frontend polls devicePoll() every `interval` seconds
  6132. // until the status flips to 'complete' (or a terminal deny/expire).
  6133. orcaCloudDeviceStart: () =>
  6134. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6135. method: 'POST',
  6136. }),
  6137. orcaCloudDevicePoll: () =>
  6138. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6139. method: 'POST',
  6140. }),
  6141. orcaCloudStatus: () =>
  6142. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6143. orcaCloudLogout: () =>
  6144. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6145. orcaCloudListProfiles: () =>
  6146. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6147. orcaCloudGetProfile: (id: string) =>
  6148. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6149. getCloudSettings: (version = '02.04.00.70') =>
  6150. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6151. getBuiltinFilaments: () =>
  6152. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6153. getFilamentIdMap: () =>
  6154. request<Record<string, string>>('/cloud/filament-id-map'),
  6155. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6156. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6157. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6158. * collapses these to the first hit; this endpoint preserves the material
  6159. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6160. * catalog at all. #1718. */
  6161. getColorByMaterial: (hex: string, material?: string) => {
  6162. const params = new URLSearchParams({ hex });
  6163. if (material) params.set('material', material);
  6164. return request<{ color_name: string | null }>(
  6165. `/inventory/colors/by-material?${params.toString()}`,
  6166. );
  6167. },
  6168. // MakerWorld URL-paste import flow.
  6169. getMakerworldStatus: () =>
  6170. request<MakerworldStatus>('/makerworld/status'),
  6171. resolveMakerworldUrl: (url: string) =>
  6172. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6173. method: 'POST',
  6174. body: JSON.stringify({ url }),
  6175. }),
  6176. getMakerworldRecentImports: (limit = 10) =>
  6177. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6178. importMakerworldInstance: (
  6179. model_id: number,
  6180. instance_id: number | null,
  6181. profile_id?: number | null,
  6182. folder_id?: number | null,
  6183. ) =>
  6184. request<MakerworldImportResponse>('/makerworld/import', {
  6185. method: 'POST',
  6186. body: JSON.stringify({
  6187. model_id,
  6188. instance_id: instance_id ?? null,
  6189. profile_id: profile_id ?? null,
  6190. folder_id: folder_id ?? null,
  6191. }),
  6192. }),
  6193. // Manyfold (#1471).
  6194. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6195. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6196. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6197. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6198. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6199. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6200. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6201. listManyfoldModels: (query: string, page: number) => {
  6202. const params = new URLSearchParams({ page: String(page) });
  6203. if (query) params.set('q', query);
  6204. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6205. },
  6206. getManyfoldModel: (modelId: string) =>
  6207. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6208. /** The model's preview, or null when it has none. Fetched rather than used
  6209. * as an <img src>: a failing protected <img> makes the app renew its media
  6210. * token, and models without a preview answer 404. */
  6211. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6212. const headers: Record<string, string> = {};
  6213. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6214. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6215. if (!response.ok) return null;
  6216. return response.blob();
  6217. },
  6218. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6219. request<ManyfoldImportResponse>('/manyfold/import', {
  6220. method: 'POST',
  6221. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6222. }),
  6223. getCloudSettingDetail: (settingId: string) =>
  6224. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6225. createCloudSetting: (data: SlicerSettingCreate) =>
  6226. request<SlicerSettingDetail>('/cloud/settings', {
  6227. method: 'POST',
  6228. body: JSON.stringify(data),
  6229. }),
  6230. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6231. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6232. method: 'PUT',
  6233. body: JSON.stringify(data),
  6234. }),
  6235. deleteCloudSetting: (settingId: string) =>
  6236. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6237. method: 'DELETE',
  6238. }),
  6239. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6240. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6241. getFilamentInfo: (settingIds: string[]) =>
  6242. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6243. method: 'POST',
  6244. body: JSON.stringify(settingIds),
  6245. }),
  6246. // Smart Plugs
  6247. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6248. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6249. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6250. createSmartPlug: (data: SmartPlugCreate) =>
  6251. request<SmartPlug>('/smart-plugs/', {
  6252. method: 'POST',
  6253. body: JSON.stringify(data),
  6254. }),
  6255. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6256. request<SmartPlug>(`/smart-plugs/${id}`, {
  6257. method: 'PATCH',
  6258. body: JSON.stringify(data),
  6259. }),
  6260. deleteSmartPlug: (id: number) =>
  6261. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6262. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6263. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6264. method: 'POST',
  6265. body: JSON.stringify({ action }),
  6266. }),
  6267. getSmartPlugStatus: (id: number) =>
  6268. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6269. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6270. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6271. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6272. method: 'POST',
  6273. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6274. }),
  6275. // Tasmota Discovery (auto-detects network)
  6276. startTasmotaScan: () =>
  6277. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6278. getTasmotaScanStatus: () =>
  6279. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6280. stopTasmotaScan: () =>
  6281. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6282. getDiscoveredTasmotaDevices: () =>
  6283. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6284. // Home Assistant Integration
  6285. testHAConnection: (url: string, token: string) =>
  6286. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6287. method: 'POST',
  6288. body: JSON.stringify({ url, token }),
  6289. }),
  6290. getHAEntities: (search?: string) => {
  6291. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6292. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6293. },
  6294. getHASensorEntities: () =>
  6295. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6296. // Home Assistant sensors bound to a printer (#1148, #448)
  6297. getHASensors: (printerId?: number) =>
  6298. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6299. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6300. getBindableHAEntities: (search?: string) => {
  6301. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6302. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6303. },
  6304. createHASensor: (data: PrinterHASensorCreate) =>
  6305. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6306. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6307. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6308. deleteHASensor: (id: number) =>
  6309. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6310. getLocationHASensors: (locationId?: number) =>
  6311. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6312. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6313. request<LocationHASensorReading[]>(
  6314. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6315. ),
  6316. getBindableLocationHAEntities: (search?: string) => {
  6317. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6318. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6319. },
  6320. createLocationHASensor: (data: LocationHASensorCreate) =>
  6321. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6322. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6323. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6324. deleteLocationHASensor: (id: number) =>
  6325. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6326. // REST smart plug
  6327. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6328. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6329. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6330. method: 'POST',
  6331. body: JSON.stringify({ url, method, headers, plug_id }),
  6332. }),
  6333. // Print Queue
  6334. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6335. const params = new URLSearchParams();
  6336. if (printerId) params.set('printer_id', String(printerId));
  6337. if (status) params.set('status', status);
  6338. if (targetModel) params.set('target_model', targetModel);
  6339. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6340. },
  6341. // History (completed / failed / skipped / cancelled), one page at a time.
  6342. getQueueHistory: (params: QueueHistoryParams) =>
  6343. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6344. // Removes the history matching the same filters, server-side.
  6345. clearQueueHistory: (params: QueueHistoryFilters) =>
  6346. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6347. method: 'POST',
  6348. }),
  6349. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6350. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6351. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6352. addToQueue: (data: PrintQueueItemCreate) =>
  6353. request<PrintQueueItem>('/queue/', {
  6354. method: 'POST',
  6355. body: JSON.stringify(data),
  6356. }),
  6357. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6358. request<PrintQueueItem>(`/queue/${id}`, {
  6359. method: 'PATCH',
  6360. body: JSON.stringify(data),
  6361. }),
  6362. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6363. * last run a batch order could re-queue its plate from (#2960). */
  6364. removeFromQueue: (id: number) =>
  6365. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6366. reorderQueue: (items: { id: number; position: number }[]) =>
  6367. request<{ message: string }>('/queue/reorder', {
  6368. method: 'POST',
  6369. body: JSON.stringify({ items }),
  6370. }),
  6371. cancelQueueItem: (id: number) =>
  6372. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6373. stopQueueItem: (id: number) =>
  6374. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6375. /**
  6376. * Start a staged queue item. The backend re-checks live filament deficit
  6377. * for the assigned spool and, when short, returns 409 with a structured
  6378. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6379. * after the user confirms "Print Anyway" (#1496).
  6380. */
  6381. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6382. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6383. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6384. },
  6385. /**
  6386. * Clear the `require_previous_success` gate for a printer after the user
  6387. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6388. * restores skipped items whose error_message matches the gate string
  6389. * back to pending. Returns counts so the UI can render a precise toast.
  6390. */
  6391. // A job for any printer of a model waits when the last print failed on every
  6392. // free one; this clears the gate on the model's printers.
  6393. resumeModelQueueAfterFailure: (model: string) =>
  6394. request<{ acknowledged: number; printers: number }>(
  6395. `/queue/model/${encodeURIComponent(model)}/resume`,
  6396. { method: 'POST' },
  6397. ),
  6398. resumeQueueAfterFailure: (printerId: number) =>
  6399. request<{ acknowledged: number; restored: number }>(
  6400. `/queue/printer/${printerId}/resume`,
  6401. { method: 'POST' },
  6402. ),
  6403. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6404. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6405. method: 'PATCH',
  6406. body: JSON.stringify(data),
  6407. }),
  6408. // Batches
  6409. getBatches: (status?: string) => {
  6410. const params = status ? `?status=${status}` : '';
  6411. return request<PrintBatch[]>(`/queue/batches${params}`);
  6412. },
  6413. cancelBatch: (id: number) =>
  6414. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6415. createBatch: (data: PrintBatchCreate) =>
  6416. request<PrintBatch>('/queue/batches', {
  6417. method: 'POST',
  6418. body: JSON.stringify(data),
  6419. }),
  6420. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6421. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6422. method: 'POST',
  6423. body: JSON.stringify(data),
  6424. }),
  6425. ungroupBatch: (id: number) =>
  6426. request<{ ungrouped_count: number; message: string }>(
  6427. `/queue/batches/${id}/ungroup`,
  6428. { method: 'POST' },
  6429. ),
  6430. // K-Profiles
  6431. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6432. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6433. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6434. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6435. method: 'POST',
  6436. body: JSON.stringify(profile),
  6437. }),
  6438. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6439. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6440. method: 'DELETE',
  6441. body: JSON.stringify(profile),
  6442. }),
  6443. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6444. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6445. method: 'POST',
  6446. body: JSON.stringify(profiles),
  6447. }),
  6448. // Finance
  6449. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6450. getMyTransactions: (limit = 50, offset = 0) =>
  6451. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6452. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6453. const params = new URLSearchParams();
  6454. params.set('limit', String(limit));
  6455. params.set('offset', String(offset));
  6456. if (userId !== undefined) params.set('user_id', String(userId));
  6457. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6458. },
  6459. deleteTransaction: (transactionId: number) =>
  6460. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6461. method: 'DELETE',
  6462. }),
  6463. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6464. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6465. method: 'PATCH',
  6466. body: JSON.stringify(data),
  6467. }),
  6468. createManualPrint: (data: ManualPrintRequest) =>
  6469. request<WalletTransaction>('/finance/transactions/manual', {
  6470. method: 'POST',
  6471. body: JSON.stringify(data),
  6472. }),
  6473. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6474. listCostCenters: (includeInactive = false) =>
  6475. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6476. createCostCenter: (data: CostCenterCreateRequest) =>
  6477. request<CostCenterSummary>('/finance/cost-centers', {
  6478. method: 'POST',
  6479. body: JSON.stringify(data),
  6480. }),
  6481. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6482. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6483. method: 'PATCH',
  6484. body: JSON.stringify(data),
  6485. }),
  6486. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6487. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6488. method: 'PATCH',
  6489. body: JSON.stringify(data),
  6490. }),
  6491. deleteCostCenter: (costCenterId: number) =>
  6492. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6493. method: 'DELETE',
  6494. }),
  6495. getCostCenter: (costCenterId: number) =>
  6496. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6497. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6498. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6499. method: 'POST',
  6500. body: JSON.stringify(data),
  6501. }),
  6502. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6503. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6504. method: 'DELETE',
  6505. }),
  6506. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6507. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6508. method: 'POST',
  6509. body: JSON.stringify(data),
  6510. }),
  6511. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6512. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6513. method: 'POST',
  6514. body: JSON.stringify(data),
  6515. }),
  6516. rebuildBalanceLedger: () =>
  6517. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6518. method: 'POST',
  6519. }),
  6520. // K-Profile Notes (stored locally, not on printer)
  6521. getKProfileNotes: (printerId: number) =>
  6522. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6523. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6524. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6525. method: 'PUT',
  6526. body: JSON.stringify({ setting_id: settingId, note }),
  6527. }),
  6528. // Slot Preset Mappings
  6529. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6530. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6531. 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)}` : ''}`, {
  6532. method: 'PUT',
  6533. }),
  6534. // AMS Labels (user-defined friendly names)
  6535. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6536. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6537. request<{ ams_id: number; label: string }>(
  6538. `/printers/${printerId}/ams-labels/${amsId}`,
  6539. {
  6540. method: 'PUT',
  6541. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6542. }
  6543. ),
  6544. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6545. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6546. method: 'DELETE',
  6547. }),
  6548. configureAmsSlot: (
  6549. printerId: number,
  6550. amsId: number,
  6551. trayId: number,
  6552. config: {
  6553. tray_info_idx: string;
  6554. tray_type: string;
  6555. tray_sub_brands: string;
  6556. tray_color: string;
  6557. nozzle_temp_min: number;
  6558. nozzle_temp_max: number;
  6559. cali_idx: number;
  6560. nozzle_diameter: string;
  6561. setting_id?: string;
  6562. kprofile_filament_id?: string;
  6563. kprofile_setting_id?: string;
  6564. k_value?: number;
  6565. // Orca Cloud profile the slot is set to; the backend looks up its
  6566. // filament id when tray_info_idx is empty (#3216).
  6567. orca_profile_id?: string;
  6568. }
  6569. ) => {
  6570. const params = new URLSearchParams({
  6571. tray_info_idx: config.tray_info_idx,
  6572. tray_type: config.tray_type,
  6573. tray_sub_brands: config.tray_sub_brands,
  6574. tray_color: config.tray_color,
  6575. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6576. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6577. cali_idx: config.cali_idx.toString(),
  6578. nozzle_diameter: config.nozzle_diameter,
  6579. });
  6580. if (config.setting_id) {
  6581. params.set('setting_id', config.setting_id);
  6582. }
  6583. if (config.kprofile_filament_id) {
  6584. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6585. }
  6586. if (config.kprofile_setting_id) {
  6587. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6588. }
  6589. if (config.k_value !== undefined && config.k_value > 0) {
  6590. params.set('k_value', config.k_value.toString());
  6591. }
  6592. if (config.orca_profile_id) {
  6593. params.set('orca_profile_id', config.orca_profile_id);
  6594. }
  6595. return request<{
  6596. success: boolean;
  6597. message: string;
  6598. // The filament id the slot was actually given.
  6599. tray_info_idx?: string;
  6600. // Why an Orca profile went out as the generic for its material, or "".
  6601. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6602. /** A manual K value could not be sent; the filament setting was. */
  6603. k_value_unsent?: boolean;
  6604. }>(
  6605. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6606. { method: 'POST' }
  6607. );
  6608. },
  6609. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6610. request<{ success: boolean; message: string }>(
  6611. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6612. { method: 'POST' }
  6613. ),
  6614. // Notification Providers
  6615. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6616. createNotificationProvider: (data: NotificationProviderCreate) =>
  6617. request<NotificationProvider>('/notifications/', {
  6618. method: 'POST',
  6619. body: JSON.stringify(data),
  6620. }),
  6621. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6622. request<NotificationProvider>(`/notifications/${id}`, {
  6623. method: 'PATCH',
  6624. body: JSON.stringify(data),
  6625. }),
  6626. deleteNotificationProvider: (id: number) =>
  6627. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6628. testNotificationProvider: (id: number) =>
  6629. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6630. testNotificationConfig: (data: NotificationTestRequest) =>
  6631. request<NotificationTestResponse>('/notifications/test-config', {
  6632. method: 'POST',
  6633. body: JSON.stringify(data),
  6634. }),
  6635. testAllNotificationProviders: () =>
  6636. request<{
  6637. tested: number;
  6638. success: number;
  6639. failed: number;
  6640. results: Array<{
  6641. provider_id: number;
  6642. provider_name: string;
  6643. provider_type: string;
  6644. success: boolean;
  6645. message: string;
  6646. }>;
  6647. }>('/notifications/test-all', { method: 'POST' }),
  6648. // Notification Templates
  6649. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6650. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6651. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6652. method: 'PUT',
  6653. body: JSON.stringify(data),
  6654. }),
  6655. resetNotificationTemplate: (id: number) =>
  6656. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6657. method: 'POST',
  6658. }),
  6659. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6660. previewTemplate: (data: TemplatePreviewRequest) =>
  6661. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6662. method: 'POST',
  6663. body: JSON.stringify(data),
  6664. }),
  6665. // Notification Logs
  6666. getNotificationLogs: (params?: {
  6667. limit?: number;
  6668. offset?: number;
  6669. provider_id?: number;
  6670. event_type?: string;
  6671. success?: boolean;
  6672. days?: number;
  6673. }) => {
  6674. const searchParams = new URLSearchParams();
  6675. if (params?.limit) searchParams.set('limit', String(params.limit));
  6676. if (params?.offset) searchParams.set('offset', String(params.offset));
  6677. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6678. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6679. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6680. if (params?.days) searchParams.set('days', String(params.days));
  6681. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6682. },
  6683. getNotificationLogStats: (days = 7) =>
  6684. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6685. clearNotificationLogs: (olderThanDays = 30) =>
  6686. request<{ deleted: number; message: string }>(
  6687. `/notifications/logs?older_than_days=${olderThanDays}`,
  6688. { method: 'DELETE' }
  6689. ),
  6690. // Spoolman Integration
  6691. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6692. migrateSpoolmanTags: (dryRun: boolean) =>
  6693. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6694. method: 'POST',
  6695. }),
  6696. connectSpoolman: () =>
  6697. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6698. method: 'POST',
  6699. }),
  6700. syncPrinterAms: (printerId: number) =>
  6701. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6702. method: 'POST',
  6703. }),
  6704. syncAllPrintersAms: () =>
  6705. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6706. method: 'POST',
  6707. }),
  6708. getSpoolmanInventoryFilaments: () =>
  6709. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6710. getUnlinkedSpools: () =>
  6711. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6712. getLinkedSpools: () =>
  6713. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6714. linkSpool: (
  6715. spoolId: number,
  6716. context: {
  6717. spoolTag: string;
  6718. printerId: number;
  6719. amsId: number;
  6720. trayId: number;
  6721. }
  6722. ) =>
  6723. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6724. method: 'POST',
  6725. body: JSON.stringify({
  6726. spool_tag: context.spoolTag,
  6727. printer_id: context.printerId,
  6728. ams_id: context.amsId,
  6729. tray_id: context.trayId,
  6730. }),
  6731. }),
  6732. unlinkSpool: (spoolId: number) =>
  6733. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6734. method: 'POST',
  6735. }),
  6736. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6737. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6738. method: 'POST',
  6739. body: JSON.stringify(data),
  6740. }),
  6741. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6742. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6743. method: 'POST',
  6744. body: JSON.stringify(data),
  6745. }),
  6746. getSpoolmanSettings: () =>
  6747. 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'),
  6748. 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; }) =>
  6749. 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', {
  6750. method: 'PUT',
  6751. body: JSON.stringify(data),
  6752. }),
  6753. // Inventory
  6754. getSpools: (includeArchived = false) =>
  6755. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6756. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6757. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6758. request<InventorySpool>('/inventory/spools', {
  6759. method: 'POST',
  6760. body: JSON.stringify(data),
  6761. }),
  6762. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6763. request<InventorySpool[]>('/inventory/spools/bulk', {
  6764. method: 'POST',
  6765. body: JSON.stringify({ spool: data, quantity }),
  6766. }),
  6767. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6768. // dry_run=true → preview (no write); omitted → real import. Both share one
  6769. // multipart upload helper; see `uploadSpoolsCsv` below.
  6770. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6771. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6772. exportSpoolsCsv: async (): Promise<void> => {
  6773. const headers: Record<string, string> = {};
  6774. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6775. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6776. if (!response.ok) {
  6777. const error = await response.json().catch(() => ({}));
  6778. throw new Error(error.detail || `HTTP ${response.status}`);
  6779. }
  6780. const disposition = response.headers.get('Content-Disposition');
  6781. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6782. const blob = await response.blob();
  6783. const url = window.URL.createObjectURL(blob);
  6784. const a = document.createElement('a');
  6785. a.href = url;
  6786. a.download = filename;
  6787. document.body.appendChild(a);
  6788. a.click();
  6789. document.body.removeChild(a);
  6790. window.URL.revokeObjectURL(url);
  6791. },
  6792. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6793. request<InventorySpool>(`/inventory/spools/${id}`, {
  6794. method: 'PATCH',
  6795. body: JSON.stringify(data),
  6796. }),
  6797. deleteSpool: (id: number) =>
  6798. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6799. archiveSpool: (id: number) =>
  6800. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6801. restoreSpool: (id: number) =>
  6802. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6803. resetSpoolConsumedCounter: (id: number) =>
  6804. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6805. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6806. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6807. method: 'POST',
  6808. body: JSON.stringify({ spool_ids: spoolIds }),
  6809. }),
  6810. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6811. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6812. method: 'POST',
  6813. body: JSON.stringify({ ids, update }),
  6814. }),
  6815. bulkDeleteSpools: (ids: number[]) =>
  6816. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6817. method: 'POST',
  6818. body: JSON.stringify({ ids }),
  6819. }),
  6820. bulkArchiveSpools: (ids: number[]) =>
  6821. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6822. method: 'POST',
  6823. body: JSON.stringify({ ids }),
  6824. }),
  6825. bulkRestoreSpools: (ids: number[]) =>
  6826. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6827. method: 'POST',
  6828. body: JSON.stringify({ ids }),
  6829. }),
  6830. getSpoolKProfiles: (spoolId: number) =>
  6831. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6832. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6833. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6834. method: 'PUT',
  6835. body: JSON.stringify(profiles),
  6836. }),
  6837. /**
  6838. * What the spool assigned to this slot is configured to use *here* -- its
  6839. * per-printer-model filament preset and the K profile for this slot's hotend.
  6840. * Nulls when the slot holds no known spool.
  6841. */
  6842. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6843. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6844. getSpoolFilamentPresets: (spoolId: number) =>
  6845. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6846. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6847. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6848. method: 'PUT',
  6849. body: JSON.stringify(presets),
  6850. }),
  6851. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6852. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6853. const params = new URLSearchParams({
  6854. brand: key.brand,
  6855. material: key.material,
  6856. subtype: key.subtype,
  6857. color_name: key.color_name,
  6858. });
  6859. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6860. },
  6861. saveProfileDefault: (data: ProfileDefaultInput) =>
  6862. request<ProfileDefault>('/inventory/profile-defaults', {
  6863. method: 'PUT',
  6864. body: JSON.stringify(data),
  6865. }),
  6866. deleteProfileDefault: (defaultId: number) =>
  6867. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6868. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6869. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6870. request<{ updated: number }>(
  6871. spoolmanMode
  6872. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6873. : `/inventory/profile-defaults/${defaultId}/apply`,
  6874. { method: 'POST' },
  6875. ),
  6876. getAssignments: (printerId?: number) =>
  6877. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  6878. // move: the spool also leaves any other slot it is in, in the same
  6879. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  6880. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  6881. request<SpoolAssignment>('/inventory/assignments', {
  6882. method: 'POST',
  6883. body: JSON.stringify(data),
  6884. }),
  6885. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  6886. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  6887. // ── Spool label printing (#809) ──────────────────────────────────────────
  6888. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  6889. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  6890. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6891. postForBlob('/inventory/labels', data),
  6892. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  6893. postForBlob('/spoolman/labels', data),
  6894. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6895. postForBlob('/inventory/labels/preview', data, signal),
  6896. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  6897. postForBlob('/spoolman/labels/preview', data, signal),
  6898. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  6899. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  6900. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  6901. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  6902. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6903. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  6904. getSpoolCatalog: () =>
  6905. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  6906. addCatalogEntry: (data: { name: string; weight: number }) =>
  6907. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  6908. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  6909. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6910. deleteCatalogEntry: (id: number) =>
  6911. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  6912. bulkDeleteCatalogEntries: (ids: number[]) =>
  6913. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6914. resetSpoolCatalog: () =>
  6915. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  6916. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  6917. getSuppliers: () =>
  6918. request<Supplier[]>('/inventory/suppliers'),
  6919. createSupplier: (data: SupplierInput) =>
  6920. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  6921. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  6922. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6923. deleteSupplier: (id: number) =>
  6924. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  6925. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  6926. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  6927. method: 'PUT',
  6928. body: JSON.stringify(links),
  6929. }),
  6930. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  6931. // remote spool id — same request/response shape as the built-in inventory.
  6932. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  6933. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  6934. method: 'PUT',
  6935. body: JSON.stringify(links),
  6936. }),
  6937. // date_from/date_to scope the usage half only, so the widget can follow the
  6938. // dashboard timeframe; stock stays point-in-time.
  6939. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  6940. const params = new URLSearchParams();
  6941. if (dateFrom) params.set('date_from', dateFrom);
  6942. if (dateTo) params.set('date_to', dateTo);
  6943. addDayZone(params);
  6944. const qs = params.toString();
  6945. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  6946. },
  6947. getLocations: () =>
  6948. request<StorageLocation[]>('/inventory/locations'),
  6949. createLocation: (data: { name: string; identifier?: string | null }) =>
  6950. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  6951. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  6952. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6953. deleteLocation: (id: number) =>
  6954. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  6955. getColorCatalog: () =>
  6956. request<ColorCatalogEntry[]>('/inventory/colors'),
  6957. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  6958. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  6959. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  6960. * map says "Jade White"). #2875. */
  6961. getColorNameMap: () =>
  6962. request<{
  6963. colors: Record<string, string>;
  6964. by_material?: Record<string, string>;
  6965. bambu?: BambuCatalogColor[];
  6966. preset_materials?: Record<string, string>;
  6967. }>('/inventory/colors/map'),
  6968. addColorEntry: (data: {
  6969. manufacturer: string;
  6970. color_name: string;
  6971. hex_color: string;
  6972. material: string | null;
  6973. extra_colors?: string | null;
  6974. effect_type?: string | null;
  6975. }) =>
  6976. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  6977. updateColorEntry: (
  6978. id: number,
  6979. data: {
  6980. manufacturer: string;
  6981. color_name: string;
  6982. hex_color: string;
  6983. material: string | null;
  6984. extra_colors?: string | null;
  6985. effect_type?: string | null;
  6986. },
  6987. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  6988. deleteColorEntry: (id: number) =>
  6989. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  6990. bulkDeleteColorEntries: (ids: number[]) =>
  6991. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  6992. resetColorCatalog: () =>
  6993. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  6994. searchColors: (manufacturer?: string, material?: string) =>
  6995. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  6996. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  6997. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  6998. method: 'PATCH',
  6999. body: JSON.stringify(data),
  7000. }),
  7001. // Per-material-number inventory aggregate (#2870). The date range narrows
  7002. // the usage half only — stock is point-in-time.
  7003. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7004. const params = new URLSearchParams();
  7005. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7006. if (options?.dateTo) params.set('date_to', options.dateTo);
  7007. addDayZone(params);
  7008. const qs = params.toString();
  7009. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7010. },
  7011. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7012. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7013. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7014. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7015. request<SpoolUsageRecord[]>(
  7016. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7017. ),
  7018. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7019. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7020. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7021. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7022. clearSpoolUsageHistory: (spoolId: number) =>
  7023. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7024. syncWeightsFromAms: () =>
  7025. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7026. getSkuSettings: () =>
  7027. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7028. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7029. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7030. method: 'POST',
  7031. body: JSON.stringify(data),
  7032. }),
  7033. getShoppingList: () =>
  7034. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7035. addToShoppingList: (data: ShoppingListItemCreate) =>
  7036. request<ShoppingListItem>('/inventory/shopping-list', {
  7037. method: 'POST',
  7038. body: JSON.stringify(data),
  7039. }),
  7040. removeFromShoppingList: (id: number) =>
  7041. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7042. clearShoppingList: () =>
  7043. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7044. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7045. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7046. method: 'PATCH',
  7047. body: JSON.stringify({ status }),
  7048. }),
  7049. getFilamentPresets: () =>
  7050. request<SlicerSetting[]>('/cloud/filaments'),
  7051. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7052. getSpoolmanInventorySpools: (includeArchived = false) =>
  7053. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7054. getSpoolmanInventorySpool: (id: number) =>
  7055. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7056. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7057. request<InventorySpool>('/spoolman/inventory/spools', {
  7058. method: 'POST',
  7059. body: JSON.stringify(data),
  7060. }),
  7061. bulkCreateSpoolmanInventorySpools: (
  7062. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7063. quantity: number,
  7064. ) =>
  7065. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7066. method: 'POST',
  7067. body: JSON.stringify({ spool: data, quantity }),
  7068. }),
  7069. updateSpoolmanInventorySpool: (
  7070. id: number,
  7071. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7072. ) =>
  7073. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7074. method: 'PATCH',
  7075. body: JSON.stringify(data),
  7076. }),
  7077. deleteSpoolmanInventorySpool: (id: number) =>
  7078. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7079. archiveSpoolmanInventorySpool: (id: number) =>
  7080. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7081. restoreSpoolmanInventorySpool: (id: number) =>
  7082. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7083. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7084. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7085. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7086. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7087. method: 'POST',
  7088. body: JSON.stringify({ spool_ids: spoolIds }),
  7089. }),
  7090. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7091. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7092. method: 'POST',
  7093. body: JSON.stringify({ ids, update }),
  7094. }),
  7095. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7096. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7097. method: 'POST',
  7098. body: JSON.stringify({ ids }),
  7099. }),
  7100. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7101. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7102. method: 'POST',
  7103. body: JSON.stringify({ ids }),
  7104. }),
  7105. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7106. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7107. method: 'POST',
  7108. body: JSON.stringify({ ids }),
  7109. }),
  7110. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7111. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7112. method: 'PATCH',
  7113. body: JSON.stringify(data),
  7114. }),
  7115. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7116. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7117. method: 'PATCH',
  7118. body: JSON.stringify({ weight_grams: weightGrams }),
  7119. }),
  7120. // move: as assignSpool's (#1574).
  7121. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7122. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7123. method: 'POST',
  7124. body: JSON.stringify(data),
  7125. }),
  7126. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7127. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7128. getSpoolmanSlotAssignments: (printerId?: number) =>
  7129. request<Array<{
  7130. printer_id: number;
  7131. printer_name: string | null;
  7132. ams_id: number;
  7133. tray_id: number;
  7134. spoolman_spool_id: number;
  7135. ams_label: string | null;
  7136. }>>(
  7137. printerId !== undefined
  7138. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7139. : '/spoolman/inventory/slot-assignments/all',
  7140. ),
  7141. syncSpoolmanAmsWeights: () =>
  7142. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7143. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7144. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7145. method: 'PUT',
  7146. body: JSON.stringify(profiles),
  7147. }),
  7148. getSpoolmanFilamentPresets: (spoolId: number) =>
  7149. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7150. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7151. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7152. method: 'PUT',
  7153. body: JSON.stringify(presets),
  7154. }),
  7155. // Updates
  7156. getVersion: () => request<VersionInfo>('/updates/version'),
  7157. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7158. applyUpdate: () =>
  7159. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7160. method: 'POST',
  7161. }),
  7162. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7163. // Maintenance
  7164. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7165. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7166. request<MaintenanceType>('/maintenance/types', {
  7167. method: 'POST',
  7168. body: JSON.stringify(data),
  7169. }),
  7170. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7171. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7172. method: 'PATCH',
  7173. body: JSON.stringify(data),
  7174. }),
  7175. deleteMaintenanceType: (id: number) =>
  7176. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7177. restoreDefaultMaintenanceTypes: () =>
  7178. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7179. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7180. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7181. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7182. method: 'PATCH',
  7183. body: JSON.stringify(data),
  7184. }),
  7185. performMaintenance: (itemId: number, notes?: string) =>
  7186. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7187. method: 'POST',
  7188. body: JSON.stringify({ notes }),
  7189. }),
  7190. setPrinterHours: (printerId: number, totalHours: number) =>
  7191. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7192. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7193. { method: 'PATCH' }
  7194. ),
  7195. assignMaintenanceType: (printerId: number, typeId: number) =>
  7196. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7197. method: 'POST',
  7198. }),
  7199. removeMaintenanceItem: (itemId: number) =>
  7200. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7201. method: 'DELETE',
  7202. }),
  7203. // Camera
  7204. getCameraStreamToken: () =>
  7205. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7206. // Media token (#3025) — the credential for thumbnails, plate previews,
  7207. // timelapses, cover images and link icons. Minted behind plain auth rather
  7208. // than camera:view, and identified, so those routes gate on the resource's
  7209. // own permission and ownership instead of on the camera.
  7210. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7211. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7212. // the /ws connection. Browsers can't attach Authorization headers to a
  7213. // WebSocket handshake, so the token rides in the ?token= query param.
  7214. getWebSocketToken: () =>
  7215. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7216. // Connected apps: sign-in to external applications with Bambuddy
  7217. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7218. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7219. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7220. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7221. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7222. rotateConnectedAppSecret: (id: number) =>
  7223. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7224. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7225. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7226. request<ConnectAuthorizeInfo>(
  7227. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7228. ),
  7229. connectAuthorize: (payload: {
  7230. client_id: string;
  7231. redirect_uri: string;
  7232. code_challenge: string;
  7233. code_challenge_method: 'S256';
  7234. }) =>
  7235. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7236. method: 'POST',
  7237. body: JSON.stringify(payload),
  7238. }),
  7239. // Long-lived camera tokens (#1108, #2531)
  7240. createLongLivedCameraToken: (payload: {
  7241. name: string;
  7242. expires_in_days: number;
  7243. scope?: LongLivedTokenScope;
  7244. }) =>
  7245. request<LongLivedCameraToken>('/auth/tokens', {
  7246. method: 'POST',
  7247. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7248. }),
  7249. listMyLongLivedCameraTokens: () =>
  7250. request<LongLivedCameraToken[]>('/auth/tokens'),
  7251. listAllLongLivedCameraTokens: () =>
  7252. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7253. revokeLongLivedCameraToken: (tokenId: number) =>
  7254. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7255. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7256. // auth is disabled, where the backend gate is a no-op anyway.
  7257. getCamWallPrinters: (token?: string) =>
  7258. request<CamWallPrinter[]>(
  7259. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7260. ),
  7261. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7262. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7263. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7264. getOverlayStatus: (printerId: number, token?: string) =>
  7265. request<OverlayStatus>(
  7266. token
  7267. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7268. : `/printers/${printerId}/overlay-status`,
  7269. ),
  7270. getCameraStatus: (printerId: number) =>
  7271. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7272. diagnoseCamera: (printerId: number) =>
  7273. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7274. diagnosePrinter: (printerId: number) =>
  7275. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7276. diagnoseConnection: (body: {
  7277. ip_address: string;
  7278. serial_number?: string;
  7279. access_code?: string;
  7280. }) =>
  7281. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7282. method: 'POST',
  7283. body: JSON.stringify(body),
  7284. }),
  7285. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7286. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7287. const params = new URLSearchParams();
  7288. // Only forward use_external when the caller explicitly sets it. Omitted →
  7289. // backend derives the default from the printer's external_camera_enabled
  7290. // setting so calibration and runtime checks use the same camera (#1359).
  7291. if (options?.useExternal !== undefined) {
  7292. params.set('use_external', String(options.useExternal));
  7293. }
  7294. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7295. return request<PlateDetectionResult>(
  7296. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7297. );
  7298. },
  7299. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7300. const params = new URLSearchParams();
  7301. if (options?.label) params.set('label', options.label);
  7302. if (options?.useExternal !== undefined) {
  7303. params.set('use_external', String(options.useExternal));
  7304. }
  7305. return request<CalibrationResult & { index: number }>(
  7306. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7307. { method: 'POST' }
  7308. );
  7309. },
  7310. getPlateReferences: (printerId: number) => {
  7311. return request<{
  7312. references: PlateReference[];
  7313. max_references: number;
  7314. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7315. },
  7316. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7317. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7318. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7319. const params = new URLSearchParams();
  7320. params.set('label', label);
  7321. return request<{ success: boolean; index: number; label: string }>(
  7322. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7323. { method: 'PUT' }
  7324. );
  7325. },
  7326. deletePlateReference: (printerId: number, index: number) => {
  7327. return request<{ success: boolean; message: string }>(
  7328. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7329. { method: 'DELETE' }
  7330. );
  7331. },
  7332. // External Links
  7333. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7334. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7335. createExternalLink: (data: ExternalLinkCreate) =>
  7336. request<ExternalLink>('/external-links/', {
  7337. method: 'POST',
  7338. body: JSON.stringify(data),
  7339. }),
  7340. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7341. request<ExternalLink>(`/external-links/${id}`, {
  7342. method: 'PATCH',
  7343. body: JSON.stringify(data),
  7344. }),
  7345. deleteExternalLink: (id: number) =>
  7346. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7347. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7348. const formData = new FormData();
  7349. formData.append('file', file);
  7350. const headers: Record<string, string> = {};
  7351. if (authToken) {
  7352. headers['Authorization'] = `Bearer ${authToken}`;
  7353. }
  7354. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7355. method: 'POST',
  7356. headers,
  7357. body: formData,
  7358. });
  7359. if (!response.ok) {
  7360. const error = await response.json().catch(() => ({}));
  7361. throw new Error(error.detail || `HTTP ${response.status}`);
  7362. }
  7363. return response.json();
  7364. },
  7365. deleteExternalLinkIcon: (id: number) =>
  7366. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7367. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7368. // Projects
  7369. getProjects: (status?: string) => {
  7370. const params = new URLSearchParams();
  7371. if (status) params.set('status', status);
  7372. return request<ProjectListItem[]>(`/projects/?${params}`);
  7373. },
  7374. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7375. createProject: (data: ProjectCreate) =>
  7376. request<Project>('/projects/', {
  7377. method: 'POST',
  7378. body: JSON.stringify(data),
  7379. }),
  7380. updateProject: (id: number, data: ProjectUpdate) =>
  7381. request<Project>(`/projects/${id}`, {
  7382. method: 'PATCH',
  7383. body: JSON.stringify(data),
  7384. }),
  7385. deleteProject: (id: number) =>
  7386. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7387. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7388. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7389. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7390. getProjectFileProgress: (id: number) =>
  7391. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7392. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7393. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7394. method: 'POST',
  7395. body: JSON.stringify({ archive_ids: archiveIds }),
  7396. }),
  7397. // #1155: Cover image
  7398. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7399. // append the stream-token query string the same way archive thumbnails do.
  7400. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7401. // before the token does: callers used to append their own `?v=` to the
  7402. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7403. // inside the token value and the image 401'd whenever auth was enabled.
  7404. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7405. withMediaToken(
  7406. `${API_BASE}/projects/${projectId}/cover-image${
  7407. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7408. }`
  7409. ),
  7410. uploadProjectCoverImage: async (
  7411. projectId: number,
  7412. file: File
  7413. ): Promise<{ status: string; filename: string; size: number }> => {
  7414. const formData = new FormData();
  7415. formData.append('file', file);
  7416. const headers: Record<string, string> = {};
  7417. if (authToken) {
  7418. headers['Authorization'] = `Bearer ${authToken}`;
  7419. }
  7420. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7421. method: 'POST',
  7422. headers,
  7423. body: formData,
  7424. });
  7425. if (!response.ok) {
  7426. const error = await response.json().catch(() => ({}));
  7427. throw new Error(error.detail || `HTTP ${response.status}`);
  7428. }
  7429. return response.json();
  7430. },
  7431. deleteProjectCoverImage: (projectId: number) =>
  7432. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7433. // BOM (Bill of Materials)
  7434. getProjectBOM: (projectId: number) =>
  7435. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7436. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7437. request<BOMItem>(`/projects/${projectId}/bom`, {
  7438. method: 'POST',
  7439. body: JSON.stringify(data),
  7440. }),
  7441. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7442. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7443. method: 'PATCH',
  7444. body: JSON.stringify(data),
  7445. }),
  7446. deleteBOMItem: (projectId: number, itemId: number) =>
  7447. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7448. method: 'DELETE',
  7449. }),
  7450. // Templates
  7451. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7452. createTemplateFromProject: (projectId: number) =>
  7453. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7454. createProjectFromTemplate: (templateId: number, name?: string) =>
  7455. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7456. method: 'POST',
  7457. }),
  7458. // Timeline
  7459. getProjectTimeline: (projectId: number, limit = 50) =>
  7460. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7461. // Project Export/Import
  7462. exportProjectJson: (projectId: number) =>
  7463. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7464. importProject: (data: ProjectImport) =>
  7465. request<Project>('/projects/import', {
  7466. method: 'POST',
  7467. body: JSON.stringify(data),
  7468. }),
  7469. importProjectFile: async (file: File): Promise<Project> => {
  7470. const formData = new FormData();
  7471. formData.append('file', file);
  7472. const headers: Record<string, string> = {};
  7473. if (authToken) {
  7474. headers['Authorization'] = `Bearer ${authToken}`;
  7475. }
  7476. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7477. method: 'POST',
  7478. headers,
  7479. body: formData,
  7480. });
  7481. if (!response.ok) {
  7482. const error = await response.json().catch(() => ({}));
  7483. throw new Error(error.detail || `HTTP ${response.status}`);
  7484. }
  7485. return response.json();
  7486. },
  7487. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7488. const headers: Record<string, string> = {};
  7489. if (authToken) {
  7490. headers['Authorization'] = `Bearer ${authToken}`;
  7491. }
  7492. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7493. headers,
  7494. });
  7495. if (!response.ok) {
  7496. const error = await response.json().catch(() => ({}));
  7497. throw new Error(error.detail || `HTTP ${response.status}`);
  7498. }
  7499. const contentDisposition = response.headers.get('Content-Disposition');
  7500. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7501. const blob = await response.blob();
  7502. return { blob, filename };
  7503. },
  7504. // API Keys
  7505. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7506. createAPIKey: (data: APIKeyCreate) =>
  7507. request<APIKeyCreateResponse>('/api-keys/', {
  7508. method: 'POST',
  7509. body: JSON.stringify(data),
  7510. }),
  7511. deleteAPIKey: (id: number) =>
  7512. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7513. // AMS History
  7514. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7515. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7516. // Printer heater (nozzle / bed / chamber) sensor history
  7517. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7518. const params = new URLSearchParams({ hours: String(hours) });
  7519. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7520. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7521. },
  7522. // System Info
  7523. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7524. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7525. getStorageUsage: (options?: { refresh?: boolean }) => {
  7526. const params = new URLSearchParams();
  7527. if (options?.refresh) {
  7528. params.set('refresh', 'true');
  7529. }
  7530. const query = params.toString();
  7531. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7532. },
  7533. // Library (File Manager)
  7534. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7535. createLibraryFolder: (data: LibraryFolderCreate) =>
  7536. request<LibraryFolder>('/library/folders', {
  7537. method: 'POST',
  7538. body: JSON.stringify(data),
  7539. }),
  7540. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7541. request<LibraryFolder>(`/library/folders/${id}`, {
  7542. method: 'PUT',
  7543. body: JSON.stringify(data),
  7544. }),
  7545. deleteLibraryFolder: (id: number) =>
  7546. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7547. createExternalFolder: (data: ExternalFolderCreate) =>
  7548. request<LibraryFolder>('/library/folders/external', {
  7549. method: 'POST',
  7550. body: JSON.stringify(data),
  7551. }),
  7552. scanExternalFolder: (folderId: number) =>
  7553. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7554. method: 'POST',
  7555. }),
  7556. getLibraryFoldersByProject: (projectId: number) =>
  7557. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7558. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7559. getLibraryFiles: (
  7560. folderId?: number | null,
  7561. includeRoot = true,
  7562. projectId?: number,
  7563. scope?: 'internal' | 'external',
  7564. recursive = false,
  7565. tagIds: number[] = [],
  7566. ) => {
  7567. const params = new URLSearchParams();
  7568. if (folderId !== undefined && folderId !== null) {
  7569. params.set('folder_id', String(folderId));
  7570. }
  7571. if (projectId !== undefined) {
  7572. params.set('project_id', String(projectId));
  7573. }
  7574. params.set('include_root', String(includeRoot));
  7575. if (scope === 'internal') params.set('internal_only', 'true');
  7576. else if (scope === 'external') params.set('external_only', 'true');
  7577. // recursive=true expands the folder_id filter to include every descendant
  7578. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7579. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7580. if (recursive) params.set('recursive', 'true');
  7581. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7582. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7583. // the array length. Tag filter intentionally bypasses folder scoping
  7584. // server-side (cross-cutting design decision).
  7585. for (const tagId of tagIds) {
  7586. params.append('tag_ids', String(tagId));
  7587. }
  7588. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7589. },
  7590. getLibraryFolderReadme: (folderId: number) =>
  7591. request<{ filename: string; content: string; truncated: boolean }>(
  7592. `/library/folders/${folderId}/readme`,
  7593. ),
  7594. // ============ Library tag catalog (#1268) ============
  7595. getLibraryTags: () =>
  7596. request<LibraryTag[]>('/library/tags'),
  7597. createLibraryTag: (name: string) =>
  7598. request<LibraryTag>('/library/tags', {
  7599. method: 'POST',
  7600. body: JSON.stringify({ name }),
  7601. }),
  7602. updateLibraryTag: (id: number, name: string) =>
  7603. request<LibraryTag>(`/library/tags/${id}`, {
  7604. method: 'PATCH',
  7605. body: JSON.stringify({ name }),
  7606. }),
  7607. deleteLibraryTag: (id: number) =>
  7608. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7609. bulkAssignLibraryTags: (
  7610. fileIds: number[],
  7611. tagIds: number[],
  7612. action: 'add' | 'remove' | 'replace',
  7613. ) =>
  7614. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7615. method: 'POST',
  7616. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7617. }),
  7618. // ============ Variant groups (#671 / #2570) ============
  7619. // "These files are the same job sliced for different printers." Consumed from
  7620. // both ends: the queue picks a printer and needs the matching file, the File
  7621. // Manager's print action has the printer and needs the same match.
  7622. createVariantGroup: (
  7623. members: { library_file_id: number; target_model?: string }[],
  7624. name?: string,
  7625. ) =>
  7626. request<VariantGroup>('/library/variant-groups', {
  7627. method: 'POST',
  7628. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7629. }),
  7630. getVariantGroup: (groupId: number) =>
  7631. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7632. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7633. uploadLibraryFile: async (
  7634. file: File,
  7635. folderId?: number | null,
  7636. generateStlThumbnails: boolean = true
  7637. ): Promise<LibraryFileUploadResponse> => {
  7638. const formData = new FormData();
  7639. formData.append('file', file);
  7640. const params = new URLSearchParams();
  7641. if (folderId) params.set('folder_id', String(folderId));
  7642. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7643. const headers: Record<string, string> = {};
  7644. if (authToken) {
  7645. headers['Authorization'] = `Bearer ${authToken}`;
  7646. }
  7647. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7648. method: 'POST',
  7649. headers,
  7650. body: formData,
  7651. });
  7652. if (!response.ok) {
  7653. const error = await response.json().catch(() => ({}));
  7654. throw new Error(error.detail || `HTTP ${response.status}`);
  7655. }
  7656. return response.json();
  7657. },
  7658. extractZipFile: async (
  7659. file: File,
  7660. folderId?: number | null,
  7661. preserveStructure: boolean = true,
  7662. createFolderFromZip: boolean = false,
  7663. generateStlThumbnails: boolean = true
  7664. ): Promise<ZipExtractResponse> => {
  7665. const formData = new FormData();
  7666. formData.append('file', file);
  7667. const params = new URLSearchParams();
  7668. if (folderId) params.set('folder_id', String(folderId));
  7669. params.set('preserve_structure', String(preserveStructure));
  7670. params.set('create_folder_from_zip', String(createFolderFromZip));
  7671. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7672. const headers: Record<string, string> = {};
  7673. if (authToken) {
  7674. headers['Authorization'] = `Bearer ${authToken}`;
  7675. }
  7676. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7677. method: 'POST',
  7678. headers,
  7679. body: formData,
  7680. });
  7681. if (!response.ok) {
  7682. const error = await response.json().catch(() => ({}));
  7683. throw new Error(error.detail || `HTTP ${response.status}`);
  7684. }
  7685. return response.json();
  7686. },
  7687. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7688. request<LibraryFile>(`/library/files/${id}`, {
  7689. method: 'PUT',
  7690. body: JSON.stringify(data),
  7691. }),
  7692. deleteLibraryFile: (id: number) =>
  7693. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7694. // ========== Library Trash (#1008) ==========
  7695. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7696. request<LibraryPurgePreview>(
  7697. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7698. ),
  7699. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7700. request<{ moved_to_trash: number }>('/library/purge', {
  7701. method: 'POST',
  7702. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7703. }),
  7704. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7705. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7706. restoreLibraryTrash: (fileId: number) =>
  7707. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7708. hardDeleteLibraryTrash: (fileId: number) =>
  7709. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7710. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7711. getLibraryTrashSettings: () =>
  7712. request<LibraryTrashSettings>('/library/trash/settings'),
  7713. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7714. request<LibraryTrashSettings>('/library/trash/settings', {
  7715. method: 'PUT',
  7716. body: JSON.stringify(body),
  7717. }),
  7718. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7719. createLibrarySlicerToken: (fileId: number) =>
  7720. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7721. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7722. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7723. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7724. const headers: Record<string, string> = {};
  7725. if (authToken) {
  7726. headers['Authorization'] = `Bearer ${authToken}`;
  7727. }
  7728. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7729. if (!response.ok) {
  7730. const error = await response.json().catch(() => ({}));
  7731. throw new Error(error.detail || `HTTP ${response.status}`);
  7732. }
  7733. const disposition = response.headers.get('Content-Disposition');
  7734. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7735. const blob = await response.blob();
  7736. const url = window.URL.createObjectURL(blob);
  7737. const a = document.createElement('a');
  7738. a.href = url;
  7739. a.download = downloadFilename;
  7740. document.body.appendChild(a);
  7741. a.click();
  7742. document.body.removeChild(a);
  7743. window.URL.revokeObjectURL(url);
  7744. },
  7745. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7746. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7747. // previews render in the browser; the first render is posted back so the
  7748. // grid gets a thumbnail without a server-side renderer for those formats.
  7749. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7750. const formData = new FormData();
  7751. formData.append('thumbnail', thumbnail, 'preview.png');
  7752. const headers: Record<string, string> = {};
  7753. if (authToken) {
  7754. headers['Authorization'] = `Bearer ${authToken}`;
  7755. }
  7756. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7757. method: 'POST',
  7758. headers,
  7759. body: formData,
  7760. });
  7761. if (!response.ok) {
  7762. const error = await response.json().catch(() => ({}));
  7763. throw new Error(error.detail || `HTTP ${response.status}`);
  7764. }
  7765. return response.json();
  7766. },
  7767. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7768. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7769. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7770. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7771. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7772. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7773. const formData = new FormData();
  7774. formData.append('file', file);
  7775. const headers: Record<string, string> = {};
  7776. if (authToken) {
  7777. headers['Authorization'] = `Bearer ${authToken}`;
  7778. }
  7779. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7780. method: 'POST',
  7781. headers,
  7782. body: formData,
  7783. });
  7784. if (!response.ok) {
  7785. const error = await response.json().catch(() => ({}));
  7786. throw new Error(error.detail || `HTTP ${response.status}`);
  7787. }
  7788. return response.json();
  7789. },
  7790. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7791. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7792. method: 'DELETE',
  7793. }),
  7794. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7795. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7796. request<{ status: string; moved: number }>('/library/files/move', {
  7797. method: 'POST',
  7798. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7799. }),
  7800. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7801. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7802. method: 'POST',
  7803. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7804. }),
  7805. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7806. batchGenerateStlThumbnails: (options: {
  7807. file_ids?: number[];
  7808. folder_id?: number;
  7809. all_missing?: boolean;
  7810. }) =>
  7811. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7812. method: 'POST',
  7813. body: JSON.stringify(options),
  7814. }),
  7815. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7816. request<LibraryFileUploadResponse>('/library/files/combine', {
  7817. method: 'POST',
  7818. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7819. }),
  7820. getLibraryFilePlates: (fileId: number) =>
  7821. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7822. getLibraryFileFilamentRequirements: (
  7823. fileId: number,
  7824. plateId?: number,
  7825. requestId?: string,
  7826. /** Ask for one entry per project slot instead of only the slots this
  7827. * plate consumes. The slice modal needs it: its filament list is
  7828. * positional, so a source whose only used slot is 4 must still present
  7829. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7830. * AMS matching must NOT set this — it wants the used-only list. */
  7831. fullSlots?: boolean,
  7832. ) => {
  7833. const qs = new URLSearchParams();
  7834. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7835. if (requestId) qs.set('request_id', requestId);
  7836. if (fullSlots) qs.set('full_slots', 'true');
  7837. return request<{
  7838. file_id: number;
  7839. filename: string;
  7840. filaments: Array<{
  7841. slot_id: number;
  7842. type: string;
  7843. color: string;
  7844. used_grams: number;
  7845. used_meters: number;
  7846. used_in_plate?: boolean;
  7847. }>;
  7848. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7849. },
  7850. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7851. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7852. * spinner + persistent toast can show "Generating G-code (45%)" while
  7853. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7854. * have an entry — early race window — or it expired) so the poller
  7855. * can keep trying. */
  7856. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7857. try {
  7858. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7859. } catch {
  7860. return null;
  7861. }
  7862. },
  7863. // GitHub Backup
  7864. getGitHubBackupConfig: () =>
  7865. request<GitHubBackupConfig | null>('/github-backup/config'),
  7866. getGitHubBackupCloudAccounts: () =>
  7867. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7868. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7869. request<GitHubBackupConfig>('/github-backup/config', {
  7870. method: 'POST',
  7871. body: JSON.stringify(config),
  7872. }),
  7873. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7874. request<GitHubBackupConfig>('/github-backup/config', {
  7875. method: 'PATCH',
  7876. body: JSON.stringify(config),
  7877. }),
  7878. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  7879. request<GitHubTestConnectionResponse>('/github-backup/test', {
  7880. method: 'POST',
  7881. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  7882. }),
  7883. testGitHubStoredConnection: () =>
  7884. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  7885. triggerGitHubBackup: () =>
  7886. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  7887. getGitHubBackupStatus: () =>
  7888. request<GitHubBackupStatus>('/github-backup/status'),
  7889. getGitHubBackupLogs: (limit: number = 50) =>
  7890. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  7891. clearGitHubBackupLogs: (keepLast: number = 10) =>
  7892. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  7893. // Restore from a Git backup (#2656)
  7894. getGitHubBackupCommits: (limit: number = 20) =>
  7895. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  7896. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  7897. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  7898. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  7899. request<GitHubRestoreResponse>('/github-backup/restore', {
  7900. method: 'POST',
  7901. body: JSON.stringify(payload),
  7902. }),
  7903. // Scheduled local backups
  7904. getLocalBackupStatus: () =>
  7905. request<LocalBackupStatus>('/local-backup/status'),
  7906. triggerLocalBackup: () =>
  7907. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  7908. checkLocalBackupPath: () =>
  7909. request<LocalBackupPathCheck>('/local-backup/path-check'),
  7910. getLocalBackups: () =>
  7911. request<LocalBackupFile[]>('/local-backup/backups'),
  7912. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  7913. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  7914. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  7915. });
  7916. if (!response.ok) throw new Error('Download failed');
  7917. const blob = await response.blob();
  7918. return { blob, filename };
  7919. },
  7920. restoreLocalBackup: (filename: string) =>
  7921. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  7922. deleteLocalBackup: (filename: string) =>
  7923. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  7924. // Obico AI failure detection
  7925. getObicoStatus: () =>
  7926. request<ObicoStatus>('/obico/status'),
  7927. getObicoPrinterStatus: () =>
  7928. request<ObicoPrinterStatus>('/obico/printer-status'),
  7929. // `token` is sent as-is, so an empty string tests with no token at all.
  7930. // Omitting the argument makes the backend fall back to the saved token.
  7931. testObicoConnection: (url: string, token?: string) =>
  7932. request<ObicoTestConnection>('/obico/test-connection', {
  7933. method: 'POST',
  7934. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  7935. }),
  7936. // OctoEverywhere AI failure detection
  7937. getOctoEverywhereStatus: () =>
  7938. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  7939. getOctoEverywherePrinterStatus: () =>
  7940. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  7941. // An omitted key uses the saved key; an explicit empty key is rejected.
  7942. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  7943. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  7944. method: 'POST',
  7945. body: JSON.stringify({ api_key: apiKey, confidence }),
  7946. }),
  7947. // Slicer API — slice in the background. Both endpoints return 202 + a
  7948. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  7949. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  7950. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  7951. method: 'POST',
  7952. body: JSON.stringify(body),
  7953. }),
  7954. sliceArchive: (archiveId: number, body: SliceRequest) =>
  7955. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  7956. method: 'POST',
  7957. body: JSON.stringify(body),
  7958. }),
  7959. getSliceJob: (jobId: number) =>
  7960. request<SliceJobState>(`/slice-jobs/${jobId}`),
  7961. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  7962. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  7963. // backend/app/api/routes/slicer_presets.py for the priority rules.
  7964. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  7965. // backend; the SliceModal's Refresh button passes true so a preset deleted
  7966. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  7967. getSlicerPresets: (options?: { refresh?: boolean }) =>
  7968. request<UnifiedPresetsResponse>(
  7969. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  7970. ),
  7971. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  7972. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  7973. listSlicerPipelines: () =>
  7974. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  7975. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  7976. request<SlicerPipeline>('/slicer-pipelines/', {
  7977. method: 'POST',
  7978. body: JSON.stringify(data),
  7979. }),
  7980. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  7981. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  7982. method: 'PUT',
  7983. body: JSON.stringify(data),
  7984. }),
  7985. deleteSlicerPipeline: (id: number) =>
  7986. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  7987. checkPipelineEligibility: (
  7988. pipelineId: number,
  7989. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  7990. ) =>
  7991. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  7992. method: 'POST',
  7993. body: JSON.stringify(
  7994. source.kind === 'libraryFile'
  7995. ? { source_library_file_id: source.id }
  7996. : { source_archive_id: source.id },
  7997. ),
  7998. }),
  7999. runPipeline: (
  8000. pipelineId: number,
  8001. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8002. force = false,
  8003. copies = 1,
  8004. ) =>
  8005. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8006. method: 'POST',
  8007. body: JSON.stringify({
  8008. ...(source.kind === 'libraryFile'
  8009. ? { source_library_file_id: source.id }
  8010. : { source_archive_id: source.id }),
  8011. force,
  8012. copies,
  8013. }),
  8014. }),
  8015. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8016. request<PipelineRunListResponse>(
  8017. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8018. ),
  8019. // Dashboard list across all pipelines (#1425 PR C).
  8020. listAllPipelineRuns: (params: {
  8021. limit?: number;
  8022. offset?: number;
  8023. pipelineId?: number;
  8024. status?: string;
  8025. targetPrinterId?: number;
  8026. targetModelClass?: string;
  8027. } = {}) => {
  8028. const search = new URLSearchParams();
  8029. if (params.limit) search.set('limit', String(params.limit));
  8030. if (params.offset) search.set('offset', String(params.offset));
  8031. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8032. if (params.status) search.set('status', params.status);
  8033. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8034. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8035. const q = search.toString();
  8036. return request<PipelineRunListResponse>(
  8037. `/pipeline-runs${q ? '?' + q : ''}`,
  8038. );
  8039. },
  8040. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8041. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8042. // runs are preserved.
  8043. clearTerminalPipelineRuns: () =>
  8044. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8045. cancelPipelineRun: (runId: number) =>
  8046. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8047. retryFailedPipelineRun: (runId: number) =>
  8048. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8049. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8050. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8051. // SliceModal uses this to classify cloud / standard presets by their
  8052. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8053. getSlicerPrinterModels: () =>
  8054. request<Record<string, string>>('/slicer/printer-models'),
  8055. getSlicerLoadedSpools: () =>
  8056. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8057. /**
  8058. * Effective values of a process preset, with its `inherits:` chain flattened
  8059. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8060. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8061. * 0.42mm line width appears as the C++ default of 0).
  8062. *
  8063. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8064. * too old for the endpoint, or slicing not configured -- and the caller should
  8065. * fall back to schema defaults rather than treat it as a failure.
  8066. */
  8067. getSlicerPresetValues: (ref: PresetRef) =>
  8068. request<SlicerPresetValues>(
  8069. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8070. ),
  8071. // Local Presets (OrcaSlicer imports)
  8072. getLocalPresets: () =>
  8073. request<LocalPresetsResponse>('/local-presets/'),
  8074. importLocalPresets: (formData: FormData) =>
  8075. fetch(`${API_BASE}/local-presets/import`, {
  8076. method: 'POST',
  8077. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8078. body: formData,
  8079. }).then(async (res) => {
  8080. if (!res.ok) {
  8081. const err = await res.json().catch(() => ({}));
  8082. throw new Error(err.detail || `HTTP ${res.status}`);
  8083. }
  8084. return res.json() as Promise<ImportResponse>;
  8085. }),
  8086. deleteLocalPreset: (id: number) =>
  8087. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8088. };
  8089. // AMS History types
  8090. export interface AMSHistoryPoint {
  8091. recorded_at: string;
  8092. humidity: number | null;
  8093. humidity_raw: number | null;
  8094. temperature: number | null;
  8095. }
  8096. export interface AMSHistoryResponse {
  8097. printer_id: number;
  8098. ams_id: number;
  8099. data: AMSHistoryPoint[];
  8100. min_humidity: number | null;
  8101. max_humidity: number | null;
  8102. avg_humidity: number | null;
  8103. min_temperature: number | null;
  8104. max_temperature: number | null;
  8105. avg_temperature: number | null;
  8106. }
  8107. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8108. export interface HeaterHistoryPoint {
  8109. recorded_at: string;
  8110. value: number | null;
  8111. target: number | null;
  8112. }
  8113. export interface HeaterSeries {
  8114. sensor_kind: HeaterSensorKind;
  8115. data: HeaterHistoryPoint[];
  8116. min_value: number | null;
  8117. max_value: number | null;
  8118. avg_value: number | null;
  8119. }
  8120. export interface PrinterSensorHistoryResponse {
  8121. printer_id: number;
  8122. series: HeaterSeries[];
  8123. }
  8124. // System Info types
  8125. export interface SystemInfo {
  8126. app: {
  8127. version: string;
  8128. base_dir: string;
  8129. archive_dir: string;
  8130. };
  8131. database: {
  8132. engine: string;
  8133. version: string;
  8134. archives: number;
  8135. archives_completed: number;
  8136. archives_failed: number;
  8137. archives_printing: number;
  8138. printers: number;
  8139. filaments: number;
  8140. projects: number;
  8141. smart_plugs: number;
  8142. total_print_time_seconds: number;
  8143. total_print_time_formatted: string;
  8144. total_filament_grams: number;
  8145. total_filament_kg: number;
  8146. };
  8147. printers: {
  8148. total: number;
  8149. connected: number;
  8150. connected_list: Array<{
  8151. id: number;
  8152. name: string;
  8153. state: string;
  8154. model: string;
  8155. }>;
  8156. };
  8157. storage: {
  8158. archive_size_bytes: number;
  8159. archive_size_formatted: string;
  8160. database_size_bytes: number;
  8161. database_size_formatted: string;
  8162. disk_total_bytes: number;
  8163. disk_total_formatted: string;
  8164. disk_used_bytes: number;
  8165. disk_used_formatted: string;
  8166. disk_free_bytes: number;
  8167. disk_free_formatted: string;
  8168. disk_percent_used: number;
  8169. };
  8170. system: {
  8171. platform: string;
  8172. platform_release: string;
  8173. platform_version: string;
  8174. architecture: string;
  8175. hostname: string;
  8176. python_version: string;
  8177. uptime_seconds: number;
  8178. uptime_formatted: string;
  8179. boot_time: string;
  8180. };
  8181. memory: {
  8182. total_bytes: number;
  8183. total_formatted: string;
  8184. available_bytes: number;
  8185. available_formatted: string;
  8186. used_bytes: number;
  8187. used_formatted: string;
  8188. percent_used: number;
  8189. };
  8190. cpu: {
  8191. count: number;
  8192. count_logical: number;
  8193. percent: number;
  8194. };
  8195. }
  8196. export interface StorageUsageCategory {
  8197. key: string;
  8198. label: string;
  8199. bytes: number;
  8200. formatted: string;
  8201. percent_of_total: number;
  8202. }
  8203. export interface StorageUsageOtherItem {
  8204. bucket: string;
  8205. label: string;
  8206. kind: 'system' | 'data';
  8207. deletable: boolean;
  8208. bytes: number;
  8209. formatted: string;
  8210. percent_of_total: number;
  8211. }
  8212. export interface StorageUsageResponse {
  8213. roots: string[];
  8214. total_bytes: number;
  8215. total_formatted: string;
  8216. categories: StorageUsageCategory[];
  8217. other_breakdown: StorageUsageOtherItem[];
  8218. scan_errors: number;
  8219. generated_at: string;
  8220. cache: {
  8221. hit: boolean;
  8222. age_seconds: number;
  8223. max_age_seconds: number;
  8224. };
  8225. }
  8226. // Library (File Manager) types
  8227. export interface LibraryFolderTree {
  8228. id: number;
  8229. name: string;
  8230. parent_id: number | null;
  8231. project_id: number | null;
  8232. archive_id: number | null;
  8233. project_name: string | null;
  8234. archive_name: string | null;
  8235. is_external: boolean;
  8236. external_path: string | null;
  8237. external_readonly: boolean;
  8238. file_count: number;
  8239. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8240. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8241. latest_activity_at: string | null;
  8242. // Ownership (#3201). can_* are for the current user: what the File
  8243. // Manager may offer on this folder. The backend enforces the same rules.
  8244. created_by_id: number | null;
  8245. shared: boolean;
  8246. can_write: boolean;
  8247. can_rename: boolean;
  8248. can_delete: boolean;
  8249. children: LibraryFolderTree[];
  8250. }
  8251. export interface LibraryFolder {
  8252. id: number;
  8253. name: string;
  8254. parent_id: number | null;
  8255. project_id: number | null;
  8256. archive_id: number | null;
  8257. project_name: string | null;
  8258. archive_name: string | null;
  8259. is_external: boolean;
  8260. external_path: string | null;
  8261. external_readonly: boolean;
  8262. external_show_hidden: boolean;
  8263. file_count: number;
  8264. latest_activity_at: string | null;
  8265. // Ownership (#3201). can_* are for the current user: what the File
  8266. // Manager may offer on this folder. The backend enforces the same rules.
  8267. created_by_id: number | null;
  8268. shared: boolean;
  8269. can_write: boolean;
  8270. can_rename: boolean;
  8271. can_delete: boolean;
  8272. created_at: string;
  8273. updated_at: string;
  8274. }
  8275. export interface LibraryFolderCreate {
  8276. name: string;
  8277. parent_id?: number | null;
  8278. project_id?: number | null;
  8279. archive_id?: number | null;
  8280. }
  8281. export interface ExternalFolderCreate {
  8282. name: string;
  8283. external_path: string;
  8284. readonly?: boolean;
  8285. show_hidden?: boolean;
  8286. parent_id?: number | null;
  8287. }
  8288. export interface LibraryFolderUpdate {
  8289. name?: string;
  8290. parent_id?: number | null;
  8291. project_id?: number | null; // 0 to unlink
  8292. archive_id?: number | null; // 0 to unlink
  8293. shared?: boolean; // library:update_all only (#3201)
  8294. }
  8295. export interface LibraryFileDuplicate {
  8296. id: number;
  8297. filename: string;
  8298. folder_id: number | null;
  8299. folder_name: string | null;
  8300. created_at: string;
  8301. }
  8302. export interface LibraryFile {
  8303. id: number;
  8304. folder_id: number | null;
  8305. folder_name: string | null;
  8306. project_id: number | null;
  8307. project_name: string | null;
  8308. is_external: boolean;
  8309. filename: string;
  8310. file_path: string;
  8311. file_type: string;
  8312. file_size: number;
  8313. file_hash: string | null;
  8314. thumbnail_path: string | null;
  8315. metadata: Record<string, unknown> | null;
  8316. print_count: number;
  8317. last_printed_at: string | null;
  8318. notes: string | null;
  8319. // User link + photos of the printed result (#3077); source_url is the
  8320. // read-only import provenance (MakerWorld).
  8321. external_url: string | null;
  8322. photos: string[];
  8323. source_url: string | null;
  8324. duplicates: LibraryFileDuplicate[] | null;
  8325. duplicate_count: number;
  8326. // User tracking (Issue #206)
  8327. created_by_id: number | null;
  8328. created_by_username: string | null;
  8329. created_at: string;
  8330. updated_at: string;
  8331. // Metadata fields
  8332. print_name: string | null;
  8333. print_time_seconds: number | null;
  8334. filament_used_grams: number | null;
  8335. sliced_for_model: string | null;
  8336. }
  8337. export interface LibraryTagSummary {
  8338. id: number;
  8339. name: string;
  8340. }
  8341. export interface LibraryFileListItem {
  8342. id: number;
  8343. folder_id: number | null;
  8344. is_external: boolean;
  8345. filename: string;
  8346. file_type: string;
  8347. file_size: number;
  8348. thumbnail_path: string | null;
  8349. print_count: number;
  8350. duplicate_count: number;
  8351. // User tracking (Issue #206)
  8352. created_by_id: number | null;
  8353. created_by_username: string | null;
  8354. created_at: string;
  8355. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8356. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8357. fs_modified_at: string | null;
  8358. print_name: string | null;
  8359. print_time_seconds: number | null;
  8360. filament_used_grams: number | null;
  8361. sliced_for_model: string | null;
  8362. // Tags assigned to this file (#1268). The backend always emits an empty
  8363. // array when a file has no tags, but the field is typed optional so any
  8364. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8365. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8366. tags?: LibraryTagSummary[];
  8367. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8368. // group, which may include files in other folders — never the number of
  8369. // matching rows on screen. 0 when the file is not grouped.
  8370. variant_group_id?: number | null;
  8371. variant_count?: number;
  8372. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8373. // mocks construct list items without them. Read sites default to falsy.
  8374. external_url?: string | null;
  8375. has_notes?: boolean;
  8376. photo_count?: number;
  8377. }
  8378. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8379. export interface VariantGroupMember {
  8380. library_file_id: number;
  8381. filename: string;
  8382. target_model: string;
  8383. position: number;
  8384. }
  8385. export interface VariantGroup {
  8386. id: number;
  8387. name: string;
  8388. /** In priority order — index 0 wins when several printers are free at once. */
  8389. members: VariantGroupMember[];
  8390. }
  8391. // Library tag catalog (#1268)
  8392. export interface LibraryTag {
  8393. id: number;
  8394. name: string;
  8395. file_count: number;
  8396. created_at: string;
  8397. updated_at: string;
  8398. }
  8399. export interface LibraryTagBulkAssignResult {
  8400. files_updated: number;
  8401. associations_added: number;
  8402. associations_removed: number;
  8403. }
  8404. export interface LibraryFileUpdate {
  8405. filename?: string;
  8406. folder_id?: number | null;
  8407. project_id?: number | null;
  8408. notes?: string | null;
  8409. external_url?: string | null;
  8410. }
  8411. // Library trash (#1008)
  8412. export interface LibraryTrashItem {
  8413. id: number;
  8414. filename: string;
  8415. file_size: number;
  8416. thumbnail_path: string | null;
  8417. folder_id: number | null;
  8418. folder_name: string | null;
  8419. created_by_id: number | null;
  8420. created_by_username: string | null;
  8421. deleted_at: string;
  8422. auto_purge_at: string;
  8423. }
  8424. export interface LibraryTrashListResponse {
  8425. items: LibraryTrashItem[];
  8426. total: number;
  8427. retention_days: number;
  8428. }
  8429. export interface LibraryPurgePreview {
  8430. count: number;
  8431. total_bytes: number;
  8432. sample_filenames: string[];
  8433. older_than_days: number;
  8434. include_never_printed: boolean;
  8435. }
  8436. export interface LibraryTrashSettings {
  8437. retention_days: number;
  8438. auto_purge_enabled: boolean;
  8439. auto_purge_days: number;
  8440. auto_purge_include_never_printed: boolean;
  8441. }
  8442. export interface ArchivePurgePreview {
  8443. count: number;
  8444. total_bytes: number;
  8445. sample_filenames: string[];
  8446. older_than_days: number;
  8447. }
  8448. export interface ArchiveMergeMember {
  8449. id: number;
  8450. print_name: string | null;
  8451. filename: string;
  8452. created_at: string | null;
  8453. run_count: number;
  8454. }
  8455. /** Why a group is left out: at work now, or holding files only one can keep. */
  8456. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8457. export interface ArchiveMergeGroup {
  8458. survivor: ArchiveMergeMember;
  8459. merged: ArchiveMergeMember[];
  8460. skipped: ArchiveMergeSkip | null;
  8461. }
  8462. export interface ArchiveMergePreview {
  8463. groups: ArchiveMergeGroup[];
  8464. }
  8465. export interface ArchiveMergeResult {
  8466. merged: { survivor_id: number; merged_ids: number[] }[];
  8467. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8468. }
  8469. export interface ArchivePurgeSettings {
  8470. enabled: boolean;
  8471. days: number;
  8472. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8473. // contribution drops from Quick Stats too. Default false — soft-delete,
  8474. // Quick Stats preserved.
  8475. purge_stats: boolean;
  8476. }
  8477. export interface LibraryFileUploadResponse {
  8478. id: number;
  8479. filename: string;
  8480. file_type: string;
  8481. file_size: number;
  8482. thumbnail_path: string | null;
  8483. duplicate_of: number | null;
  8484. metadata: Record<string, unknown> | null;
  8485. }
  8486. export interface LibraryStats {
  8487. total_files: number;
  8488. total_folders: number;
  8489. total_size_bytes: number;
  8490. files_by_type: Record<string, number>;
  8491. total_prints: number;
  8492. disk_free_bytes: number;
  8493. disk_total_bytes: number;
  8494. disk_used_bytes: number;
  8495. }
  8496. export interface ZipExtractResult {
  8497. filename: string;
  8498. file_id: number;
  8499. folder_id: number | null;
  8500. }
  8501. export interface ZipExtractError {
  8502. filename: string;
  8503. error: string;
  8504. }
  8505. export interface ZipExtractResponse {
  8506. extracted: number;
  8507. folders_created: number;
  8508. files: ZipExtractResult[];
  8509. errors: ZipExtractError[];
  8510. }
  8511. // STL Thumbnail Generation types
  8512. export interface BatchThumbnailResult {
  8513. file_id: number;
  8514. filename: string;
  8515. success: boolean;
  8516. error?: string | null;
  8517. }
  8518. export interface BatchThumbnailResponse {
  8519. processed: number;
  8520. succeeded: number;
  8521. failed: number;
  8522. results: BatchThumbnailResult[];
  8523. }
  8524. // Discovery types
  8525. export interface DiscoveredPrinter {
  8526. serial: string;
  8527. name: string;
  8528. ip_address: string;
  8529. model: string | null;
  8530. discovered_at: string | null;
  8531. }
  8532. export interface DiscoveryStatus {
  8533. running: boolean;
  8534. }
  8535. export interface DiscoveryInfo {
  8536. is_docker: boolean;
  8537. ssdp_running: boolean;
  8538. scan_running: boolean;
  8539. subnets: string[];
  8540. }
  8541. export interface SubnetScanStatus {
  8542. running: boolean;
  8543. scanned: number;
  8544. total: number;
  8545. }
  8546. // Discovery API
  8547. export const discoveryApi = {
  8548. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8549. startDiscovery: (duration: number = 10) =>
  8550. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8551. stopDiscovery: () =>
  8552. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8553. getDiscoveredPrinters: () =>
  8554. request<DiscoveredPrinter[]>('/discovery/printers'),
  8555. // Subnet scanning (for Docker environments)
  8556. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8557. request<SubnetScanStatus>('/discovery/scan', {
  8558. method: 'POST',
  8559. body: JSON.stringify({ subnet, timeout }),
  8560. }),
  8561. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8562. stopSubnetScan: () =>
  8563. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8564. };
  8565. // Virtual Printer types
  8566. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8567. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8568. // accepted by the backend so older API clients keep working, but new code
  8569. // should send the canonical names.
  8570. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  8571. export interface VirtualPrinterProxyStatus {
  8572. running: boolean;
  8573. target_host: string;
  8574. ftp_port: number;
  8575. mqtt_port: number;
  8576. ftp_connections: number;
  8577. mqtt_connections: number;
  8578. }
  8579. export interface VirtualPrinterStatus {
  8580. enabled: boolean;
  8581. running: boolean;
  8582. mode: VirtualPrinterMode;
  8583. name: string;
  8584. serial: string;
  8585. model: string;
  8586. model_name: string;
  8587. pending_files: number;
  8588. target_printer_ip?: string; // For proxy mode
  8589. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8590. }
  8591. export interface VirtualPrinterSettings {
  8592. tailscale_disabled: boolean;
  8593. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8594. status: VirtualPrinterStatus;
  8595. }
  8596. export interface NetworkInterface {
  8597. name: string;
  8598. ip: string;
  8599. netmask: string;
  8600. subnet: string;
  8601. is_alias?: boolean;
  8602. label?: string;
  8603. }
  8604. export interface PendingUpload {
  8605. id: number;
  8606. filename: string;
  8607. // Resolved name the review card should show — mirrors what archive_print
  8608. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8609. // back to the stripped filename stem when the 3MF has no embedded title or
  8610. // the operator has chosen the "filename" archive-name source.
  8611. display_name: string;
  8612. file_size: number;
  8613. source_ip: string | null;
  8614. status: string;
  8615. tags: string | null;
  8616. notes: string | null;
  8617. project_id: number | null;
  8618. uploaded_at: string;
  8619. }
  8620. // Virtual Printer API
  8621. export const virtualPrinterApi = {
  8622. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8623. updateSettings: (data: {
  8624. tailscale_disabled?: boolean;
  8625. archive_name_source?: 'metadata' | 'filename';
  8626. }) => {
  8627. const params = new URLSearchParams();
  8628. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8629. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8630. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8631. method: 'PUT',
  8632. });
  8633. },
  8634. };
  8635. // Multi Virtual Printer API
  8636. export interface VirtualPrinterConfig {
  8637. id: number;
  8638. name: string;
  8639. enabled: boolean;
  8640. mode: VirtualPrinterMode;
  8641. model: string | null;
  8642. model_name: string | null;
  8643. access_code_set: boolean;
  8644. serial: string;
  8645. target_printer_id: number | null;
  8646. auto_dispatch: boolean;
  8647. queue_force_color_match: boolean;
  8648. save_ams_mapping: boolean;
  8649. gcode_injection: boolean;
  8650. tailscale_disabled: boolean;
  8651. bind_ip: string | null;
  8652. remote_interface_ip: string | null;
  8653. position: number;
  8654. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8655. }
  8656. export interface VirtualPrinterListResponse {
  8657. printers: VirtualPrinterConfig[];
  8658. models: Record<string, string>;
  8659. }
  8660. export const multiVirtualPrinterApi = {
  8661. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8662. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8663. create: (data: {
  8664. name?: string;
  8665. enabled?: boolean;
  8666. mode?: string;
  8667. model?: string;
  8668. access_code?: string;
  8669. target_printer_id?: number;
  8670. auto_dispatch?: boolean;
  8671. queue_force_color_match?: boolean;
  8672. save_ams_mapping?: boolean;
  8673. gcode_injection?: boolean;
  8674. bind_ip?: string;
  8675. remote_interface_ip?: string;
  8676. }) =>
  8677. request<VirtualPrinterConfig>('/virtual-printers', {
  8678. method: 'POST',
  8679. body: JSON.stringify(data),
  8680. }),
  8681. update: (id: number, data: {
  8682. name?: string;
  8683. enabled?: boolean;
  8684. mode?: string;
  8685. model?: string;
  8686. access_code?: string;
  8687. target_printer_id?: number;
  8688. auto_dispatch?: boolean;
  8689. queue_force_color_match?: boolean;
  8690. save_ams_mapping?: boolean;
  8691. gcode_injection?: boolean;
  8692. tailscale_disabled?: boolean;
  8693. bind_ip?: string;
  8694. remote_interface_ip?: string;
  8695. }) =>
  8696. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8697. method: 'PUT',
  8698. body: JSON.stringify(data),
  8699. }),
  8700. remove: (id: number) =>
  8701. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8702. method: 'DELETE',
  8703. }),
  8704. getTailscaleStatus: () =>
  8705. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8706. getCaCertificate: () =>
  8707. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8708. diagnose: (id: number) =>
  8709. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8710. };
  8711. /** The shared CA certificate every virtual printer presents — imported once
  8712. * into the slicer's trust store. Only the public certificate is returned. */
  8713. export interface VPCaCertificate {
  8714. pem: string;
  8715. fingerprint_sha256: string;
  8716. not_valid_after: string;
  8717. }
  8718. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8719. export interface VPDiagnosticCheck {
  8720. id:
  8721. | 'enabled'
  8722. | 'running'
  8723. | 'bind_interface'
  8724. | 'access_code'
  8725. | 'target_printer'
  8726. | 'port_ftps'
  8727. | 'port_mqtt'
  8728. | 'port_bind'
  8729. | 'certificate';
  8730. status: VPDiagnosticStatus;
  8731. params: Record<string, string | number>;
  8732. }
  8733. export interface VPDiagnosticResult {
  8734. vp_id: number;
  8735. vp_name: string;
  8736. mode: string;
  8737. overall: 'ok' | 'warnings' | 'problems';
  8738. checks: VPDiagnosticCheck[];
  8739. }
  8740. export interface TailscaleStatusResponse {
  8741. available: boolean;
  8742. fqdn: string;
  8743. hostname: string;
  8744. tailnet_name: string;
  8745. tailscale_ips: string[];
  8746. error: string | null;
  8747. }
  8748. // Pending Uploads API
  8749. export const pendingUploadsApi = {
  8750. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8751. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8752. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8753. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8754. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  8755. method: 'POST',
  8756. body: JSON.stringify(data || {}),
  8757. }),
  8758. discard: (id: number) =>
  8759. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8760. archiveAll: () =>
  8761. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8762. discardAll: () =>
  8763. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8764. };
  8765. // Firmware API Types
  8766. export interface AvailableFirmwareVersion {
  8767. version: string;
  8768. file_available: boolean;
  8769. download_url: string | null;
  8770. release_notes: string | null;
  8771. release_time: string | null;
  8772. }
  8773. export interface FirmwareUpdateInfo {
  8774. printer_id: number;
  8775. printer_name: string;
  8776. model: string | null;
  8777. current_version: string | null;
  8778. latest_version: string | null;
  8779. update_available: boolean;
  8780. download_url: string | null;
  8781. release_notes: string | null;
  8782. available_versions: AvailableFirmwareVersion[];
  8783. }
  8784. export interface FirmwareUploadPrepare {
  8785. can_proceed: boolean;
  8786. sd_card_present: boolean;
  8787. sd_card_free_space: number;
  8788. firmware_size: number;
  8789. space_sufficient: boolean;
  8790. update_available: boolean;
  8791. current_version: string | null;
  8792. latest_version: string | null;
  8793. target_version: string | null;
  8794. firmware_filename: string | null;
  8795. errors: string[];
  8796. }
  8797. export interface FirmwareUploadStatus {
  8798. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8799. progress: number;
  8800. message: string;
  8801. error: string | null;
  8802. firmware_filename: string | null;
  8803. firmware_version: string | null;
  8804. }
  8805. // Firmware API
  8806. export const firmwareApi = {
  8807. checkUpdates: () =>
  8808. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8809. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8810. prepareUpload: (printerId: number, version?: string) =>
  8811. request<FirmwareUploadPrepare>(
  8812. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8813. ),
  8814. startUpload: (printerId: number, version?: string) =>
  8815. request<{ started: boolean; message: string }>(
  8816. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8817. { method: 'POST' },
  8818. ),
  8819. getUploadStatus: (printerId: number) =>
  8820. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8821. };
  8822. // Support types
  8823. export interface DebugLoggingState {
  8824. enabled: boolean;
  8825. enabled_at: string | null;
  8826. duration_seconds: number | null;
  8827. }
  8828. export interface LogEntry {
  8829. timestamp: string;
  8830. level: string;
  8831. logger_name: string;
  8832. message: string;
  8833. }
  8834. export interface LogsResponse {
  8835. entries: LogEntry[];
  8836. total_in_file: number;
  8837. filtered_count: number;
  8838. }
  8839. // Support API
  8840. export const supportApi = {
  8841. getDebugLoggingState: () =>
  8842. request<DebugLoggingState>('/support/debug-logging'),
  8843. setDebugLogging: (enabled: boolean) =>
  8844. request<DebugLoggingState>('/support/debug-logging', {
  8845. method: 'POST',
  8846. body: JSON.stringify({ enabled }),
  8847. }),
  8848. downloadSupportBundle: async () => {
  8849. const headers: Record<string, string> = {};
  8850. if (authToken) {
  8851. headers['Authorization'] = `Bearer ${authToken}`;
  8852. }
  8853. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8854. if (!response.ok) {
  8855. const error = await response.json().catch(() => ({}));
  8856. throw new Error(error.detail || `HTTP ${response.status}`);
  8857. }
  8858. // Get filename from Content-Disposition header or use default
  8859. const disposition = response.headers.get('Content-Disposition');
  8860. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  8861. // Download the blob
  8862. const blob = await response.blob();
  8863. const url = window.URL.createObjectURL(blob);
  8864. const a = document.createElement('a');
  8865. a.href = url;
  8866. a.download = filename;
  8867. document.body.appendChild(a);
  8868. a.click();
  8869. document.body.removeChild(a);
  8870. window.URL.revokeObjectURL(url);
  8871. },
  8872. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  8873. const searchParams = new URLSearchParams();
  8874. if (params?.limit) searchParams.set('limit', params.limit.toString());
  8875. if (params?.level) searchParams.set('level', params.level);
  8876. if (params?.search) searchParams.set('search', params.search);
  8877. const query = searchParams.toString();
  8878. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  8879. },
  8880. clearLogs: () =>
  8881. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  8882. };
  8883. // SpoolBuddy types
  8884. export interface SpoolBuddyDevice {
  8885. id: number;
  8886. device_id: string;
  8887. hostname: string;
  8888. ip_address: string;
  8889. backend_url?: string | null;
  8890. firmware_version: string | null;
  8891. has_nfc: boolean;
  8892. has_scale: boolean;
  8893. tare_offset: number;
  8894. calibration_factor: number;
  8895. nfc_reader_type: string | null;
  8896. nfc_connection: string | null;
  8897. display_brightness: number;
  8898. display_blank_timeout: number;
  8899. has_backlight: boolean;
  8900. last_calibrated_at: string | null;
  8901. last_seen: string | null;
  8902. pending_command: string | null;
  8903. nfc_ok: boolean;
  8904. scale_ok: boolean;
  8905. uptime_s: number;
  8906. update_status: string | null;
  8907. update_message: string | null;
  8908. system_stats: {
  8909. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  8910. cpu_temp_c?: number;
  8911. cpu_count?: number;
  8912. load_avg?: number[];
  8913. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  8914. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  8915. system_uptime_s?: number;
  8916. } | null;
  8917. online: boolean;
  8918. }
  8919. export interface DaemonUpdateCheck {
  8920. current_version: string;
  8921. latest_version: string | null;
  8922. update_available: boolean;
  8923. }
  8924. // SpoolBuddy API
  8925. export const spoolbuddyApi = {
  8926. getDevices: () =>
  8927. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  8928. deleteDevice: (deviceId: string) =>
  8929. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  8930. method: 'DELETE',
  8931. }),
  8932. tare: (deviceId: string) =>
  8933. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  8934. method: 'POST',
  8935. body: '{}',
  8936. }),
  8937. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  8938. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  8939. method: 'POST',
  8940. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  8941. }),
  8942. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  8943. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  8944. method: 'POST',
  8945. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  8946. }),
  8947. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  8948. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  8949. method: 'PUT',
  8950. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  8951. }),
  8952. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  8953. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  8954. method: 'POST',
  8955. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  8956. }),
  8957. checkDaemonUpdate: (deviceId: string) =>
  8958. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  8959. triggerUpdate: (deviceId: string) =>
  8960. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  8961. method: 'POST',
  8962. body: '{}',
  8963. }),
  8964. getSSHPublicKey: () =>
  8965. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  8966. writeTag: (deviceId: string, spoolId: number) =>
  8967. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  8968. method: 'POST',
  8969. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  8970. }),
  8971. cancelWrite: (deviceId: string) =>
  8972. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  8973. method: 'POST',
  8974. body: '{}',
  8975. }),
  8976. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  8977. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  8978. method: 'POST',
  8979. body: JSON.stringify({ command }),
  8980. }),
  8981. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  8982. request<{ status: string; diagnostic: string; message: string }>(
  8983. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  8984. { method: 'POST', body: '{}' }
  8985. ),
  8986. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  8987. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  8988. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  8989. { method: 'GET' }
  8990. ),
  8991. };
  8992. export interface BugReportRequest {
  8993. description: string;
  8994. email?: string;
  8995. screenshot_base64?: string;
  8996. include_support_info?: boolean;
  8997. debug_logs?: string;
  8998. }
  8999. export interface BugReportResponse {
  9000. success: boolean;
  9001. message: string;
  9002. issue_url?: string;
  9003. issue_number?: number;
  9004. }
  9005. export const bugReportApi = {
  9006. submit: (data: BugReportRequest) =>
  9007. request<BugReportResponse>('/bug-report/submit', {
  9008. method: 'POST',
  9009. body: JSON.stringify(data),
  9010. }),
  9011. startLogging: () =>
  9012. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9013. method: 'POST',
  9014. }),
  9015. stopLogging: (wasDebug: boolean) =>
  9016. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9017. method: 'POST',
  9018. }),
  9019. };
  9020. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9021. export interface AnnouncementText {
  9022. title: string;
  9023. body: string;
  9024. link_label?: string;
  9025. }
  9026. // One message from the Bambuddy maintainers. `texts` holds every language the
  9027. // message was written in; English is always there.
  9028. export interface Announcement {
  9029. id: string;
  9030. level: AnnouncementLevel;
  9031. texts: Record<string, AnnouncementText>;
  9032. link_url: string | null;
  9033. published_at: string | null;
  9034. expires_at: string | null;
  9035. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9036. archived: boolean;
  9037. read: boolean;
  9038. }
  9039. // `visible` says whether this user may see announcements at all (switched on,
  9040. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9041. // is published.
  9042. export interface AnnouncementList {
  9043. visible: boolean;
  9044. announcements: Announcement[];
  9045. }
  9046. export const announcementsApi = {
  9047. list: () => request<AnnouncementList>('/announcements'),
  9048. markRead: (id: string) =>
  9049. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9050. };
  9051. export interface SponsorPromptCheckResponse {
  9052. show: boolean;
  9053. milestone?: string;
  9054. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9055. threshold?: number;
  9056. payload?: Record<string, unknown>;
  9057. }
  9058. export const sponsorPromptApi = {
  9059. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9060. dismiss: (milestone: string) =>
  9061. request<void>('/sponsor-prompt/dismiss', {
  9062. method: 'POST',
  9063. body: JSON.stringify({ milestone }),
  9064. }),
  9065. };