client.ts 340 KB

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