client.ts 328 KB

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