client.ts 335 KB

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