client.ts 326 KB

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