client.ts 249 KB

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