client.ts 331 KB

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