client.ts 304 KB

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