client.ts 280 KB

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