client.ts 224 KB

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