client.ts 226 KB

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