client.ts 259 KB

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