client.ts 259 KB

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