client.ts 325 KB

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