client.ts 265 KB

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