client.ts 267 KB

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