client.ts 266 KB

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