client.ts 259 KB

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