client.ts 224 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668
  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 = 'ams_30x15' | 'box_40x30' | 'box_62x29' | 'avery_5160' | 'avery_l7160';
  2243. export interface InventorySpool {
  2244. id: number;
  2245. material: string;
  2246. subtype: string | null;
  2247. color_name: string | null;
  2248. // True when color_name was synthesised from subtype because Spoolman has no
  2249. // stored value (Spoolman-backed inventory only). The edit form uses this to
  2250. // leave the input blank, so the user doesn't round-trip the synth value
  2251. // back to Spoolman as if it were a real user-set color_name (#1319).
  2252. color_name_is_synthesized?: boolean;
  2253. rgba: string | null;
  2254. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  2255. extra_colors: string | null;
  2256. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  2257. effect_type: string | null;
  2258. brand: string | null;
  2259. label_weight: number;
  2260. core_weight: number;
  2261. core_weight_catalog_id: number | null;
  2262. weight_used: number;
  2263. // Anchor for the resettable "Total Consumed" display (#1390). The
  2264. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  2265. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  2266. // zeroes the counter without disturbing remaining. Optional for back-compat
  2267. // with rows from a pre-migration DB snapshot — default to 0.
  2268. weight_used_baseline?: number;
  2269. slicer_filament: string | null;
  2270. slicer_filament_name: string | null;
  2271. nozzle_temp_min: number | null;
  2272. nozzle_temp_max: number | null;
  2273. note: string | null;
  2274. added_full: boolean | null;
  2275. last_used: string | null;
  2276. encode_time: string | null;
  2277. tag_uid: string | null;
  2278. tray_uuid: string | null;
  2279. data_origin: string | null;
  2280. tag_type: string | null;
  2281. archived_at: string | null;
  2282. created_at: string;
  2283. updated_at: string;
  2284. cost_per_kg: number | null;
  2285. last_scale_weight: number | null;
  2286. last_weighed_at: string | null;
  2287. // User-defined category + per-spool low-stock threshold override (#729).
  2288. category: string | null;
  2289. low_stock_threshold_pct: number | null;
  2290. k_profiles?: SpoolKProfile[];
  2291. storage_location?: string | null;
  2292. }
  2293. export interface SpoolmanBulkCreateResult {
  2294. created: InventorySpool[];
  2295. requested_count: number;
  2296. failed_count: number;
  2297. }
  2298. export interface SpoolUsageRecord {
  2299. id: number;
  2300. spool_id: number;
  2301. printer_id: number | null;
  2302. print_name: string | null;
  2303. weight_used: number;
  2304. percent_used: number;
  2305. status: string;
  2306. cost: number | null;
  2307. created_at: string;
  2308. }
  2309. export interface SpoolKProfile {
  2310. id: number;
  2311. spool_id: number;
  2312. printer_id: number;
  2313. extruder: number;
  2314. nozzle_diameter: string;
  2315. nozzle_type: string | null;
  2316. k_value: number;
  2317. name: string | null;
  2318. cali_idx: number | null;
  2319. setting_id: string | null;
  2320. created_at: string;
  2321. }
  2322. export interface SpoolKProfileInput {
  2323. printer_id: number;
  2324. extruder?: number;
  2325. nozzle_diameter?: string;
  2326. nozzle_type?: string | null;
  2327. k_value: number;
  2328. name?: string | null;
  2329. cali_idx?: number | null;
  2330. setting_id?: string | null;
  2331. }
  2332. export interface SpoolAssignment {
  2333. id: number;
  2334. spool_id: number;
  2335. printer_id: number;
  2336. printer_name: string | null;
  2337. ams_id: number;
  2338. tray_id: number;
  2339. fingerprint_color: string | null;
  2340. fingerprint_type: string | null;
  2341. spool?: InventorySpool | null;
  2342. configured: boolean;
  2343. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  2344. created_at: string;
  2345. ams_label?: string | null; // User-defined friendly name for the AMS unit
  2346. }
  2347. export interface FilamentSkuSettings {
  2348. id: number;
  2349. material: string;
  2350. subtype: string | null;
  2351. brand: string | null;
  2352. lead_time_days: number;
  2353. safety_margin_value: number;
  2354. safety_margin_unit: 'days' | 'g';
  2355. alerts_snoozed: boolean;
  2356. }
  2357. export interface ShoppingListItem {
  2358. id: number;
  2359. material: string;
  2360. subtype: string | null;
  2361. brand: string | null;
  2362. quantity_spools: number;
  2363. note: string | null;
  2364. status: 'pending' | 'purchased' | 'received';
  2365. purchased_at: string | null;
  2366. added_at: string;
  2367. }
  2368. export interface ShoppingListItemCreate {
  2369. material: string;
  2370. subtype: string | null;
  2371. brand: string | null;
  2372. quantity_spools: number;
  2373. note?: string | null;
  2374. }
  2375. // Update types
  2376. export interface VersionInfo {
  2377. version: string;
  2378. repo: string;
  2379. }
  2380. export interface UpdateCheckResult {
  2381. update_available: boolean;
  2382. current_version: string;
  2383. latest_version: string | null;
  2384. release_name?: string;
  2385. release_notes?: string;
  2386. release_url?: string;
  2387. published_at?: string;
  2388. error?: string;
  2389. message?: string;
  2390. is_docker?: boolean;
  2391. is_ha_addon?: boolean;
  2392. update_method?: 'docker' | 'git' | 'ha_addon';
  2393. }
  2394. export interface UpdateStatus {
  2395. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  2396. progress: number;
  2397. message: string;
  2398. error: string | null;
  2399. }
  2400. // Maintenance types
  2401. export interface MaintenanceType {
  2402. id: number;
  2403. name: string;
  2404. description: string | null;
  2405. default_interval_hours: number;
  2406. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  2407. icon: string | null;
  2408. wiki_url: string | null; // Documentation link
  2409. is_system: boolean;
  2410. created_at: string;
  2411. }
  2412. export interface MaintenanceTypeCreate {
  2413. name: string;
  2414. description?: string | null;
  2415. default_interval_hours?: number;
  2416. interval_type?: 'hours' | 'days';
  2417. icon?: string | null;
  2418. wiki_url?: string | null;
  2419. }
  2420. export interface MaintenanceStatus {
  2421. id: number;
  2422. printer_id: number;
  2423. printer_name: string;
  2424. printer_model: string | null;
  2425. maintenance_type_id: number;
  2426. maintenance_type_name: string;
  2427. maintenance_type_icon: string | null;
  2428. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  2429. enabled: boolean;
  2430. interval_hours: number; // For hours type: print hours; for days type: number of days
  2431. interval_type: 'hours' | 'days';
  2432. current_hours: number;
  2433. hours_since_maintenance: number;
  2434. hours_until_due: number;
  2435. days_since_maintenance: number | null; // For days type
  2436. days_until_due: number | null; // For days type
  2437. is_due: boolean;
  2438. is_warning: boolean;
  2439. last_performed_at: string | null;
  2440. }
  2441. export interface PrinterMaintenanceOverview {
  2442. printer_id: number;
  2443. printer_name: string;
  2444. printer_model: string | null;
  2445. total_print_hours: number;
  2446. maintenance_items: MaintenanceStatus[];
  2447. due_count: number;
  2448. warning_count: number;
  2449. }
  2450. export interface MaintenanceHistory {
  2451. id: number;
  2452. printer_maintenance_id: number;
  2453. performed_at: string;
  2454. hours_at_maintenance: number;
  2455. notes: string | null;
  2456. }
  2457. export interface MaintenanceSummary {
  2458. total_due: number;
  2459. total_warning: number;
  2460. printers_with_issues: Array<{
  2461. printer_id: number;
  2462. printer_name: string;
  2463. due_count: number;
  2464. warning_count: number;
  2465. }>;
  2466. }
  2467. // External Links (sidebar)
  2468. export interface ExternalLink {
  2469. id: number;
  2470. name: string;
  2471. url: string;
  2472. icon: string;
  2473. open_in_new_tab: boolean;
  2474. custom_icon: string | null;
  2475. sort_order: number;
  2476. created_at: string;
  2477. updated_at: string;
  2478. }
  2479. export interface ExternalLinkCreate {
  2480. name: string;
  2481. url: string;
  2482. icon: string;
  2483. open_in_new_tab?: boolean;
  2484. }
  2485. export interface ExternalLinkUpdate {
  2486. name?: string;
  2487. url?: string;
  2488. icon?: string;
  2489. open_in_new_tab?: boolean;
  2490. }
  2491. // Permission type - all available permissions
  2492. export type Permission =
  2493. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  2494. | 'archives:read' | 'archives:create'
  2495. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  2496. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  2497. | 'queue:read' | 'queue:create'
  2498. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  2499. | 'queue:reorder'
  2500. | 'library:read' | 'library:upload'
  2501. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  2502. | 'library:purge'
  2503. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  2504. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  2505. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  2506. | 'inventory:forecast_read' | 'inventory:forecast_write'
  2507. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  2508. | 'camera:view'
  2509. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  2510. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  2511. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  2512. | 'notification_templates:read' | 'notification_templates:update'
  2513. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  2514. | 'discovery:scan'
  2515. | 'firmware:read' | 'firmware:update'
  2516. | 'ams_history:read'
  2517. | 'stats:read' | 'stats:filter_by_user'
  2518. | 'system:read'
  2519. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  2520. | 'github:backup' | 'github:restore'
  2521. | 'cloud:auth'
  2522. | 'makerworld:view' | 'makerworld:import'
  2523. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  2524. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  2525. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  2526. | 'websocket:connect';
  2527. // Group types
  2528. export interface GroupBrief {
  2529. id: number;
  2530. name: string;
  2531. }
  2532. export interface Group {
  2533. id: number;
  2534. name: string;
  2535. description: string | null;
  2536. permissions: Permission[];
  2537. is_system: boolean;
  2538. user_count: number;
  2539. created_at: string;
  2540. updated_at: string;
  2541. }
  2542. export interface GroupDetail extends Group {
  2543. users: Array<{ id: number; username: string; is_active: boolean }>;
  2544. }
  2545. export interface GroupCreate {
  2546. name: string;
  2547. description?: string;
  2548. permissions: Permission[];
  2549. }
  2550. export interface GroupUpdate {
  2551. name?: string;
  2552. description?: string;
  2553. permissions?: Permission[];
  2554. }
  2555. export interface PermissionInfo {
  2556. value: Permission;
  2557. label: string;
  2558. }
  2559. export interface PermissionCategory {
  2560. name: string;
  2561. permissions: PermissionInfo[];
  2562. }
  2563. export interface PermissionsListResponse {
  2564. categories: PermissionCategory[];
  2565. all_permissions: Permission[];
  2566. }
  2567. // User email notification preferences
  2568. export interface UserEmailPreferences {
  2569. notify_print_start: boolean;
  2570. notify_print_complete: boolean;
  2571. notify_print_failed: boolean;
  2572. notify_print_stopped: boolean;
  2573. }
  2574. // Auth types
  2575. export interface LoginRequest {
  2576. username: string;
  2577. password: string;
  2578. }
  2579. export interface LoginResponse {
  2580. access_token?: string;
  2581. token_type?: string;
  2582. user?: UserResponse;
  2583. /** Set when 2FA verification is required before a full token is issued. */
  2584. requires_2fa?: boolean;
  2585. pre_auth_token?: string;
  2586. two_fa_methods?: string[];
  2587. }
  2588. export interface UserResponse {
  2589. id: number;
  2590. username: string;
  2591. email?: string;
  2592. role: string; // Deprecated, kept for backward compatibility
  2593. is_active: boolean;
  2594. is_admin: boolean; // Computed from role and group membership
  2595. auth_source: string; // "local" or "ldap"
  2596. groups: GroupBrief[];
  2597. permissions: Permission[]; // All permissions from groups
  2598. created_at: string;
  2599. }
  2600. export interface UserCreate {
  2601. username: string;
  2602. password?: string; // Optional when advanced auth is enabled
  2603. email?: string;
  2604. role: string;
  2605. group_ids?: number[];
  2606. }
  2607. export interface UserUpdate {
  2608. username?: string;
  2609. password?: string;
  2610. email?: string;
  2611. role?: string;
  2612. is_active?: boolean;
  2613. group_ids?: number[];
  2614. }
  2615. export interface SetupRequest {
  2616. auth_enabled: boolean;
  2617. admin_username?: string;
  2618. admin_password?: string;
  2619. }
  2620. export interface ForgotPasswordRequest {
  2621. email: string;
  2622. }
  2623. export interface ForgotPasswordResponse {
  2624. message: string;
  2625. }
  2626. export interface ResetPasswordRequest {
  2627. user_id: number;
  2628. }
  2629. export interface ResetPasswordResponse {
  2630. message: string;
  2631. }
  2632. export interface SMTPSettings {
  2633. smtp_host: string;
  2634. smtp_port: number;
  2635. smtp_username?: string;
  2636. smtp_password?: string;
  2637. smtp_security: 'starttls' | 'ssl' | 'none';
  2638. smtp_auth_enabled: boolean;
  2639. smtp_from_email: string;
  2640. smtp_from_name: string;
  2641. }
  2642. // 2FA / MFA interfaces
  2643. export interface TwoFAStatus {
  2644. totp_enabled: boolean;
  2645. email_otp_enabled: boolean;
  2646. backup_codes_remaining: number;
  2647. }
  2648. export interface TOTPSetupResponse {
  2649. secret: string;
  2650. qr_code_b64: string;
  2651. issuer: string;
  2652. }
  2653. export interface TOTPEnableResponse {
  2654. message: string;
  2655. backup_codes: string[];
  2656. }
  2657. export interface BackupCodesResponse {
  2658. backup_codes: string[];
  2659. message: string;
  2660. }
  2661. export interface TwoFAVerifyRequest {
  2662. pre_auth_token: string;
  2663. code: string;
  2664. method: 'totp' | 'email' | 'backup';
  2665. }
  2666. /**
  2667. * A URL that is known to be same-origin (a relative path starting with ``/``).
  2668. *
  2669. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  2670. * can be distinguished from arbitrary strings at the type level. The brand
  2671. * is compile-time only; at runtime these are plain strings.
  2672. *
  2673. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  2674. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  2675. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  2676. * that no external URL slips through.
  2677. */
  2678. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  2679. // OIDC interfaces
  2680. export interface OIDCProvider {
  2681. id: number;
  2682. name: string;
  2683. issuer_url: string;
  2684. client_id: string;
  2685. scopes: string;
  2686. is_enabled: boolean;
  2687. auto_create_users: boolean;
  2688. auto_link_existing_accounts: boolean;
  2689. email_claim: string;
  2690. require_email_verified: boolean;
  2691. icon_url?: string | null;
  2692. default_group_id?: number | null;
  2693. // True when the backend has cached icon bytes for this provider.
  2694. // Login page / admin preview consume this via the proxy URL
  2695. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  2696. // hotlinks the external icon URL — that would require loosening
  2697. // the strict img-src CSP. Required, not optional: the backend always
  2698. // includes this field in the response (Pydantic default-False is
  2699. // populated unconditionally in the route handler).
  2700. has_icon: boolean;
  2701. }
  2702. export interface OIDCProviderCreate {
  2703. name: string;
  2704. issuer_url: string;
  2705. client_id: string;
  2706. client_secret: string;
  2707. scopes?: string;
  2708. is_enabled?: boolean;
  2709. auto_create_users?: boolean;
  2710. auto_link_existing_accounts?: boolean;
  2711. email_claim?: string;
  2712. require_email_verified?: boolean;
  2713. icon_url?: string | null;
  2714. default_group_id?: number | null;
  2715. }
  2716. export interface OIDCLink {
  2717. id: number;
  2718. provider_id: number;
  2719. provider_name: string;
  2720. provider_email?: string | null;
  2721. created_at: string;
  2722. }
  2723. export interface TestSMTPRequest {
  2724. test_recipient: string;
  2725. }
  2726. export interface TestSMTPResponse {
  2727. success: boolean;
  2728. message: string;
  2729. }
  2730. export interface AdvancedAuthStatus {
  2731. advanced_auth_enabled: boolean;
  2732. smtp_configured: boolean;
  2733. }
  2734. export interface LDAPStatus {
  2735. ldap_enabled: boolean;
  2736. ldap_configured: boolean;
  2737. }
  2738. export interface EncryptionRowCounts {
  2739. oidc_providers: number;
  2740. user_totp: number;
  2741. }
  2742. export interface EncryptionStatus {
  2743. key_configured: boolean;
  2744. key_source: 'env' | 'file' | 'generated' | 'none';
  2745. legacy_plaintext_rows: EncryptionRowCounts;
  2746. encrypted_rows: EncryptionRowCounts;
  2747. decryption_broken: boolean;
  2748. // B2: count of rows skipped during the last legacy re-encryption migration.
  2749. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  2750. migration_error_count: number;
  2751. }
  2752. export interface LDAPTestResponse {
  2753. success: boolean;
  2754. message: string;
  2755. }
  2756. export interface LDAPSearchResult {
  2757. username: string;
  2758. email: string | null;
  2759. display_name: string | null;
  2760. dn: string;
  2761. already_provisioned: boolean;
  2762. }
  2763. export interface SetupResponse {
  2764. auth_enabled: boolean;
  2765. admin_created?: boolean;
  2766. }
  2767. export interface AuthStatus {
  2768. auth_enabled: boolean;
  2769. requires_setup: boolean;
  2770. }
  2771. // API functions
  2772. export const api = {
  2773. // Authentication
  2774. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  2775. setupAuth: (data: SetupRequest) =>
  2776. request<SetupResponse>('/auth/setup', {
  2777. method: 'POST',
  2778. body: JSON.stringify(data),
  2779. }),
  2780. login: (data: LoginRequest) =>
  2781. request<LoginResponse>('/auth/login', {
  2782. method: 'POST',
  2783. body: JSON.stringify(data),
  2784. }),
  2785. logout: () =>
  2786. request<{ message: string }>('/auth/logout', {
  2787. method: 'POST',
  2788. }),
  2789. getCurrentUser: () => request<UserResponse>('/auth/me'),
  2790. disableAuth: () =>
  2791. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  2792. method: 'POST',
  2793. }),
  2794. // Advanced Authentication
  2795. testSMTP: (data: TestSMTPRequest) =>
  2796. request<TestSMTPResponse>('/auth/smtp/test', {
  2797. method: 'POST',
  2798. body: JSON.stringify(data),
  2799. }),
  2800. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  2801. saveSMTPSettings: (data: SMTPSettings) =>
  2802. request<{ message: string }>('/auth/smtp', {
  2803. method: 'POST',
  2804. body: JSON.stringify(data),
  2805. }),
  2806. enableAdvancedAuth: () =>
  2807. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  2808. method: 'POST',
  2809. }),
  2810. disableAdvancedAuth: () =>
  2811. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  2812. method: 'POST',
  2813. }),
  2814. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  2815. // LDAP Authentication
  2816. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  2817. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  2818. testLDAP: () =>
  2819. request<LDAPTestResponse>('/auth/ldap/test', {
  2820. method: 'POST',
  2821. }),
  2822. searchLDAPDirectory: (q: string) =>
  2823. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  2824. provisionLDAPUser: (username: string) =>
  2825. request<UserResponse>('/auth/ldap/provision', {
  2826. method: 'POST',
  2827. body: JSON.stringify({ username }),
  2828. }),
  2829. forgotPassword: (data: ForgotPasswordRequest) =>
  2830. request<ForgotPasswordResponse>('/auth/forgot-password', {
  2831. method: 'POST',
  2832. body: JSON.stringify(data),
  2833. }),
  2834. // H-6: Confirm password reset using the token from the emailed link
  2835. forgotPasswordConfirm: (token: string, newPassword: string) =>
  2836. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  2837. method: 'POST',
  2838. body: JSON.stringify({ token, new_password: newPassword }),
  2839. }),
  2840. resetUserPassword: (data: ResetPasswordRequest) =>
  2841. request<ResetPasswordResponse>('/auth/reset-password', {
  2842. method: 'POST',
  2843. body: JSON.stringify(data),
  2844. }),
  2845. // 2FA - status
  2846. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  2847. // 2FA - TOTP
  2848. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  2849. enableTOTP: (code: string) =>
  2850. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  2851. method: 'POST',
  2852. body: JSON.stringify({ code }),
  2853. }),
  2854. disableTOTP: (code: string) =>
  2855. request<{ message: string }>('/auth/2fa/totp/disable', {
  2856. method: 'POST',
  2857. body: JSON.stringify({ code }),
  2858. }),
  2859. regenerateBackupCodes: (code: string) =>
  2860. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  2861. method: 'POST',
  2862. body: JSON.stringify({ code }),
  2863. }),
  2864. // 2FA - Email OTP
  2865. // Step 1: send a verification code to the user's email (proof of possession)
  2866. enableEmailOTP: () =>
  2867. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  2868. // Step 2: confirm with the code received by email
  2869. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  2870. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  2871. method: 'POST',
  2872. body: JSON.stringify({ setup_token, code }),
  2873. }),
  2874. // Disable requires account password for re-auth
  2875. disableEmailOTP: (password: string) =>
  2876. request<{ message: string }>('/auth/2fa/email/disable', {
  2877. method: 'POST',
  2878. body: JSON.stringify({ password }),
  2879. }),
  2880. sendEmailOTP: (preAuthToken: string) =>
  2881. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  2882. method: 'POST',
  2883. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  2884. }),
  2885. // 2FA - verify (completes login)
  2886. verify2FA: (data: TwoFAVerifyRequest) =>
  2887. request<LoginResponse>('/auth/2fa/verify', {
  2888. method: 'POST',
  2889. body: JSON.stringify(data),
  2890. }),
  2891. // 2FA - admin
  2892. admin2FADisable: (userId: number) =>
  2893. request<{ message: string }>(`/auth/2fa/admin/${userId}`, { method: 'DELETE' }),
  2894. // OIDC providers (public list)
  2895. getOIDCProviders: () => request<OIDCProvider[]>('/auth/oidc/providers'),
  2896. // OIDC providers (admin)
  2897. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  2898. createOIDCProvider: (data: OIDCProviderCreate) =>
  2899. request<OIDCProvider>('/auth/oidc/providers', {
  2900. method: 'POST',
  2901. body: JSON.stringify(data),
  2902. }),
  2903. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  2904. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  2905. method: 'PUT',
  2906. body: JSON.stringify(data),
  2907. }),
  2908. deleteOIDCProvider: (id: number) =>
  2909. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  2910. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  2911. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  2912. // so a future caller can't accidentally substitute an attacker-
  2913. // controlled URL where this is consumed.
  2914. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  2915. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  2916. deleteOIDCProviderIcon: (id: number) =>
  2917. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  2918. refreshOIDCProviderIcon: (id: number) =>
  2919. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  2920. // OIDC authorize URL
  2921. getOIDCAuthorizeUrl: (providerId: number) =>
  2922. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  2923. // OIDC exchange token for JWT
  2924. exchangeOIDCToken: (oidcToken: string) =>
  2925. request<LoginResponse>('/auth/oidc/exchange', {
  2926. method: 'POST',
  2927. body: JSON.stringify({ oidc_token: oidcToken }),
  2928. }),
  2929. // OIDC links for current user
  2930. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  2931. deleteOIDCLink: (providerId: number) =>
  2932. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  2933. // Users
  2934. getUsers: () => request<UserResponse[]>('/users/'),
  2935. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  2936. createUser: (data: UserCreate) =>
  2937. request<UserResponse>('/users/', {
  2938. method: 'POST',
  2939. body: JSON.stringify(data),
  2940. }),
  2941. updateUser: (id: number, data: UserUpdate) =>
  2942. request<UserResponse>(`/users/${id}`, {
  2943. method: 'PATCH',
  2944. body: JSON.stringify(data),
  2945. }),
  2946. deleteUser: (id: number, deleteItems: boolean = false) =>
  2947. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  2948. method: 'DELETE',
  2949. }),
  2950. getUserItemsCount: (id: number) =>
  2951. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  2952. changePassword: (currentPassword: string, newPassword: string) =>
  2953. request<{ message: string }>('/users/me/change-password', {
  2954. method: 'POST',
  2955. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  2956. }),
  2957. // User Email Notifications
  2958. getUserEmailPreferences: () =>
  2959. request<UserEmailPreferences>('/user-notifications/preferences'),
  2960. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  2961. request<UserEmailPreferences>('/user-notifications/preferences', {
  2962. method: 'PUT',
  2963. body: JSON.stringify(data),
  2964. }),
  2965. // Groups
  2966. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  2967. getGroups: () => request<Group[]>('/groups/'),
  2968. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  2969. createGroup: (data: GroupCreate) =>
  2970. request<Group>('/groups/', {
  2971. method: 'POST',
  2972. body: JSON.stringify(data),
  2973. }),
  2974. updateGroup: (id: number, data: GroupUpdate) =>
  2975. request<Group>(`/groups/${id}`, {
  2976. method: 'PATCH',
  2977. body: JSON.stringify(data),
  2978. }),
  2979. deleteGroup: (id: number) =>
  2980. request<void>(`/groups/${id}`, {
  2981. method: 'DELETE',
  2982. }),
  2983. addUserToGroup: (groupId: number, userId: number) =>
  2984. request<void>(`/groups/${groupId}/users/${userId}`, {
  2985. method: 'POST',
  2986. }),
  2987. removeUserFromGroup: (groupId: number, userId: number) =>
  2988. request<void>(`/groups/${groupId}/users/${userId}`, {
  2989. method: 'DELETE',
  2990. }),
  2991. // Printers
  2992. getPrinters: () => request<Printer[]>('/printers/'),
  2993. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  2994. createPrinter: (data: PrinterCreate) =>
  2995. request<Printer>('/printers/', {
  2996. method: 'POST',
  2997. body: JSON.stringify(data),
  2998. }),
  2999. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  3000. request<Printer>(`/printers/${id}`, {
  3001. method: 'PATCH',
  3002. body: JSON.stringify(data),
  3003. }),
  3004. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  3005. request<{ status: string; archives_deleted: boolean }>(
  3006. `/printers/${id}?delete_archives=${deleteArchives}`,
  3007. { method: 'DELETE' }
  3008. ),
  3009. getDeveloperModeWarnings: () =>
  3010. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  3011. getAvailableFilaments: (model: string, location?: string) => {
  3012. const params = new URLSearchParams({ model });
  3013. if (location) params.set('location', location);
  3014. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  3015. },
  3016. getPrinterStatus: (id: number) =>
  3017. request<PrinterStatus>(`/printers/${id}/status`),
  3018. refreshPrinterStatus: (id: number) =>
  3019. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  3020. method: 'POST',
  3021. }),
  3022. connectPrinter: (id: number) =>
  3023. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  3024. method: 'POST',
  3025. }),
  3026. disconnectPrinter: (id: number) =>
  3027. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  3028. method: 'POST',
  3029. }),
  3030. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  3031. request<{ success: boolean; error?: string; resolution?: string }>(
  3032. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  3033. { method: 'POST' }
  3034. ),
  3035. // Print Control
  3036. stopPrint: (printerId: number) =>
  3037. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  3038. method: 'POST',
  3039. }),
  3040. pausePrint: (printerId: number) =>
  3041. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  3042. method: 'POST',
  3043. }),
  3044. resumePrint: (printerId: number) =>
  3045. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  3046. method: 'POST',
  3047. }),
  3048. clearPlate: (printerId: number) =>
  3049. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  3050. method: 'POST',
  3051. }),
  3052. // Get current print user (for reprint tracking - Issue #206)
  3053. getCurrentPrintUser: (printerId: number) =>
  3054. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  3055. // Print Speed Control
  3056. setPrintSpeed: (printerId: number, mode: number) =>
  3057. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  3058. method: 'POST',
  3059. }),
  3060. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  3061. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  3062. method: 'POST',
  3063. }),
  3064. // Bed (Z-axis) jog
  3065. bedJog: (printerId: number, distance: number, force: boolean = false) =>
  3066. request<{ success: boolean; message: string }>(
  3067. `/printers/${printerId}/bed-jog?distance=${distance}&force=${force}`,
  3068. { method: 'POST' }
  3069. ),
  3070. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  3071. request<{ success: boolean; message: string }>(
  3072. `/printers/${printerId}/home-axes?axes=${axes}`,
  3073. { method: 'POST' }
  3074. ),
  3075. // Chamber Light Control
  3076. setChamberLight: (printerId: number, on: boolean) =>
  3077. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  3078. method: 'POST',
  3079. }),
  3080. // AMS Drying Control
  3081. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  3082. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  3083. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  3084. { method: 'POST' }
  3085. ),
  3086. stopDrying: (printerId: number, amsId: number) =>
  3087. request<{ status: string; ams_id: number }>(
  3088. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  3089. { method: 'POST' }
  3090. ),
  3091. // Skip Objects
  3092. getPrintableObjects: (printerId: number) =>
  3093. request<{
  3094. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  3095. total: number;
  3096. skipped_count: number;
  3097. is_printing: boolean;
  3098. bbox_all: [number, number, number, number] | null;
  3099. }>(`/printers/${printerId}/print/objects`),
  3100. skipObjects: (printerId: number, objectIds: number[]) =>
  3101. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  3102. `/printers/${printerId}/print/skip-objects`,
  3103. {
  3104. method: 'POST',
  3105. body: JSON.stringify(objectIds),
  3106. }
  3107. ),
  3108. // HMS Errors
  3109. clearHMSErrors: (printerId: number) =>
  3110. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  3111. // AMS Control
  3112. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  3113. request<{ success: boolean; message: string }>(
  3114. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  3115. { method: 'POST' }
  3116. ),
  3117. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 254 for external spool.
  3118. loadAmsTray: (printerId: number, trayId: number) =>
  3119. request<{ success: boolean; message: string }>(
  3120. `/printers/${printerId}/ams/load?tray_id=${trayId}`,
  3121. { method: 'POST' }
  3122. ),
  3123. // Unload the currently loaded filament.
  3124. unloadAms: (printerId: number) =>
  3125. request<{ success: boolean; message: string }>(
  3126. `/printers/${printerId}/ams/unload`,
  3127. { method: 'POST' }
  3128. ),
  3129. // MQTT Debug Logging
  3130. enableMQTTLogging: (printerId: number) =>
  3131. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  3132. method: 'POST',
  3133. }),
  3134. disableMQTTLogging: (printerId: number) =>
  3135. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  3136. method: 'POST',
  3137. }),
  3138. getMQTTLogs: (printerId: number) =>
  3139. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  3140. clearMQTTLogs: (printerId: number) =>
  3141. request<{ status: string }>(`/printers/${printerId}/logging`, {
  3142. method: 'DELETE',
  3143. }),
  3144. // Printer File Manager
  3145. getPrinterFiles: (printerId: number, path = '/') =>
  3146. request<{
  3147. path: string;
  3148. files: Array<{
  3149. name: string;
  3150. is_directory: boolean;
  3151. size: number;
  3152. path: string;
  3153. mtime?: string;
  3154. }>;
  3155. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  3156. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  3157. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3158. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  3159. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  3160. getPrinterFilePlates: (printerId: number, path: string) =>
  3161. request<{
  3162. printer_id: number;
  3163. path: string;
  3164. filename: string;
  3165. plates: Array<{
  3166. index: number;
  3167. name: string | null;
  3168. objects: string[];
  3169. has_thumbnail: boolean;
  3170. thumbnail_url: string | null;
  3171. print_time_seconds: number | null;
  3172. filament_used_grams: number | null;
  3173. filaments: Array<{
  3174. slot_id: number;
  3175. type: string;
  3176. color: string;
  3177. used_grams: number;
  3178. used_meters: number;
  3179. }>;
  3180. }>;
  3181. is_multi_plate: boolean;
  3182. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  3183. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  3184. withStreamToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  3185. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  3186. const headers: Record<string, string> = {};
  3187. if (authToken) {
  3188. headers['Authorization'] = `Bearer ${authToken}`;
  3189. }
  3190. const response = await fetch(
  3191. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3192. { headers }
  3193. );
  3194. if (!response.ok) {
  3195. const error = await response.json().catch(() => ({}));
  3196. throw new Error(error.detail || `HTTP ${response.status}`);
  3197. }
  3198. const disposition = response.headers.get('Content-Disposition');
  3199. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  3200. const blob = await response.blob();
  3201. const url = window.URL.createObjectURL(blob);
  3202. const a = document.createElement('a');
  3203. a.href = url;
  3204. a.download = filename;
  3205. document.body.appendChild(a);
  3206. a.click();
  3207. document.body.removeChild(a);
  3208. window.URL.revokeObjectURL(url);
  3209. },
  3210. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  3211. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  3212. if (authToken) {
  3213. headers['Authorization'] = `Bearer ${authToken}`;
  3214. }
  3215. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  3216. method: 'POST',
  3217. headers,
  3218. body: JSON.stringify({ paths }),
  3219. });
  3220. if (!response.ok) {
  3221. const error = await response.json().catch(() => ({}));
  3222. throw new Error(error.detail || `HTTP ${response.status}`);
  3223. }
  3224. return response.blob();
  3225. },
  3226. deletePrinterFile: (printerId: number, path: string) =>
  3227. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  3228. method: 'DELETE',
  3229. }),
  3230. getPrinterStorage: (printerId: number) =>
  3231. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  3232. // Archives
  3233. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  3234. const params = new URLSearchParams();
  3235. if (printerId) params.set('printer_id', String(printerId));
  3236. if (projectId) params.set('project_id', String(projectId));
  3237. params.set('limit', String(limit));
  3238. params.set('offset', String(offset));
  3239. if (dateFrom) params.set('date_from', dateFrom);
  3240. if (dateTo) params.set('date_to', dateTo);
  3241. return request<Archive[]>(`/archives/?${params}`);
  3242. },
  3243. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  3244. const params = new URLSearchParams();
  3245. if (dateFrom) params.set('date_from', dateFrom);
  3246. if (dateTo) params.set('date_to', dateTo);
  3247. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  3248. const qs = params.toString();
  3249. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  3250. },
  3251. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  3252. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  3253. searchArchives: (query: string, options?: {
  3254. printerId?: number;
  3255. projectId?: number;
  3256. status?: string;
  3257. limit?: number;
  3258. offset?: number;
  3259. }) => {
  3260. const params = new URLSearchParams();
  3261. params.set('q', query);
  3262. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3263. if (options?.projectId) params.set('project_id', String(options.projectId));
  3264. if (options?.status) params.set('status', options.status);
  3265. if (options?.limit) params.set('limit', String(options.limit));
  3266. if (options?.offset) params.set('offset', String(options.offset));
  3267. return request<Archive[]>(`/archives/search?${params}`);
  3268. },
  3269. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  3270. updateArchive: (id: number, data: {
  3271. printer_id?: number | null;
  3272. project_id?: number | null;
  3273. print_name?: string;
  3274. is_favorite?: boolean;
  3275. tags?: string;
  3276. notes?: string;
  3277. cost?: number;
  3278. failure_reason?: string | null;
  3279. status?: string;
  3280. quantity?: number;
  3281. external_url?: string | null;
  3282. }) =>
  3283. request<Archive>(`/archives/${id}`, {
  3284. method: 'PATCH',
  3285. body: JSON.stringify(data),
  3286. }),
  3287. toggleFavorite: (id: number) =>
  3288. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  3289. // Soft-deletes by default (#1343): files removed from disk, row hidden
  3290. // from listings, but its filament / time / cost / energy contribution
  3291. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  3292. // row from statistics too.
  3293. deleteArchive: (id: number, purgeStats: boolean = false) =>
  3294. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  3295. // ========== Archive auto-purge (#1008 follow-up) ==========
  3296. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3297. request<ArchivePurgePreview>(
  3298. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  3299. ),
  3300. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  3301. // preserved, files removed from disk, row hidden via deleted_at. true matches
  3302. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  3303. // linked PrintLogEntry rows so the contribution drops from /stats too).
  3304. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3305. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  3306. method: 'POST',
  3307. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  3308. }),
  3309. getArchivePurgeSettings: () =>
  3310. request<ArchivePurgeSettings>('/archives/purge/settings'),
  3311. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  3312. request<ArchivePurgeSettings>('/archives/purge/settings', {
  3313. method: 'PUT',
  3314. body: JSON.stringify(body),
  3315. }),
  3316. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  3317. const params = new URLSearchParams();
  3318. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3319. if (options?.dateTo) params.set('date_to', options.dateTo);
  3320. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3321. const qs = params.toString();
  3322. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  3323. },
  3324. // Tag management
  3325. getTags: () => request<TagInfo[]>('/archives/tags'),
  3326. renameTag: (oldName: string, newName: string) =>
  3327. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  3328. method: 'PUT',
  3329. body: JSON.stringify({ new_name: newName }),
  3330. }),
  3331. deleteTag: (name: string) =>
  3332. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  3333. method: 'DELETE',
  3334. }),
  3335. recalculateCosts: () =>
  3336. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  3337. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  3338. const params = new URLSearchParams();
  3339. if (options?.days) params.set('days', String(options.days));
  3340. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3341. if (options?.dateTo) params.set('date_to', options.dateTo);
  3342. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3343. if (options?.projectId) params.set('project_id', String(options.projectId));
  3344. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3345. const qs = params.toString();
  3346. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  3347. },
  3348. compareArchives: (archiveIds: number[]) =>
  3349. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  3350. findSimilarArchives: (archiveId: number, limit = 10) =>
  3351. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  3352. exportArchives: async (options?: {
  3353. format?: 'csv' | 'xlsx';
  3354. fields?: string[];
  3355. printerId?: number;
  3356. projectId?: number;
  3357. status?: string;
  3358. dateFrom?: string;
  3359. dateTo?: string;
  3360. search?: string;
  3361. }): Promise<{ blob: Blob; filename: string }> => {
  3362. const params = new URLSearchParams();
  3363. if (options?.format) params.set('format', options.format);
  3364. if (options?.fields) params.set('fields', options.fields.join(','));
  3365. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3366. if (options?.projectId) params.set('project_id', String(options.projectId));
  3367. if (options?.status) params.set('status', options.status);
  3368. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3369. if (options?.dateTo) params.set('date_to', options.dateTo);
  3370. if (options?.search) params.set('search', options.search);
  3371. const headers: Record<string, string> = {};
  3372. if (authToken) {
  3373. headers['Authorization'] = `Bearer ${authToken}`;
  3374. }
  3375. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  3376. if (!response.ok) {
  3377. const error = await response.json().catch(() => ({}));
  3378. throw new Error(error.detail || `HTTP ${response.status}`);
  3379. }
  3380. const contentDisposition = response.headers.get('Content-Disposition');
  3381. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  3382. if (contentDisposition) {
  3383. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3384. if (match) filename = match[1];
  3385. }
  3386. const blob = await response.blob();
  3387. return { blob, filename };
  3388. },
  3389. exportStats: async (options?: {
  3390. format?: 'csv' | 'xlsx';
  3391. days?: number;
  3392. printerId?: number;
  3393. projectId?: number;
  3394. createdById?: number;
  3395. }): Promise<{ blob: Blob; filename: string }> => {
  3396. const params = new URLSearchParams();
  3397. if (options?.format) params.set('format', options.format);
  3398. if (options?.days) params.set('days', String(options.days));
  3399. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3400. if (options?.projectId) params.set('project_id', String(options.projectId));
  3401. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3402. const headers: Record<string, string> = {};
  3403. if (authToken) {
  3404. headers['Authorization'] = `Bearer ${authToken}`;
  3405. }
  3406. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  3407. if (!response.ok) {
  3408. const error = await response.json().catch(() => ({}));
  3409. throw new Error(error.detail || `HTTP ${response.status}`);
  3410. }
  3411. const contentDisposition = response.headers.get('Content-Disposition');
  3412. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  3413. if (contentDisposition) {
  3414. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3415. if (match) filename = match[1];
  3416. }
  3417. const blob = await response.blob();
  3418. return { blob, filename };
  3419. },
  3420. getArchiveDuplicates: (id: number) =>
  3421. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  3422. backfillContentHashes: () =>
  3423. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  3424. method: 'POST',
  3425. }),
  3426. getArchiveThumbnail: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  3427. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  3428. withStreamToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  3429. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  3430. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  3431. const headers: Record<string, string> = {};
  3432. if (authToken) {
  3433. headers['Authorization'] = `Bearer ${authToken}`;
  3434. }
  3435. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  3436. if (!response.ok) {
  3437. const error = await response.json().catch(() => ({}));
  3438. throw new Error(error.detail || `HTTP ${response.status}`);
  3439. }
  3440. const disposition = response.headers.get('Content-Disposition');
  3441. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  3442. const blob = await response.blob();
  3443. const url = window.URL.createObjectURL(blob);
  3444. const a = document.createElement('a');
  3445. a.href = url;
  3446. a.download = downloadFilename;
  3447. document.body.appendChild(a);
  3448. a.click();
  3449. document.body.removeChild(a);
  3450. window.URL.revokeObjectURL(url);
  3451. },
  3452. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  3453. getArchivePlatePreview: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/plate-preview`),
  3454. getArchiveTimelapse: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  3455. scanArchiveTimelapse: (id: number) =>
  3456. request<{
  3457. status: string;
  3458. message: string;
  3459. filename?: string;
  3460. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  3461. }>(`/archives/${id}/timelapse/scan`, {
  3462. method: 'POST',
  3463. }),
  3464. selectArchiveTimelapse: (id: number, filename: string) =>
  3465. request<{ status: string; message: string; filename: string }>(
  3466. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  3467. { method: 'POST' }
  3468. ),
  3469. deleteArchiveTimelapse: (id: number) =>
  3470. request<{ status: string }>(`/archives/${id}/timelapse`, {
  3471. method: 'DELETE',
  3472. }),
  3473. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3474. const formData = new FormData();
  3475. formData.append('file', file);
  3476. const headers: Record<string, string> = {};
  3477. if (authToken) {
  3478. headers['Authorization'] = `Bearer ${authToken}`;
  3479. }
  3480. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  3481. method: 'POST',
  3482. headers,
  3483. body: formData,
  3484. });
  3485. if (!response.ok) {
  3486. const error = await response.json().catch(() => ({}));
  3487. throw new Error(error.detail || `HTTP ${response.status}`);
  3488. }
  3489. return response.json();
  3490. },
  3491. // Timelapse Editor
  3492. getTimelapseInfo: (archiveId: number) =>
  3493. request<{
  3494. duration: number;
  3495. width: number;
  3496. height: number;
  3497. fps: number;
  3498. codec: string;
  3499. file_size: number;
  3500. has_audio: boolean;
  3501. }>(`/archives/${archiveId}/timelapse/info`),
  3502. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  3503. request<{
  3504. thumbnails: string[];
  3505. timestamps: number[];
  3506. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  3507. processTimelapse: async (
  3508. archiveId: number,
  3509. params: {
  3510. trimStart?: number;
  3511. trimEnd?: number;
  3512. speed?: number;
  3513. saveMode: 'replace' | 'new';
  3514. outputFilename?: string;
  3515. },
  3516. audioFile?: File
  3517. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  3518. const formData = new FormData();
  3519. formData.append('trim_start', String(params.trimStart ?? 0));
  3520. if (params.trimEnd !== undefined) {
  3521. formData.append('trim_end', String(params.trimEnd));
  3522. }
  3523. formData.append('speed', String(params.speed ?? 1));
  3524. formData.append('save_mode', params.saveMode);
  3525. if (params.outputFilename) {
  3526. formData.append('output_filename', params.outputFilename);
  3527. }
  3528. if (audioFile) {
  3529. formData.append('audio', audioFile);
  3530. }
  3531. const headers: Record<string, string> = {};
  3532. if (authToken) {
  3533. headers['Authorization'] = `Bearer ${authToken}`;
  3534. }
  3535. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  3536. method: 'POST',
  3537. headers,
  3538. body: formData,
  3539. });
  3540. if (!response.ok) {
  3541. const error = await response.json().catch(() => ({}));
  3542. throw new Error(error.detail || `HTTP ${response.status}`);
  3543. }
  3544. return response.json();
  3545. },
  3546. // Photos
  3547. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  3548. withStreamToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  3549. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  3550. const formData = new FormData();
  3551. formData.append('file', file);
  3552. const headers: Record<string, string> = {};
  3553. if (authToken) {
  3554. headers['Authorization'] = `Bearer ${authToken}`;
  3555. }
  3556. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  3557. headers,
  3558. method: 'POST',
  3559. body: formData,
  3560. });
  3561. if (!response.ok) {
  3562. const error = await response.json().catch(() => ({}));
  3563. throw new Error(error.detail || `HTTP ${response.status}`);
  3564. }
  3565. return response.json();
  3566. },
  3567. deleteArchivePhoto: (archiveId: number, filename: string) =>
  3568. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  3569. method: 'DELETE',
  3570. }),
  3571. // Source 3MF (original slicer project file)
  3572. getSource3mfDownloadUrl: (archiveId: number) =>
  3573. `${API_BASE}/archives/${archiveId}/source`,
  3574. downloadSource3mf: async (archiveId: number): Promise<void> => {
  3575. const headers: Record<string, string> = {};
  3576. if (authToken) {
  3577. headers['Authorization'] = `Bearer ${authToken}`;
  3578. }
  3579. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  3580. if (!response.ok) {
  3581. const error = await response.json().catch(() => ({}));
  3582. throw new Error(error.detail || `HTTP ${response.status}`);
  3583. }
  3584. const disposition = response.headers.get('Content-Disposition');
  3585. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  3586. const blob = await response.blob();
  3587. const url = window.URL.createObjectURL(blob);
  3588. const a = document.createElement('a');
  3589. a.href = url;
  3590. a.download = filename;
  3591. document.body.appendChild(a);
  3592. a.click();
  3593. document.body.removeChild(a);
  3594. window.URL.revokeObjectURL(url);
  3595. },
  3596. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  3597. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  3598. const safe = filename.replace(/[/\\?#]/g, '_');
  3599. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3600. },
  3601. createSourceSlicerToken: (archiveId: number) =>
  3602. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  3603. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3604. const safe = filename.replace(/[/\\?#]/g, '_');
  3605. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3606. },
  3607. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3608. const formData = new FormData();
  3609. formData.append('file', file);
  3610. const headers: Record<string, string> = {};
  3611. if (authToken) {
  3612. headers['Authorization'] = `Bearer ${authToken}`;
  3613. }
  3614. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  3615. method: 'POST',
  3616. headers,
  3617. body: formData,
  3618. });
  3619. if (!response.ok) {
  3620. const error = await response.json().catch(() => ({}));
  3621. throw new Error(error.detail || `HTTP ${response.status}`);
  3622. }
  3623. return response.json();
  3624. },
  3625. deleteSource3mf: (archiveId: number) =>
  3626. request<{ status: string }>(`/archives/${archiveId}/source`, {
  3627. method: 'DELETE',
  3628. }),
  3629. // F3D (Fusion 360 design file)
  3630. getF3dDownloadUrl: (archiveId: number) =>
  3631. `${API_BASE}/archives/${archiveId}/f3d`,
  3632. downloadF3d: async (archiveId: number): Promise<void> => {
  3633. const headers: Record<string, string> = {};
  3634. if (authToken) {
  3635. headers['Authorization'] = `Bearer ${authToken}`;
  3636. }
  3637. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  3638. if (!response.ok) {
  3639. const error = await response.json().catch(() => ({}));
  3640. throw new Error(error.detail || `HTTP ${response.status}`);
  3641. }
  3642. const disposition = response.headers.get('Content-Disposition');
  3643. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  3644. const blob = await response.blob();
  3645. const url = window.URL.createObjectURL(blob);
  3646. const a = document.createElement('a');
  3647. a.href = url;
  3648. a.download = filename;
  3649. document.body.appendChild(a);
  3650. a.click();
  3651. document.body.removeChild(a);
  3652. window.URL.revokeObjectURL(url);
  3653. },
  3654. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3655. const formData = new FormData();
  3656. formData.append('file', file);
  3657. const headers: Record<string, string> = {};
  3658. if (authToken) {
  3659. headers['Authorization'] = `Bearer ${authToken}`;
  3660. }
  3661. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  3662. method: 'POST',
  3663. headers,
  3664. body: formData,
  3665. });
  3666. if (!response.ok) {
  3667. const error = await response.json().catch(() => ({}));
  3668. throw new Error(error.detail || `HTTP ${response.status}`);
  3669. }
  3670. return response.json();
  3671. },
  3672. deleteF3d: (archiveId: number) =>
  3673. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  3674. method: 'DELETE',
  3675. }),
  3676. // QR Code
  3677. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  3678. withStreamToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  3679. getArchiveCapabilities: (id: number) =>
  3680. request<{
  3681. has_model: boolean;
  3682. has_gcode: boolean;
  3683. has_source: boolean;
  3684. build_volume: { x: number; y: number; z: number };
  3685. filament_colors: string[];
  3686. }>(`/archives/${id}/capabilities`),
  3687. // Project Page
  3688. getArchiveProjectPage: (id: number) =>
  3689. request<{
  3690. title: string | null;
  3691. description: string | null;
  3692. designer: string | null;
  3693. designer_user_id: string | null;
  3694. license: string | null;
  3695. copyright: string | null;
  3696. creation_date: string | null;
  3697. modification_date: string | null;
  3698. origin: string | null;
  3699. profile_title: string | null;
  3700. profile_description: string | null;
  3701. profile_cover: string | null;
  3702. profile_user_id: string | null;
  3703. profile_user_name: string | null;
  3704. design_model_id: string | null;
  3705. design_profile_id: string | null;
  3706. design_region: string | null;
  3707. model_pictures: Array<{ name: string; path: string; url: string }>;
  3708. profile_pictures: Array<{ name: string; path: string; url: string }>;
  3709. thumbnails: Array<{ name: string; path: string; url: string }>;
  3710. }>(`/archives/${id}/project-page`),
  3711. updateArchiveProjectPage: (id: number, data: {
  3712. title?: string;
  3713. description?: string;
  3714. designer?: string;
  3715. license?: string;
  3716. copyright?: string;
  3717. profile_title?: string;
  3718. profile_description?: string;
  3719. }) =>
  3720. request(`/archives/${id}/project-page`, {
  3721. method: 'PATCH',
  3722. body: JSON.stringify(data),
  3723. }),
  3724. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  3725. withStreamToken(`${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`),
  3726. getArchiveForSlicer: (id: number, filename: string) => {
  3727. const safe = filename.replace(/[/\\?#]/g, '_');
  3728. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3729. },
  3730. createArchiveSlicerToken: (archiveId: number) =>
  3731. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  3732. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3733. const safe = filename.replace(/[/\\?#]/g, '_');
  3734. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3735. },
  3736. getArchivePlates: (archiveId: number) =>
  3737. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  3738. getArchiveFilamentRequirements: (
  3739. archiveId: number,
  3740. plateId?: number,
  3741. requestId?: string,
  3742. // Optional bundle context: when supplied, the backend's preview slice
  3743. // (run for unsliced project files) uses slice_with_bundle so gram
  3744. // numbers reflect the same triplet the real print will use. All four
  3745. // fields must be set for the bundle path to engage; partial context
  3746. // falls back to the embedded-settings preview without erroring.
  3747. bundle?: {
  3748. bundle_id: string;
  3749. printer_name: string;
  3750. process_name: string;
  3751. filament_names: string[];
  3752. },
  3753. ) => {
  3754. const qs = new URLSearchParams();
  3755. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  3756. if (requestId) qs.set('request_id', requestId);
  3757. if (bundle) {
  3758. qs.set('bundle_id', bundle.bundle_id);
  3759. qs.set('printer_name', bundle.printer_name);
  3760. qs.set('process_name', bundle.process_name);
  3761. qs.set('filament_names', bundle.filament_names.join(';'));
  3762. }
  3763. return request<{
  3764. archive_id: number;
  3765. filename: string;
  3766. plate_id: number | null;
  3767. filaments: Array<{
  3768. slot_id: number;
  3769. type: string;
  3770. color: string;
  3771. used_grams: number;
  3772. used_meters: number;
  3773. used_in_plate?: boolean;
  3774. }>;
  3775. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  3776. },
  3777. reprintArchive: (
  3778. archiveId: number,
  3779. printerId: number,
  3780. options?: {
  3781. plate_id?: number;
  3782. plate_name?: string;
  3783. ams_mapping?: number[];
  3784. timelapse?: boolean;
  3785. bed_levelling?: boolean;
  3786. flow_cali?: boolean;
  3787. vibration_cali?: boolean;
  3788. layer_inspect?: boolean;
  3789. use_ams?: boolean;
  3790. }
  3791. ) =>
  3792. request<BackgroundDispatchResponse>(
  3793. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  3794. {
  3795. method: 'POST',
  3796. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  3797. body: options ? JSON.stringify(options) : undefined,
  3798. }
  3799. ),
  3800. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  3801. const formData = new FormData();
  3802. formData.append('file', file);
  3803. const url = printerId
  3804. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  3805. : `${API_BASE}/archives/upload`;
  3806. const headers: Record<string, string> = {};
  3807. if (authToken) {
  3808. headers['Authorization'] = `Bearer ${authToken}`;
  3809. }
  3810. const response = await fetch(url, {
  3811. method: 'POST',
  3812. headers,
  3813. body: formData,
  3814. });
  3815. if (!response.ok) {
  3816. const error = await response.json().catch(() => ({}));
  3817. throw new Error(error.detail || `HTTP ${response.status}`);
  3818. }
  3819. return response.json();
  3820. },
  3821. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  3822. const formData = new FormData();
  3823. files.forEach((file) => formData.append('files', file));
  3824. const url = printerId
  3825. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  3826. : `${API_BASE}/archives/upload-bulk`;
  3827. const headers: Record<string, string> = {};
  3828. if (authToken) {
  3829. headers['Authorization'] = `Bearer ${authToken}`;
  3830. }
  3831. const response = await fetch(url, {
  3832. method: 'POST',
  3833. headers,
  3834. body: formData,
  3835. });
  3836. if (!response.ok) {
  3837. const error = await response.json().catch(() => ({}));
  3838. throw new Error(error.detail || `HTTP ${response.status}`);
  3839. }
  3840. return response.json();
  3841. },
  3842. // Print Log
  3843. getPrintLog: (params?: {
  3844. search?: string;
  3845. printerId?: number;
  3846. username?: string;
  3847. status?: string;
  3848. dateFrom?: string;
  3849. dateTo?: string;
  3850. limit?: number;
  3851. offset?: number;
  3852. }) => {
  3853. const searchParams = new URLSearchParams();
  3854. if (params?.search) searchParams.set('search', params.search);
  3855. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  3856. if (params?.username) searchParams.set('created_by_username', params.username);
  3857. if (params?.status) searchParams.set('status', params.status);
  3858. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  3859. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  3860. if (params?.limit) searchParams.set('limit', String(params.limit));
  3861. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  3862. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  3863. },
  3864. getPrintLogThumbnail: (id: number) => withStreamToken(`${API_BASE}/print-log/${id}/thumbnail`),
  3865. clearPrintLog: () =>
  3866. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  3867. // Settings
  3868. getSettings: () => request<AppSettings>('/settings/'),
  3869. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  3870. // Public subset of settings for UI rendering — no settings:read required.
  3871. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  3872. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  3873. // backend/app/api/routes/settings.py.
  3874. getUiPreferences: () =>
  3875. request<{
  3876. require_plate_clear?: boolean;
  3877. check_printer_firmware?: boolean;
  3878. camera_view_mode?: 'window' | 'embedded';
  3879. time_format?: 'system' | '12h' | '24h';
  3880. date_format?: string;
  3881. drying_presets?: string;
  3882. ams_humidity_good?: number;
  3883. ams_humidity_fair?: number;
  3884. ams_temp_good?: number;
  3885. ams_temp_fair?: number;
  3886. bed_cooled_threshold?: number;
  3887. }>('/settings/ui-preferences'),
  3888. updateSettings: (data: AppSettingsUpdate) =>
  3889. request<AppSettings>('/settings/', {
  3890. method: 'PUT',
  3891. body: JSON.stringify(data),
  3892. }),
  3893. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  3894. resetSettings: () =>
  3895. request<AppSettings>('/settings/reset', { method: 'POST' }),
  3896. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  3897. // New simplified backup - complete database + all files
  3898. const url = `${API_BASE}/settings/backup`;
  3899. const headers: Record<string, string> = {};
  3900. if (authToken) {
  3901. headers['Authorization'] = `Bearer ${authToken}`;
  3902. }
  3903. const response = await fetch(url, { headers });
  3904. // Check for errors
  3905. if (!response.ok) {
  3906. const errorText = await response.text();
  3907. throw new Error(errorText || `Backup failed with status ${response.status}`);
  3908. }
  3909. // Get filename from Content-Disposition header
  3910. const contentDisposition = response.headers.get('Content-Disposition');
  3911. let filename = 'bambuddy-backup.zip';
  3912. if (contentDisposition) {
  3913. const match = contentDisposition.match(/filename=([^;]+)/);
  3914. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  3915. }
  3916. const blob = await response.blob();
  3917. return { blob, filename };
  3918. },
  3919. importBackup: async (file: File) => {
  3920. // New simplified restore - replaces database + all directories
  3921. const formData = new FormData();
  3922. formData.append('file', file);
  3923. const url = `${API_BASE}/settings/restore`;
  3924. const headers: Record<string, string> = {};
  3925. if (authToken) {
  3926. headers['Authorization'] = `Bearer ${authToken}`;
  3927. }
  3928. const response = await fetch(url, {
  3929. method: 'POST',
  3930. headers,
  3931. body: formData,
  3932. });
  3933. return response.json() as Promise<{
  3934. success: boolean;
  3935. message: string;
  3936. }>;
  3937. },
  3938. checkFfmpeg: () =>
  3939. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  3940. getNetworkInterfaces: () =>
  3941. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  3942. // Cloud
  3943. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  3944. cloudLogin: (email: string, password: string, region = 'global') =>
  3945. request<CloudLoginResponse>('/cloud/login', {
  3946. method: 'POST',
  3947. body: JSON.stringify({ email, password, region }),
  3948. }),
  3949. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  3950. request<CloudLoginResponse>('/cloud/verify', {
  3951. method: 'POST',
  3952. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  3953. }),
  3954. cloudSetToken: (access_token: string, region: string = 'global') =>
  3955. request<CloudAuthStatus>('/cloud/token', {
  3956. method: 'POST',
  3957. body: JSON.stringify({ access_token, region }),
  3958. }),
  3959. cloudLogout: () =>
  3960. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  3961. getCloudSettings: (version = '02.04.00.70') =>
  3962. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  3963. getBuiltinFilaments: () =>
  3964. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  3965. getFilamentIdMap: () =>
  3966. request<Record<string, string>>('/cloud/filament-id-map'),
  3967. // MakerWorld URL-paste import flow.
  3968. getMakerworldStatus: () =>
  3969. request<MakerworldStatus>('/makerworld/status'),
  3970. resolveMakerworldUrl: (url: string) =>
  3971. request<MakerworldResolvedModel>('/makerworld/resolve', {
  3972. method: 'POST',
  3973. body: JSON.stringify({ url }),
  3974. }),
  3975. getMakerworldRecentImports: (limit = 10) =>
  3976. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  3977. importMakerworldInstance: (
  3978. model_id: number,
  3979. instance_id: number | null,
  3980. profile_id?: number | null,
  3981. folder_id?: number | null,
  3982. ) =>
  3983. request<MakerworldImportResponse>('/makerworld/import', {
  3984. method: 'POST',
  3985. body: JSON.stringify({
  3986. model_id,
  3987. instance_id: instance_id ?? null,
  3988. profile_id: profile_id ?? null,
  3989. folder_id: folder_id ?? null,
  3990. }),
  3991. }),
  3992. getCloudSettingDetail: (settingId: string) =>
  3993. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  3994. createCloudSetting: (data: SlicerSettingCreate) =>
  3995. request<SlicerSettingDetail>('/cloud/settings', {
  3996. method: 'POST',
  3997. body: JSON.stringify(data),
  3998. }),
  3999. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  4000. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  4001. method: 'PUT',
  4002. body: JSON.stringify(data),
  4003. }),
  4004. deleteCloudSetting: (settingId: string) =>
  4005. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  4006. method: 'DELETE',
  4007. }),
  4008. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  4009. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  4010. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  4011. getAllCloudFields: () =>
  4012. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  4013. getFilamentInfo: (settingIds: string[]) =>
  4014. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  4015. method: 'POST',
  4016. body: JSON.stringify(settingIds),
  4017. }),
  4018. // Smart Plugs
  4019. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  4020. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  4021. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  4022. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  4023. createSmartPlug: (data: SmartPlugCreate) =>
  4024. request<SmartPlug>('/smart-plugs/', {
  4025. method: 'POST',
  4026. body: JSON.stringify(data),
  4027. }),
  4028. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  4029. request<SmartPlug>(`/smart-plugs/${id}`, {
  4030. method: 'PATCH',
  4031. body: JSON.stringify(data),
  4032. }),
  4033. deleteSmartPlug: (id: number) =>
  4034. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  4035. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  4036. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  4037. method: 'POST',
  4038. body: JSON.stringify({ action }),
  4039. }),
  4040. getSmartPlugStatus: (id: number) =>
  4041. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  4042. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  4043. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  4044. method: 'POST',
  4045. body: JSON.stringify({ ip_address, username, password }),
  4046. }),
  4047. // Tasmota Discovery (auto-detects network)
  4048. startTasmotaScan: () =>
  4049. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  4050. getTasmotaScanStatus: () =>
  4051. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  4052. stopTasmotaScan: () =>
  4053. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  4054. getDiscoveredTasmotaDevices: () =>
  4055. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  4056. // Home Assistant Integration
  4057. testHAConnection: (url: string, token: string) =>
  4058. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  4059. method: 'POST',
  4060. body: JSON.stringify({ url, token }),
  4061. }),
  4062. getHAEntities: (search?: string) => {
  4063. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  4064. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  4065. },
  4066. getHASensorEntities: () =>
  4067. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  4068. // REST smart plug
  4069. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null) =>
  4070. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  4071. method: 'POST',
  4072. body: JSON.stringify({ url, method, headers }),
  4073. }),
  4074. // Print Queue
  4075. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  4076. const params = new URLSearchParams();
  4077. if (printerId) params.set('printer_id', String(printerId));
  4078. if (status) params.set('status', status);
  4079. if (targetModel) params.set('target_model', targetModel);
  4080. return request<PrintQueueItem[]>(`/queue/?${params}`);
  4081. },
  4082. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  4083. addToQueue: (data: PrintQueueItemCreate) =>
  4084. request<PrintQueueItem>('/queue/', {
  4085. method: 'POST',
  4086. body: JSON.stringify(data),
  4087. }),
  4088. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  4089. request<PrintQueueItem>(`/queue/${id}`, {
  4090. method: 'PATCH',
  4091. body: JSON.stringify(data),
  4092. }),
  4093. removeFromQueue: (id: number) =>
  4094. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  4095. reorderQueue: (items: { id: number; position: number }[]) =>
  4096. request<{ message: string }>('/queue/reorder', {
  4097. method: 'POST',
  4098. body: JSON.stringify({ items }),
  4099. }),
  4100. cancelQueueItem: (id: number) =>
  4101. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  4102. stopQueueItem: (id: number) =>
  4103. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  4104. startQueueItem: (id: number) =>
  4105. request<PrintQueueItem>(`/queue/${id}/start`, { method: 'POST' }),
  4106. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  4107. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  4108. method: 'PATCH',
  4109. body: JSON.stringify(data),
  4110. }),
  4111. // Batches
  4112. getBatches: (status?: string) => {
  4113. const params = status ? `?status=${status}` : '';
  4114. return request<PrintBatch[]>(`/queue/batches${params}`);
  4115. },
  4116. getBatch: (id: number) => request<PrintBatch>(`/queue/batches/${id}`),
  4117. cancelBatch: (id: number) =>
  4118. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  4119. // K-Profiles
  4120. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  4121. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  4122. setKProfile: (printerId: number, profile: KProfileCreate) =>
  4123. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4124. method: 'POST',
  4125. body: JSON.stringify(profile),
  4126. }),
  4127. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  4128. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4129. method: 'DELETE',
  4130. body: JSON.stringify(profile),
  4131. }),
  4132. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  4133. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  4134. method: 'POST',
  4135. body: JSON.stringify(profiles),
  4136. }),
  4137. // K-Profile Notes (stored locally, not on printer)
  4138. getKProfileNotes: (printerId: number) =>
  4139. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  4140. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  4141. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  4142. method: 'PUT',
  4143. body: JSON.stringify({ setting_id: settingId, note }),
  4144. }),
  4145. deleteKProfileNote: (printerId: number, settingId: string) =>
  4146. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  4147. method: 'DELETE',
  4148. }),
  4149. // Slot Preset Mappings
  4150. getSlotPresets: (printerId: number) =>
  4151. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  4152. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4153. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  4154. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  4155. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  4156. method: 'PUT',
  4157. }),
  4158. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4159. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  4160. method: 'DELETE',
  4161. }),
  4162. // AMS Labels (user-defined friendly names)
  4163. getAmsLabels: (printerId: number) =>
  4164. request<Record<number, string>>(`/printers/${printerId}/ams-labels`),
  4165. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  4166. request<{ ams_id: number; label: string }>(
  4167. `/printers/${printerId}/ams-labels/${amsId}`,
  4168. {
  4169. method: 'PUT',
  4170. body: JSON.stringify({ label, ams_serial: amsSerial }),
  4171. }
  4172. ),
  4173. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  4174. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  4175. method: 'DELETE',
  4176. }),
  4177. configureAmsSlot: (
  4178. printerId: number,
  4179. amsId: number,
  4180. trayId: number,
  4181. config: {
  4182. tray_info_idx: string;
  4183. tray_type: string;
  4184. tray_sub_brands: string;
  4185. tray_color: string;
  4186. nozzle_temp_min: number;
  4187. nozzle_temp_max: number;
  4188. cali_idx: number;
  4189. nozzle_diameter: string;
  4190. setting_id?: string;
  4191. kprofile_filament_id?: string;
  4192. kprofile_setting_id?: string;
  4193. k_value?: number;
  4194. }
  4195. ) => {
  4196. const params = new URLSearchParams({
  4197. tray_info_idx: config.tray_info_idx,
  4198. tray_type: config.tray_type,
  4199. tray_sub_brands: config.tray_sub_brands,
  4200. tray_color: config.tray_color,
  4201. nozzle_temp_min: config.nozzle_temp_min.toString(),
  4202. nozzle_temp_max: config.nozzle_temp_max.toString(),
  4203. cali_idx: config.cali_idx.toString(),
  4204. nozzle_diameter: config.nozzle_diameter,
  4205. });
  4206. if (config.setting_id) {
  4207. params.set('setting_id', config.setting_id);
  4208. }
  4209. if (config.kprofile_filament_id) {
  4210. params.set('kprofile_filament_id', config.kprofile_filament_id);
  4211. }
  4212. if (config.kprofile_setting_id) {
  4213. params.set('kprofile_setting_id', config.kprofile_setting_id);
  4214. }
  4215. if (config.k_value !== undefined && config.k_value > 0) {
  4216. params.set('k_value', config.k_value.toString());
  4217. }
  4218. return request<{ success: boolean; message: string }>(
  4219. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  4220. { method: 'POST' }
  4221. );
  4222. },
  4223. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  4224. request<{ success: boolean; message: string }>(
  4225. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  4226. { method: 'POST' }
  4227. ),
  4228. // Filament Catalog (material types with cost/temp data)
  4229. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  4230. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  4231. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  4232. // Notification Providers
  4233. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  4234. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  4235. createNotificationProvider: (data: NotificationProviderCreate) =>
  4236. request<NotificationProvider>('/notifications/', {
  4237. method: 'POST',
  4238. body: JSON.stringify(data),
  4239. }),
  4240. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  4241. request<NotificationProvider>(`/notifications/${id}`, {
  4242. method: 'PATCH',
  4243. body: JSON.stringify(data),
  4244. }),
  4245. deleteNotificationProvider: (id: number) =>
  4246. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  4247. testNotificationProvider: (id: number) =>
  4248. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  4249. testNotificationConfig: (data: NotificationTestRequest) =>
  4250. request<NotificationTestResponse>('/notifications/test-config', {
  4251. method: 'POST',
  4252. body: JSON.stringify(data),
  4253. }),
  4254. testAllNotificationProviders: () =>
  4255. request<{
  4256. tested: number;
  4257. success: number;
  4258. failed: number;
  4259. results: Array<{
  4260. provider_id: number;
  4261. provider_name: string;
  4262. provider_type: string;
  4263. success: boolean;
  4264. message: string;
  4265. }>;
  4266. }>('/notifications/test-all', { method: 'POST' }),
  4267. // Notification Templates
  4268. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  4269. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  4270. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  4271. request<NotificationTemplate>(`/notification-templates/${id}`, {
  4272. method: 'PUT',
  4273. body: JSON.stringify(data),
  4274. }),
  4275. resetNotificationTemplate: (id: number) =>
  4276. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  4277. method: 'POST',
  4278. }),
  4279. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  4280. previewTemplate: (data: TemplatePreviewRequest) =>
  4281. request<TemplatePreviewResponse>('/notification-templates/preview', {
  4282. method: 'POST',
  4283. body: JSON.stringify(data),
  4284. }),
  4285. // Notification Logs
  4286. getNotificationLogs: (params?: {
  4287. limit?: number;
  4288. offset?: number;
  4289. provider_id?: number;
  4290. event_type?: string;
  4291. success?: boolean;
  4292. days?: number;
  4293. }) => {
  4294. const searchParams = new URLSearchParams();
  4295. if (params?.limit) searchParams.set('limit', String(params.limit));
  4296. if (params?.offset) searchParams.set('offset', String(params.offset));
  4297. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  4298. if (params?.event_type) searchParams.set('event_type', params.event_type);
  4299. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  4300. if (params?.days) searchParams.set('days', String(params.days));
  4301. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  4302. },
  4303. getNotificationLogStats: (days = 7) =>
  4304. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  4305. clearNotificationLogs: (olderThanDays = 30) =>
  4306. request<{ deleted: number; message: string }>(
  4307. `/notifications/logs?older_than_days=${olderThanDays}`,
  4308. { method: 'DELETE' }
  4309. ),
  4310. // Spoolman Integration
  4311. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  4312. connectSpoolman: () =>
  4313. request<{ success: boolean; message: string }>('/spoolman/connect', {
  4314. method: 'POST',
  4315. }),
  4316. disconnectSpoolman: () =>
  4317. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  4318. method: 'POST',
  4319. }),
  4320. syncPrinterAms: (printerId: number) =>
  4321. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  4322. method: 'POST',
  4323. }),
  4324. syncAllPrintersAms: () =>
  4325. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  4326. method: 'POST',
  4327. }),
  4328. getSpoolmanSpools: () =>
  4329. request<{ spools: unknown[] }>('/spoolman/spools'),
  4330. /** @deprecated Use getSpoolmanInventoryFilaments() — this endpoint has no SSRF guard */
  4331. getSpoolmanFilaments: () =>
  4332. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  4333. getSpoolmanInventoryFilaments: () =>
  4334. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  4335. patchSpoolmanFilament: (
  4336. filamentId: number,
  4337. data: { name?: string; spool_weight?: number | null; keep_existing_spools?: boolean },
  4338. ) =>
  4339. request<SpoolmanFilamentEntry>(`/spoolman/inventory/filaments/${filamentId}`, {
  4340. method: 'PATCH',
  4341. body: JSON.stringify(data),
  4342. }),
  4343. getUnlinkedSpools: () =>
  4344. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  4345. getLinkedSpools: () =>
  4346. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  4347. linkSpool: (
  4348. spoolId: number,
  4349. context: {
  4350. spoolTag: string;
  4351. printerId: number;
  4352. amsId: number;
  4353. trayId: number;
  4354. }
  4355. ) =>
  4356. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  4357. method: 'POST',
  4358. body: JSON.stringify({
  4359. spool_tag: context.spoolTag,
  4360. printer_id: context.printerId,
  4361. ams_id: context.amsId,
  4362. tray_id: context.trayId,
  4363. }),
  4364. }),
  4365. unlinkSpool: (spoolId: number) =>
  4366. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  4367. method: 'POST',
  4368. }),
  4369. getSpoolmanSettings: () =>
  4370. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman'),
  4371. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; }) =>
  4372. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman', {
  4373. method: 'PUT',
  4374. body: JSON.stringify(data),
  4375. }),
  4376. // Inventory
  4377. getSpools: (includeArchived = false) =>
  4378. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  4379. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  4380. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4381. request<InventorySpool>('/inventory/spools', {
  4382. method: 'POST',
  4383. body: JSON.stringify(data),
  4384. }),
  4385. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  4386. request<InventorySpool[]>('/inventory/spools/bulk', {
  4387. method: 'POST',
  4388. body: JSON.stringify({ spool: data, quantity }),
  4389. }),
  4390. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  4391. request<InventorySpool>(`/inventory/spools/${id}`, {
  4392. method: 'PATCH',
  4393. body: JSON.stringify(data),
  4394. }),
  4395. deleteSpool: (id: number) =>
  4396. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  4397. archiveSpool: (id: number) =>
  4398. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  4399. restoreSpool: (id: number) =>
  4400. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  4401. resetSpoolUsage: (id: number) =>
  4402. request<InventorySpool>(`/inventory/spools/${id}/reset-usage`, { method: 'POST' }),
  4403. bulkResetSpoolUsage: (spoolIds: number[]) =>
  4404. request<{ reset: number }>(`/inventory/spools/reset-usage-bulk`, {
  4405. method: 'POST',
  4406. body: JSON.stringify({ spool_ids: spoolIds }),
  4407. }),
  4408. getSpoolKProfiles: (spoolId: number) =>
  4409. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  4410. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4411. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  4412. method: 'PUT',
  4413. body: JSON.stringify(profiles),
  4414. }),
  4415. getAssignments: (printerId?: number) =>
  4416. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  4417. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4418. request<SpoolAssignment>('/inventory/assignments', {
  4419. method: 'POST',
  4420. body: JSON.stringify(data),
  4421. }),
  4422. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  4423. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  4424. // ── Spool label printing (#809) ──────────────────────────────────────────
  4425. // Both endpoints return application/pdf. Frontend opens the resulting Blob
  4426. // in a new tab so the user can print or save from the browser's PDF viewer.
  4427. printSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate }): Promise<Blob> => {
  4428. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4429. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4430. const response = await fetch(`${API_BASE}/inventory/labels`, {
  4431. method: 'POST',
  4432. headers,
  4433. body: JSON.stringify(data),
  4434. });
  4435. if (!response.ok) {
  4436. const error = await response.json().catch(() => ({}));
  4437. throw new Error(error.detail || `HTTP ${response.status}`);
  4438. }
  4439. return response.blob();
  4440. },
  4441. printSpoolmanSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate }): Promise<Blob> => {
  4442. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4443. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4444. const response = await fetch(`${API_BASE}/spoolman/labels`, {
  4445. method: 'POST',
  4446. headers,
  4447. body: JSON.stringify(data),
  4448. });
  4449. if (!response.ok) {
  4450. const error = await response.json().catch(() => ({}));
  4451. throw new Error(error.detail || `HTTP ${response.status}`);
  4452. }
  4453. return response.blob();
  4454. },
  4455. getSpoolCatalog: () =>
  4456. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  4457. addCatalogEntry: (data: { name: string; weight: number }) =>
  4458. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  4459. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  4460. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4461. deleteCatalogEntry: (id: number) =>
  4462. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  4463. bulkDeleteCatalogEntries: (ids: number[]) =>
  4464. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4465. resetSpoolCatalog: () =>
  4466. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  4467. getColorCatalog: () =>
  4468. request<ColorCatalogEntry[]>('/inventory/colors'),
  4469. getColorNameMap: () =>
  4470. request<{ colors: Record<string, string> }>('/inventory/colors/map'),
  4471. addColorEntry: (data: {
  4472. manufacturer: string;
  4473. color_name: string;
  4474. hex_color: string;
  4475. material: string | null;
  4476. extra_colors?: string | null;
  4477. effect_type?: string | null;
  4478. }) =>
  4479. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  4480. updateColorEntry: (
  4481. id: number,
  4482. data: {
  4483. manufacturer: string;
  4484. color_name: string;
  4485. hex_color: string;
  4486. material: string | null;
  4487. extra_colors?: string | null;
  4488. effect_type?: string | null;
  4489. },
  4490. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4491. deleteColorEntry: (id: number) =>
  4492. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  4493. bulkDeleteColorEntries: (ids: number[]) =>
  4494. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4495. resetColorCatalog: () =>
  4496. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  4497. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  4498. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  4499. searchColors: (manufacturer?: string, material?: string) =>
  4500. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  4501. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  4502. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  4503. method: 'PATCH',
  4504. body: JSON.stringify(data),
  4505. }),
  4506. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  4507. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  4508. getAllUsageHistory: (limit = 100, printerId?: number) =>
  4509. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  4510. clearSpoolUsageHistory: (spoolId: number) =>
  4511. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  4512. syncWeightsFromAms: () =>
  4513. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  4514. getSkuSettings: () =>
  4515. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  4516. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  4517. request<FilamentSkuSettings>('/inventory/sku-settings', {
  4518. method: 'POST',
  4519. body: JSON.stringify(data),
  4520. }),
  4521. getShoppingList: () =>
  4522. request<ShoppingListItem[]>('/inventory/shopping-list'),
  4523. addToShoppingList: (data: ShoppingListItemCreate) =>
  4524. request<ShoppingListItem>('/inventory/shopping-list', {
  4525. method: 'POST',
  4526. body: JSON.stringify(data),
  4527. }),
  4528. removeFromShoppingList: (id: number) =>
  4529. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  4530. clearShoppingList: () =>
  4531. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  4532. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  4533. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  4534. method: 'PATCH',
  4535. body: JSON.stringify({ status }),
  4536. }),
  4537. getFilamentPresets: () =>
  4538. request<SlicerSetting[]>('/cloud/filaments'),
  4539. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  4540. getSpoolmanInventorySpools: (includeArchived = false) =>
  4541. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  4542. getSpoolmanInventorySpool: (id: number) =>
  4543. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  4544. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4545. request<InventorySpool>('/spoolman/inventory/spools', {
  4546. method: 'POST',
  4547. body: JSON.stringify(data),
  4548. }),
  4549. bulkCreateSpoolmanInventorySpools: (
  4550. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  4551. quantity: number,
  4552. ) =>
  4553. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  4554. method: 'POST',
  4555. body: JSON.stringify({ spool: data, quantity }),
  4556. }),
  4557. updateSpoolmanInventorySpool: (
  4558. id: number,
  4559. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  4560. ) =>
  4561. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  4562. method: 'PATCH',
  4563. body: JSON.stringify(data),
  4564. }),
  4565. deleteSpoolmanInventorySpool: (id: number) =>
  4566. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  4567. archiveSpoolmanInventorySpool: (id: number) =>
  4568. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  4569. restoreSpoolmanInventorySpool: (id: number) =>
  4570. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  4571. resetSpoolmanInventorySpoolUsage: (id: number) =>
  4572. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-usage`, { method: 'POST' }),
  4573. bulkResetSpoolmanInventorySpoolUsage: (spoolIds: number[]) =>
  4574. request<{ reset: number }>(`/spoolman/inventory/spools/reset-usage-bulk`, {
  4575. method: 'POST',
  4576. body: JSON.stringify({ spool_ids: spoolIds }),
  4577. }),
  4578. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  4579. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  4580. method: 'PATCH',
  4581. body: JSON.stringify(data),
  4582. }),
  4583. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  4584. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  4585. method: 'PATCH',
  4586. body: JSON.stringify({ weight_grams: weightGrams }),
  4587. }),
  4588. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4589. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  4590. method: 'POST',
  4591. body: JSON.stringify(data),
  4592. }),
  4593. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  4594. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  4595. getSpoolmanSlotAssignment: (printerId: number, amsId: number, trayId: number) =>
  4596. request<InventorySpool | null>(
  4597. `/spoolman/inventory/slot-assignments?printer_id=${printerId}&ams_id=${amsId}&tray_id=${trayId}`,
  4598. ),
  4599. getSpoolmanSlotAssignments: (printerId?: number) =>
  4600. request<Array<{
  4601. printer_id: number;
  4602. printer_name: string | null;
  4603. ams_id: number;
  4604. tray_id: number;
  4605. spoolman_spool_id: number;
  4606. ams_label: string | null;
  4607. }>>(
  4608. printerId !== undefined
  4609. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  4610. : '/spoolman/inventory/slot-assignments/all',
  4611. ),
  4612. syncSpoolmanAmsWeights: () =>
  4613. request<{ synced: number; skipped: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  4614. getSpoolmanKProfiles: (spoolId: number) =>
  4615. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`),
  4616. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4617. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  4618. method: 'PUT',
  4619. body: JSON.stringify(profiles),
  4620. }),
  4621. // Updates
  4622. getVersion: () => request<VersionInfo>('/updates/version'),
  4623. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  4624. applyUpdate: () =>
  4625. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean }>('/updates/apply', {
  4626. method: 'POST',
  4627. }),
  4628. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  4629. // Maintenance
  4630. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  4631. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  4632. request<MaintenanceType>('/maintenance/types', {
  4633. method: 'POST',
  4634. body: JSON.stringify(data),
  4635. }),
  4636. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  4637. request<MaintenanceType>(`/maintenance/types/${id}`, {
  4638. method: 'PATCH',
  4639. body: JSON.stringify(data),
  4640. }),
  4641. deleteMaintenanceType: (id: number) =>
  4642. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  4643. restoreDefaultMaintenanceTypes: () =>
  4644. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  4645. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  4646. getPrinterMaintenance: (printerId: number) =>
  4647. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  4648. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  4649. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  4650. method: 'PATCH',
  4651. body: JSON.stringify(data),
  4652. }),
  4653. performMaintenance: (itemId: number, notes?: string) =>
  4654. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  4655. method: 'POST',
  4656. body: JSON.stringify({ notes }),
  4657. }),
  4658. getMaintenanceHistory: (itemId: number) =>
  4659. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  4660. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  4661. setPrinterHours: (printerId: number, totalHours: number) =>
  4662. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  4663. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  4664. { method: 'PATCH' }
  4665. ),
  4666. assignMaintenanceType: (printerId: number, typeId: number) =>
  4667. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  4668. method: 'POST',
  4669. }),
  4670. removeMaintenanceItem: (itemId: number) =>
  4671. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  4672. method: 'DELETE',
  4673. }),
  4674. // Camera
  4675. getCameraStreamToken: () =>
  4676. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  4677. // Long-lived camera-stream tokens (#1108)
  4678. createLongLivedCameraToken: (payload: { name: string; expires_in_days: number }) =>
  4679. request<LongLivedCameraToken>('/auth/tokens', {
  4680. method: 'POST',
  4681. body: JSON.stringify({ ...payload, scope: 'camera_stream' }),
  4682. }),
  4683. listMyLongLivedCameraTokens: () =>
  4684. request<LongLivedCameraToken[]>('/auth/tokens'),
  4685. listAllLongLivedCameraTokens: () =>
  4686. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  4687. listLongLivedCameraTokensForUser: (userId: number) =>
  4688. request<LongLivedCameraToken[]>(`/auth/tokens?user_id=${userId}`),
  4689. revokeLongLivedCameraToken: (tokenId: number) =>
  4690. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  4691. getCameraStreamUrl: (printerId: number, fps = 10) =>
  4692. withStreamToken(`${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`),
  4693. getCameraSnapshotUrl: (printerId: number) =>
  4694. withStreamToken(`${API_BASE}/printers/${printerId}/camera/snapshot`),
  4695. testCameraConnection: (printerId: number) =>
  4696. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  4697. getCameraStatus: (printerId: number) =>
  4698. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  4699. diagnoseCamera: (printerId: number) =>
  4700. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  4701. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  4702. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  4703. const params = new URLSearchParams();
  4704. // Only forward use_external when the caller explicitly sets it. Omitted →
  4705. // backend derives the default from the printer's external_camera_enabled
  4706. // setting so calibration and runtime checks use the same camera (#1359).
  4707. if (options?.useExternal !== undefined) {
  4708. params.set('use_external', String(options.useExternal));
  4709. }
  4710. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  4711. return request<PlateDetectionResult>(
  4712. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  4713. );
  4714. },
  4715. getPlateDetectionStatus: (printerId: number) => {
  4716. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  4717. `/printers/${printerId}/camera/plate-detection/status`
  4718. );
  4719. },
  4720. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  4721. const params = new URLSearchParams();
  4722. if (options?.label) params.set('label', options.label);
  4723. if (options?.useExternal !== undefined) {
  4724. params.set('use_external', String(options.useExternal));
  4725. }
  4726. return request<CalibrationResult & { index: number }>(
  4727. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  4728. { method: 'POST' }
  4729. );
  4730. },
  4731. deletePlateCalibration: (printerId: number) => {
  4732. return request<CalibrationResult>(
  4733. `/printers/${printerId}/camera/plate-detection/calibrate`,
  4734. { method: 'DELETE' }
  4735. );
  4736. },
  4737. getPlateReferences: (printerId: number) => {
  4738. return request<{
  4739. references: PlateReference[];
  4740. max_references: number;
  4741. }>(`/printers/${printerId}/camera/plate-detection/references`);
  4742. },
  4743. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  4744. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  4745. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  4746. const params = new URLSearchParams();
  4747. params.set('label', label);
  4748. return request<{ success: boolean; index: number; label: string }>(
  4749. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  4750. { method: 'PUT' }
  4751. );
  4752. },
  4753. deletePlateReference: (printerId: number, index: number) => {
  4754. return request<{ success: boolean; message: string }>(
  4755. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  4756. { method: 'DELETE' }
  4757. );
  4758. },
  4759. // External Links
  4760. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  4761. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  4762. createExternalLink: (data: ExternalLinkCreate) =>
  4763. request<ExternalLink>('/external-links/', {
  4764. method: 'POST',
  4765. body: JSON.stringify(data),
  4766. }),
  4767. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  4768. request<ExternalLink>(`/external-links/${id}`, {
  4769. method: 'PATCH',
  4770. body: JSON.stringify(data),
  4771. }),
  4772. deleteExternalLink: (id: number) =>
  4773. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  4774. reorderExternalLinks: (ids: number[]) =>
  4775. request<ExternalLink[]>('/external-links/reorder', {
  4776. method: 'PUT',
  4777. body: JSON.stringify({ ids }),
  4778. }),
  4779. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  4780. const formData = new FormData();
  4781. formData.append('file', file);
  4782. const headers: Record<string, string> = {};
  4783. if (authToken) {
  4784. headers['Authorization'] = `Bearer ${authToken}`;
  4785. }
  4786. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  4787. method: 'POST',
  4788. headers,
  4789. body: formData,
  4790. });
  4791. if (!response.ok) {
  4792. const error = await response.json().catch(() => ({}));
  4793. throw new Error(error.detail || `HTTP ${response.status}`);
  4794. }
  4795. return response.json();
  4796. },
  4797. deleteExternalLinkIcon: (id: number) =>
  4798. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  4799. getExternalLinkIconUrl: (id: number) => withStreamToken(`${API_BASE}/external-links/${id}/icon`),
  4800. // Projects
  4801. getProjects: (status?: string) => {
  4802. const params = new URLSearchParams();
  4803. if (status) params.set('status', status);
  4804. return request<ProjectListItem[]>(`/projects/?${params}`);
  4805. },
  4806. getProject: (id: number) => request<Project>(`/projects/${id}`),
  4807. createProject: (data: ProjectCreate) =>
  4808. request<Project>('/projects/', {
  4809. method: 'POST',
  4810. body: JSON.stringify(data),
  4811. }),
  4812. updateProject: (id: number, data: ProjectUpdate) =>
  4813. request<Project>(`/projects/${id}`, {
  4814. method: 'PATCH',
  4815. body: JSON.stringify(data),
  4816. }),
  4817. deleteProject: (id: number) =>
  4818. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  4819. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  4820. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  4821. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  4822. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  4823. method: 'POST',
  4824. body: JSON.stringify({ archive_ids: archiveIds }),
  4825. }),
  4826. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  4827. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  4828. method: 'POST',
  4829. body: JSON.stringify({ archive_ids: archiveIds }),
  4830. }),
  4831. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  4832. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  4833. method: 'POST',
  4834. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  4835. }),
  4836. // Project Attachments
  4837. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  4838. status: string;
  4839. filename: string;
  4840. original_name: string;
  4841. attachments: ProjectAttachment[];
  4842. }> => {
  4843. const formData = new FormData();
  4844. formData.append('file', file);
  4845. const headers: Record<string, string> = {};
  4846. if (authToken) {
  4847. headers['Authorization'] = `Bearer ${authToken}`;
  4848. }
  4849. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  4850. method: 'POST',
  4851. headers,
  4852. body: formData,
  4853. });
  4854. if (!response.ok) {
  4855. const error = await response.json().catch(() => ({}));
  4856. throw new Error(error.detail || `HTTP ${response.status}`);
  4857. }
  4858. return response.json();
  4859. },
  4860. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  4861. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  4862. deleteProjectAttachment: (projectId: number, filename: string) =>
  4863. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  4864. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  4865. { method: 'DELETE' }
  4866. ),
  4867. // #1155: Cover image
  4868. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  4869. // append the stream-token query string the same way archive thumbnails do.
  4870. getProjectCoverImageUrl: (projectId: number) =>
  4871. withStreamToken(`${API_BASE}/projects/${projectId}/cover-image`),
  4872. uploadProjectCoverImage: async (
  4873. projectId: number,
  4874. file: File
  4875. ): Promise<{ status: string; filename: string; size: number }> => {
  4876. const formData = new FormData();
  4877. formData.append('file', file);
  4878. const headers: Record<string, string> = {};
  4879. if (authToken) {
  4880. headers['Authorization'] = `Bearer ${authToken}`;
  4881. }
  4882. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  4883. method: 'POST',
  4884. headers,
  4885. body: formData,
  4886. });
  4887. if (!response.ok) {
  4888. const error = await response.json().catch(() => ({}));
  4889. throw new Error(error.detail || `HTTP ${response.status}`);
  4890. }
  4891. return response.json();
  4892. },
  4893. deleteProjectCoverImage: (projectId: number) =>
  4894. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  4895. // BOM (Bill of Materials)
  4896. getProjectBOM: (projectId: number) =>
  4897. request<BOMItem[]>(`/projects/${projectId}/bom`),
  4898. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  4899. request<BOMItem>(`/projects/${projectId}/bom`, {
  4900. method: 'POST',
  4901. body: JSON.stringify(data),
  4902. }),
  4903. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  4904. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  4905. method: 'PATCH',
  4906. body: JSON.stringify(data),
  4907. }),
  4908. deleteBOMItem: (projectId: number, itemId: number) =>
  4909. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  4910. method: 'DELETE',
  4911. }),
  4912. // Templates
  4913. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  4914. createTemplateFromProject: (projectId: number) =>
  4915. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  4916. createProjectFromTemplate: (templateId: number, name?: string) =>
  4917. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  4918. method: 'POST',
  4919. }),
  4920. // Timeline
  4921. getProjectTimeline: (projectId: number, limit = 50) =>
  4922. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  4923. // Project Export/Import
  4924. exportProjectJson: (projectId: number) =>
  4925. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  4926. importProject: (data: ProjectImport) =>
  4927. request<Project>('/projects/import', {
  4928. method: 'POST',
  4929. body: JSON.stringify(data),
  4930. }),
  4931. importProjectFile: async (file: File): Promise<Project> => {
  4932. const formData = new FormData();
  4933. formData.append('file', file);
  4934. const headers: Record<string, string> = {};
  4935. if (authToken) {
  4936. headers['Authorization'] = `Bearer ${authToken}`;
  4937. }
  4938. const response = await fetch(`${API_BASE}/projects/import/file`, {
  4939. method: 'POST',
  4940. headers,
  4941. body: formData,
  4942. });
  4943. if (!response.ok) {
  4944. const error = await response.json().catch(() => ({}));
  4945. throw new Error(error.detail || `HTTP ${response.status}`);
  4946. }
  4947. return response.json();
  4948. },
  4949. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  4950. const headers: Record<string, string> = {};
  4951. if (authToken) {
  4952. headers['Authorization'] = `Bearer ${authToken}`;
  4953. }
  4954. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  4955. headers,
  4956. });
  4957. if (!response.ok) {
  4958. const error = await response.json().catch(() => ({}));
  4959. throw new Error(error.detail || `HTTP ${response.status}`);
  4960. }
  4961. const contentDisposition = response.headers.get('Content-Disposition');
  4962. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  4963. const blob = await response.blob();
  4964. return { blob, filename };
  4965. },
  4966. // API Keys
  4967. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  4968. createAPIKey: (data: APIKeyCreate) =>
  4969. request<APIKeyCreateResponse>('/api-keys/', {
  4970. method: 'POST',
  4971. body: JSON.stringify(data),
  4972. }),
  4973. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  4974. request<APIKey>(`/api-keys/${id}`, {
  4975. method: 'PATCH',
  4976. body: JSON.stringify(data),
  4977. }),
  4978. deleteAPIKey: (id: number) =>
  4979. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  4980. // AMS History
  4981. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  4982. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  4983. // System Info
  4984. getSystemInfo: () => request<SystemInfo>('/system/info'),
  4985. getStorageUsage: (options?: { refresh?: boolean }) => {
  4986. const params = new URLSearchParams();
  4987. if (options?.refresh) {
  4988. params.set('refresh', 'true');
  4989. }
  4990. const query = params.toString();
  4991. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  4992. },
  4993. // Library (File Manager)
  4994. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  4995. createLibraryFolder: (data: LibraryFolderCreate) =>
  4996. request<LibraryFolder>('/library/folders', {
  4997. method: 'POST',
  4998. body: JSON.stringify(data),
  4999. }),
  5000. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  5001. request<LibraryFolder>(`/library/folders/${id}`, {
  5002. method: 'PUT',
  5003. body: JSON.stringify(data),
  5004. }),
  5005. deleteLibraryFolder: (id: number) =>
  5006. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  5007. createExternalFolder: (data: ExternalFolderCreate) =>
  5008. request<LibraryFolder>('/library/folders/external', {
  5009. method: 'POST',
  5010. body: JSON.stringify(data),
  5011. }),
  5012. scanExternalFolder: (folderId: number) =>
  5013. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  5014. method: 'POST',
  5015. }),
  5016. getLibraryFoldersByProject: (projectId: number) =>
  5017. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  5018. getLibraryFoldersByArchive: (archiveId: number) =>
  5019. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  5020. getLibraryFiles: (folderId?: number | null, includeRoot = true, projectId?: number) => {
  5021. const params = new URLSearchParams();
  5022. if (folderId !== undefined && folderId !== null) {
  5023. params.set('folder_id', String(folderId));
  5024. }
  5025. if (projectId !== undefined) {
  5026. params.set('project_id', String(projectId));
  5027. }
  5028. params.set('include_root', String(includeRoot));
  5029. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  5030. },
  5031. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  5032. uploadLibraryFile: async (
  5033. file: File,
  5034. folderId?: number | null,
  5035. generateStlThumbnails: boolean = true
  5036. ): Promise<LibraryFileUploadResponse> => {
  5037. const formData = new FormData();
  5038. formData.append('file', file);
  5039. const params = new URLSearchParams();
  5040. if (folderId) params.set('folder_id', String(folderId));
  5041. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5042. const headers: Record<string, string> = {};
  5043. if (authToken) {
  5044. headers['Authorization'] = `Bearer ${authToken}`;
  5045. }
  5046. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  5047. method: 'POST',
  5048. headers,
  5049. body: formData,
  5050. });
  5051. if (!response.ok) {
  5052. const error = await response.json().catch(() => ({}));
  5053. throw new Error(error.detail || `HTTP ${response.status}`);
  5054. }
  5055. return response.json();
  5056. },
  5057. extractZipFile: async (
  5058. file: File,
  5059. folderId?: number | null,
  5060. preserveStructure: boolean = true,
  5061. createFolderFromZip: boolean = false,
  5062. generateStlThumbnails: boolean = true
  5063. ): Promise<ZipExtractResponse> => {
  5064. const formData = new FormData();
  5065. formData.append('file', file);
  5066. const params = new URLSearchParams();
  5067. if (folderId) params.set('folder_id', String(folderId));
  5068. params.set('preserve_structure', String(preserveStructure));
  5069. params.set('create_folder_from_zip', String(createFolderFromZip));
  5070. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5071. const headers: Record<string, string> = {};
  5072. if (authToken) {
  5073. headers['Authorization'] = `Bearer ${authToken}`;
  5074. }
  5075. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  5076. method: 'POST',
  5077. headers,
  5078. body: formData,
  5079. });
  5080. if (!response.ok) {
  5081. const error = await response.json().catch(() => ({}));
  5082. throw new Error(error.detail || `HTTP ${response.status}`);
  5083. }
  5084. return response.json();
  5085. },
  5086. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  5087. request<LibraryFile>(`/library/files/${id}`, {
  5088. method: 'PUT',
  5089. body: JSON.stringify(data),
  5090. }),
  5091. deleteLibraryFile: (id: number) =>
  5092. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  5093. // ========== Library Trash (#1008) ==========
  5094. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5095. request<LibraryPurgePreview>(
  5096. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  5097. ),
  5098. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5099. request<{ moved_to_trash: number }>('/library/purge', {
  5100. method: 'POST',
  5101. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  5102. }),
  5103. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  5104. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  5105. restoreLibraryTrash: (fileId: number) =>
  5106. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  5107. hardDeleteLibraryTrash: (fileId: number) =>
  5108. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  5109. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  5110. getLibraryTrashSettings: () =>
  5111. request<LibraryTrashSettings>('/library/trash/settings'),
  5112. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  5113. request<LibraryTrashSettings>('/library/trash/settings', {
  5114. method: 'PUT',
  5115. body: JSON.stringify(body),
  5116. }),
  5117. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  5118. createLibrarySlicerToken: (fileId: number) =>
  5119. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  5120. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  5121. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  5122. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  5123. const headers: Record<string, string> = {};
  5124. if (authToken) {
  5125. headers['Authorization'] = `Bearer ${authToken}`;
  5126. }
  5127. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  5128. if (!response.ok) {
  5129. const error = await response.json().catch(() => ({}));
  5130. throw new Error(error.detail || `HTTP ${response.status}`);
  5131. }
  5132. const disposition = response.headers.get('Content-Disposition');
  5133. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  5134. const blob = await response.blob();
  5135. const url = window.URL.createObjectURL(blob);
  5136. const a = document.createElement('a');
  5137. a.href = url;
  5138. a.download = downloadFilename;
  5139. document.body.appendChild(a);
  5140. a.click();
  5141. document.body.removeChild(a);
  5142. window.URL.revokeObjectURL(url);
  5143. },
  5144. getLibraryFileThumbnailUrl: (id: number) => withStreamToken(`${API_BASE}/library/files/${id}/thumbnail`),
  5145. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  5146. withStreamToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  5147. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  5148. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  5149. request<{ status: string; moved: number }>('/library/files/move', {
  5150. method: 'POST',
  5151. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  5152. }),
  5153. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  5154. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  5155. method: 'POST',
  5156. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  5157. }),
  5158. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  5159. batchGenerateStlThumbnails: (options: {
  5160. file_ids?: number[];
  5161. folder_id?: number;
  5162. all_missing?: boolean;
  5163. }) =>
  5164. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  5165. method: 'POST',
  5166. body: JSON.stringify(options),
  5167. }),
  5168. addLibraryFilesToQueue: (fileIds: number[]) =>
  5169. request<AddToQueueResponse>('/library/files/add-to-queue', {
  5170. method: 'POST',
  5171. body: JSON.stringify({ file_ids: fileIds }),
  5172. }),
  5173. printLibraryFile: (
  5174. fileId: number,
  5175. printerId: number,
  5176. options?: {
  5177. plate_id?: number;
  5178. plate_name?: string;
  5179. ams_mapping?: number[];
  5180. bed_levelling?: boolean;
  5181. flow_cali?: boolean;
  5182. vibration_cali?: boolean;
  5183. layer_inspect?: boolean;
  5184. timelapse?: boolean;
  5185. use_ams?: boolean;
  5186. project_id?: number;
  5187. cleanup_library_after_dispatch?: boolean;
  5188. }
  5189. ) =>
  5190. request<BackgroundDispatchResponse>(
  5191. `/library/files/${fileId}/print?printer_id=${printerId}`,
  5192. {
  5193. method: 'POST',
  5194. body: options ? JSON.stringify(options) : undefined,
  5195. }
  5196. ),
  5197. cancelBackgroundDispatchJob: (jobId: number) =>
  5198. request<{
  5199. status: 'cancelled' | 'cancelling';
  5200. job_id: number;
  5201. source_name: string;
  5202. printer_id: number;
  5203. printer_name: string;
  5204. }>(`/background-dispatch/${jobId}`, {
  5205. method: 'DELETE',
  5206. }),
  5207. getLibraryFilePlates: (fileId: number) =>
  5208. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  5209. getLibraryFileFilamentRequirements: (
  5210. fileId: number,
  5211. plateId?: number,
  5212. requestId?: string,
  5213. // Optional bundle context — see getArchiveFilamentRequirements above
  5214. // for the contract. Same shape so callers can share a builder helper.
  5215. bundle?: {
  5216. bundle_id: string;
  5217. printer_name: string;
  5218. process_name: string;
  5219. filament_names: string[];
  5220. },
  5221. ) => {
  5222. const qs = new URLSearchParams();
  5223. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5224. if (requestId) qs.set('request_id', requestId);
  5225. if (bundle) {
  5226. qs.set('bundle_id', bundle.bundle_id);
  5227. qs.set('printer_name', bundle.printer_name);
  5228. qs.set('process_name', bundle.process_name);
  5229. qs.set('filament_names', bundle.filament_names.join(';'));
  5230. }
  5231. return request<{
  5232. file_id: number;
  5233. filename: string;
  5234. filaments: Array<{
  5235. slot_id: number;
  5236. type: string;
  5237. color: string;
  5238. used_grams: number;
  5239. used_meters: number;
  5240. used_in_plate?: boolean;
  5241. }>;
  5242. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5243. },
  5244. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  5245. * proxy. Used by the SliceModal's filament-discovery path so the inline
  5246. * spinner + persistent toast can show "Generating G-code (45%)" while
  5247. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  5248. * have an entry — early race window — or it expired) so the poller
  5249. * can keep trying. */
  5250. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  5251. try {
  5252. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  5253. } catch {
  5254. return null;
  5255. }
  5256. },
  5257. // GitHub Backup
  5258. getGitHubBackupConfig: () =>
  5259. request<GitHubBackupConfig | null>('/github-backup/config'),
  5260. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  5261. request<GitHubBackupConfig>('/github-backup/config', {
  5262. method: 'POST',
  5263. body: JSON.stringify(config),
  5264. }),
  5265. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  5266. request<GitHubBackupConfig>('/github-backup/config', {
  5267. method: 'PATCH',
  5268. body: JSON.stringify(config),
  5269. }),
  5270. deleteGitHubBackupConfig: () =>
  5271. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  5272. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  5273. request<GitHubTestConnectionResponse>(
  5274. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}&provider=${encodeURIComponent(provider)}`,
  5275. { method: 'POST' }
  5276. ),
  5277. testGitHubStoredConnection: () =>
  5278. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  5279. triggerGitHubBackup: () =>
  5280. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  5281. getGitHubBackupStatus: () =>
  5282. request<GitHubBackupStatus>('/github-backup/status'),
  5283. getGitHubBackupLogs: (limit: number = 50) =>
  5284. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  5285. clearGitHubBackupLogs: (keepLast: number = 10) =>
  5286. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  5287. // Scheduled local backups
  5288. getLocalBackupStatus: () =>
  5289. request<LocalBackupStatus>('/local-backup/status'),
  5290. triggerLocalBackup: () =>
  5291. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  5292. getLocalBackups: () =>
  5293. request<LocalBackupFile[]>('/local-backup/backups'),
  5294. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  5295. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  5296. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5297. });
  5298. if (!response.ok) throw new Error('Download failed');
  5299. const blob = await response.blob();
  5300. return { blob, filename };
  5301. },
  5302. restoreLocalBackup: (filename: string) =>
  5303. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  5304. deleteLocalBackup: (filename: string) =>
  5305. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  5306. // Obico AI failure detection
  5307. getObicoStatus: () =>
  5308. request<ObicoStatus>('/obico/status'),
  5309. testObicoConnection: (url: string) =>
  5310. request<ObicoTestConnection>('/obico/test-connection', {
  5311. method: 'POST',
  5312. body: JSON.stringify({ url }),
  5313. }),
  5314. // Slicer API — slice in the background. Both endpoints return 202 + a
  5315. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  5316. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  5317. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  5318. method: 'POST',
  5319. body: JSON.stringify(body),
  5320. }),
  5321. sliceArchive: (archiveId: number, body: SliceRequest) =>
  5322. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  5323. method: 'POST',
  5324. body: JSON.stringify(body),
  5325. }),
  5326. getSliceJob: (jobId: number) =>
  5327. request<SliceJobState>(`/slice-jobs/${jobId}`),
  5328. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  5329. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  5330. // backend/app/api/routes/slicer_presets.py for the priority rules.
  5331. getSlicerPresets: () =>
  5332. request<UnifiedPresetsResponse>('/slicer/presets'),
  5333. // Slicer Bundles (.bbscfg) — Printer Preset Bundles imported from BambuStudio.
  5334. // Settings → Slicer Bundles uploads/lists/deletes; the SliceModal picks
  5335. // presets by name from a chosen bundle (separate follow-up).
  5336. listSlicerBundles: () =>
  5337. request<SlicerBundle[]>('/slicer/bundles'),
  5338. importSlicerBundle: (file: File) => {
  5339. // The /slicer/bundles upload accepts multipart with field name "file"
  5340. // (matches the FastAPI route's UploadFile parameter). Bypass `request`
  5341. // because it always JSON-stringifies the body — multipart needs the
  5342. // browser to set the boundary in the Content-Type header.
  5343. const fd = new FormData();
  5344. fd.append('file', file);
  5345. return fetch(`${API_BASE}/slicer/bundles`, {
  5346. method: 'POST',
  5347. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5348. body: fd,
  5349. }).then(async (res) => {
  5350. if (!res.ok) {
  5351. const err = await res.json().catch(() => ({}));
  5352. throw new Error(err.detail || `HTTP ${res.status}`);
  5353. }
  5354. return res.json() as Promise<SlicerBundle>;
  5355. });
  5356. },
  5357. deleteSlicerBundle: (bundleId: string) =>
  5358. request<void>(`/slicer/bundles/${encodeURIComponent(bundleId)}`, {
  5359. method: 'DELETE',
  5360. }),
  5361. // Local Presets (OrcaSlicer imports)
  5362. getLocalPresets: () =>
  5363. request<LocalPresetsResponse>('/local-presets/'),
  5364. getLocalPresetDetail: (id: number) =>
  5365. request<LocalPresetDetail>(`/local-presets/${id}`),
  5366. importLocalPresets: (formData: FormData) =>
  5367. fetch(`${API_BASE}/local-presets/import`, {
  5368. method: 'POST',
  5369. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5370. body: formData,
  5371. }).then(async (res) => {
  5372. if (!res.ok) {
  5373. const err = await res.json().catch(() => ({}));
  5374. throw new Error(err.detail || `HTTP ${res.status}`);
  5375. }
  5376. return res.json() as Promise<ImportResponse>;
  5377. }),
  5378. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  5379. request<LocalPreset>('/local-presets/', {
  5380. method: 'POST',
  5381. body: JSON.stringify(data),
  5382. }),
  5383. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  5384. request<LocalPreset>(`/local-presets/${id}`, {
  5385. method: 'PUT',
  5386. body: JSON.stringify(data),
  5387. }),
  5388. deleteLocalPreset: (id: number) =>
  5389. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  5390. refreshBaseProfileCache: () =>
  5391. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  5392. };
  5393. // AMS History types
  5394. export interface AMSHistoryPoint {
  5395. recorded_at: string;
  5396. humidity: number | null;
  5397. humidity_raw: number | null;
  5398. temperature: number | null;
  5399. }
  5400. export interface AMSHistoryResponse {
  5401. printer_id: number;
  5402. ams_id: number;
  5403. data: AMSHistoryPoint[];
  5404. min_humidity: number | null;
  5405. max_humidity: number | null;
  5406. avg_humidity: number | null;
  5407. min_temperature: number | null;
  5408. max_temperature: number | null;
  5409. avg_temperature: number | null;
  5410. }
  5411. // System Info types
  5412. export interface SystemInfo {
  5413. app: {
  5414. version: string;
  5415. base_dir: string;
  5416. archive_dir: string;
  5417. };
  5418. database: {
  5419. engine: string;
  5420. version: string;
  5421. archives: number;
  5422. archives_completed: number;
  5423. archives_failed: number;
  5424. archives_printing: number;
  5425. printers: number;
  5426. filaments: number;
  5427. projects: number;
  5428. smart_plugs: number;
  5429. total_print_time_seconds: number;
  5430. total_print_time_formatted: string;
  5431. total_filament_grams: number;
  5432. total_filament_kg: number;
  5433. };
  5434. printers: {
  5435. total: number;
  5436. connected: number;
  5437. connected_list: Array<{
  5438. id: number;
  5439. name: string;
  5440. state: string;
  5441. model: string;
  5442. }>;
  5443. };
  5444. storage: {
  5445. archive_size_bytes: number;
  5446. archive_size_formatted: string;
  5447. database_size_bytes: number;
  5448. database_size_formatted: string;
  5449. disk_total_bytes: number;
  5450. disk_total_formatted: string;
  5451. disk_used_bytes: number;
  5452. disk_used_formatted: string;
  5453. disk_free_bytes: number;
  5454. disk_free_formatted: string;
  5455. disk_percent_used: number;
  5456. };
  5457. system: {
  5458. platform: string;
  5459. platform_release: string;
  5460. platform_version: string;
  5461. architecture: string;
  5462. hostname: string;
  5463. python_version: string;
  5464. uptime_seconds: number;
  5465. uptime_formatted: string;
  5466. boot_time: string;
  5467. };
  5468. memory: {
  5469. total_bytes: number;
  5470. total_formatted: string;
  5471. available_bytes: number;
  5472. available_formatted: string;
  5473. used_bytes: number;
  5474. used_formatted: string;
  5475. percent_used: number;
  5476. };
  5477. cpu: {
  5478. count: number;
  5479. count_logical: number;
  5480. percent: number;
  5481. };
  5482. }
  5483. export interface StorageUsageCategory {
  5484. key: string;
  5485. label: string;
  5486. bytes: number;
  5487. formatted: string;
  5488. percent_of_total: number;
  5489. }
  5490. export interface StorageUsageOtherItem {
  5491. bucket: string;
  5492. label: string;
  5493. kind: 'system' | 'data';
  5494. deletable: boolean;
  5495. bytes: number;
  5496. formatted: string;
  5497. percent_of_total: number;
  5498. }
  5499. export interface StorageUsageResponse {
  5500. roots: string[];
  5501. total_bytes: number;
  5502. total_formatted: string;
  5503. categories: StorageUsageCategory[];
  5504. other_breakdown: StorageUsageOtherItem[];
  5505. scan_errors: number;
  5506. generated_at: string;
  5507. cache: {
  5508. hit: boolean;
  5509. age_seconds: number;
  5510. max_age_seconds: number;
  5511. };
  5512. }
  5513. // Library (File Manager) types
  5514. export interface LibraryFolderTree {
  5515. id: number;
  5516. name: string;
  5517. parent_id: number | null;
  5518. project_id: number | null;
  5519. archive_id: number | null;
  5520. project_name: string | null;
  5521. archive_name: string | null;
  5522. is_external: boolean;
  5523. external_path: string | null;
  5524. external_readonly: boolean;
  5525. file_count: number;
  5526. children: LibraryFolderTree[];
  5527. }
  5528. export interface LibraryFolder {
  5529. id: number;
  5530. name: string;
  5531. parent_id: number | null;
  5532. project_id: number | null;
  5533. archive_id: number | null;
  5534. project_name: string | null;
  5535. archive_name: string | null;
  5536. is_external: boolean;
  5537. external_path: string | null;
  5538. external_readonly: boolean;
  5539. external_show_hidden: boolean;
  5540. file_count: number;
  5541. created_at: string;
  5542. updated_at: string;
  5543. }
  5544. export interface LibraryFolderCreate {
  5545. name: string;
  5546. parent_id?: number | null;
  5547. project_id?: number | null;
  5548. archive_id?: number | null;
  5549. }
  5550. export interface ExternalFolderCreate {
  5551. name: string;
  5552. external_path: string;
  5553. readonly?: boolean;
  5554. show_hidden?: boolean;
  5555. parent_id?: number | null;
  5556. }
  5557. export interface LibraryFolderUpdate {
  5558. name?: string;
  5559. parent_id?: number | null;
  5560. project_id?: number | null; // 0 to unlink
  5561. archive_id?: number | null; // 0 to unlink
  5562. }
  5563. export interface LibraryFileDuplicate {
  5564. id: number;
  5565. filename: string;
  5566. folder_id: number | null;
  5567. folder_name: string | null;
  5568. created_at: string;
  5569. }
  5570. export interface LibraryFile {
  5571. id: number;
  5572. folder_id: number | null;
  5573. folder_name: string | null;
  5574. project_id: number | null;
  5575. project_name: string | null;
  5576. is_external: boolean;
  5577. filename: string;
  5578. file_path: string;
  5579. file_type: string;
  5580. file_size: number;
  5581. file_hash: string | null;
  5582. thumbnail_path: string | null;
  5583. metadata: Record<string, unknown> | null;
  5584. print_count: number;
  5585. last_printed_at: string | null;
  5586. notes: string | null;
  5587. duplicates: LibraryFileDuplicate[] | null;
  5588. duplicate_count: number;
  5589. // User tracking (Issue #206)
  5590. created_by_id: number | null;
  5591. created_by_username: string | null;
  5592. created_at: string;
  5593. updated_at: string;
  5594. // Metadata fields
  5595. print_name: string | null;
  5596. print_time_seconds: number | null;
  5597. filament_used_grams: number | null;
  5598. sliced_for_model: string | null;
  5599. }
  5600. export interface LibraryFileListItem {
  5601. id: number;
  5602. folder_id: number | null;
  5603. is_external: boolean;
  5604. filename: string;
  5605. file_type: string;
  5606. file_size: number;
  5607. thumbnail_path: string | null;
  5608. print_count: number;
  5609. duplicate_count: number;
  5610. // User tracking (Issue #206)
  5611. created_by_id: number | null;
  5612. created_by_username: string | null;
  5613. created_at: string;
  5614. print_name: string | null;
  5615. print_time_seconds: number | null;
  5616. filament_used_grams: number | null;
  5617. sliced_for_model: string | null;
  5618. }
  5619. export interface LibraryFileUpdate {
  5620. filename?: string;
  5621. folder_id?: number | null;
  5622. project_id?: number | null;
  5623. notes?: string | null;
  5624. }
  5625. // Library trash (#1008)
  5626. export interface LibraryTrashItem {
  5627. id: number;
  5628. filename: string;
  5629. file_size: number;
  5630. thumbnail_path: string | null;
  5631. folder_id: number | null;
  5632. folder_name: string | null;
  5633. created_by_id: number | null;
  5634. created_by_username: string | null;
  5635. deleted_at: string;
  5636. auto_purge_at: string;
  5637. }
  5638. export interface LibraryTrashListResponse {
  5639. items: LibraryTrashItem[];
  5640. total: number;
  5641. retention_days: number;
  5642. }
  5643. export interface LibraryPurgePreview {
  5644. count: number;
  5645. total_bytes: number;
  5646. sample_filenames: string[];
  5647. older_than_days: number;
  5648. include_never_printed: boolean;
  5649. }
  5650. export interface LibraryTrashSettings {
  5651. retention_days: number;
  5652. auto_purge_enabled: boolean;
  5653. auto_purge_days: number;
  5654. auto_purge_include_never_printed: boolean;
  5655. }
  5656. export interface ArchivePurgePreview {
  5657. count: number;
  5658. total_bytes: number;
  5659. sample_filenames: string[];
  5660. older_than_days: number;
  5661. }
  5662. export interface ArchivePurgeSettings {
  5663. enabled: boolean;
  5664. days: number;
  5665. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  5666. // contribution drops from Quick Stats too. Default false — soft-delete,
  5667. // Quick Stats preserved.
  5668. purge_stats: boolean;
  5669. }
  5670. export interface LibraryFileUploadResponse {
  5671. id: number;
  5672. filename: string;
  5673. file_type: string;
  5674. file_size: number;
  5675. thumbnail_path: string | null;
  5676. duplicate_of: number | null;
  5677. metadata: Record<string, unknown> | null;
  5678. }
  5679. export interface LibraryStats {
  5680. total_files: number;
  5681. total_folders: number;
  5682. total_size_bytes: number;
  5683. files_by_type: Record<string, number>;
  5684. total_prints: number;
  5685. disk_free_bytes: number;
  5686. disk_total_bytes: number;
  5687. disk_used_bytes: number;
  5688. }
  5689. export interface ZipExtractResult {
  5690. filename: string;
  5691. file_id: number;
  5692. folder_id: number | null;
  5693. }
  5694. export interface ZipExtractError {
  5695. filename: string;
  5696. error: string;
  5697. }
  5698. export interface ZipExtractResponse {
  5699. extracted: number;
  5700. folders_created: number;
  5701. files: ZipExtractResult[];
  5702. errors: ZipExtractError[];
  5703. }
  5704. // STL Thumbnail Generation types
  5705. export interface BatchThumbnailResult {
  5706. file_id: number;
  5707. filename: string;
  5708. success: boolean;
  5709. error?: string | null;
  5710. }
  5711. export interface BatchThumbnailResponse {
  5712. processed: number;
  5713. succeeded: number;
  5714. failed: number;
  5715. results: BatchThumbnailResult[];
  5716. }
  5717. // Library Queue types
  5718. export interface AddToQueueResult {
  5719. file_id: number;
  5720. filename: string;
  5721. queue_item_id: number;
  5722. archive_id: number;
  5723. }
  5724. export interface AddToQueueError {
  5725. file_id: number;
  5726. filename: string;
  5727. error: string;
  5728. }
  5729. export interface AddToQueueResponse {
  5730. added: AddToQueueResult[];
  5731. errors: AddToQueueError[];
  5732. }
  5733. // Discovery types
  5734. export interface DiscoveredPrinter {
  5735. serial: string;
  5736. name: string;
  5737. ip_address: string;
  5738. model: string | null;
  5739. discovered_at: string | null;
  5740. }
  5741. export interface DiscoveryStatus {
  5742. running: boolean;
  5743. }
  5744. export interface DiscoveryInfo {
  5745. is_docker: boolean;
  5746. ssdp_running: boolean;
  5747. scan_running: boolean;
  5748. subnets: string[];
  5749. }
  5750. export interface SubnetScanStatus {
  5751. running: boolean;
  5752. scanned: number;
  5753. total: number;
  5754. }
  5755. // Discovery API
  5756. export const discoveryApi = {
  5757. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  5758. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  5759. startDiscovery: (duration: number = 10) =>
  5760. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  5761. stopDiscovery: () =>
  5762. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  5763. getDiscoveredPrinters: () =>
  5764. request<DiscoveredPrinter[]>('/discovery/printers'),
  5765. // Subnet scanning (for Docker environments)
  5766. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  5767. request<SubnetScanStatus>('/discovery/scan', {
  5768. method: 'POST',
  5769. body: JSON.stringify({ subnet, timeout }),
  5770. }),
  5771. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  5772. stopSubnetScan: () =>
  5773. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  5774. };
  5775. // Virtual Printer types
  5776. export type VirtualPrinterMode = 'immediate' | 'queue' | 'review' | 'print_queue' | 'proxy'; // 'queue' is legacy, normalized to 'review'
  5777. export interface VirtualPrinterProxyStatus {
  5778. running: boolean;
  5779. target_host: string;
  5780. ftp_port: number;
  5781. mqtt_port: number;
  5782. ftp_connections: number;
  5783. mqtt_connections: number;
  5784. }
  5785. export interface VirtualPrinterStatus {
  5786. enabled: boolean;
  5787. running: boolean;
  5788. mode: VirtualPrinterMode;
  5789. name: string;
  5790. serial: string;
  5791. model: string;
  5792. model_name: string;
  5793. pending_files: number;
  5794. target_printer_ip?: string; // For proxy mode
  5795. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  5796. }
  5797. export interface VirtualPrinterSettings {
  5798. enabled: boolean;
  5799. access_code_set: boolean;
  5800. mode: VirtualPrinterMode;
  5801. model: string;
  5802. target_printer_id: number | null; // For proxy mode
  5803. remote_interface_ip: string | null; // For SSDP proxy across networks
  5804. tailscale_disabled: boolean;
  5805. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  5806. status: VirtualPrinterStatus;
  5807. }
  5808. export interface NetworkInterface {
  5809. name: string;
  5810. ip: string;
  5811. netmask: string;
  5812. subnet: string;
  5813. is_alias?: boolean;
  5814. label?: string;
  5815. }
  5816. export interface VirtualPrinterModels {
  5817. models: Record<string, string>; // SSDP code -> display name
  5818. default: string;
  5819. }
  5820. export interface PendingUpload {
  5821. id: number;
  5822. filename: string;
  5823. // Resolved name the review card should show — mirrors what archive_print
  5824. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  5825. // back to the stripped filename stem when the 3MF has no embedded title or
  5826. // the operator has chosen the "filename" archive-name source.
  5827. display_name: string;
  5828. file_size: number;
  5829. source_ip: string | null;
  5830. status: string;
  5831. tags: string | null;
  5832. notes: string | null;
  5833. project_id: number | null;
  5834. uploaded_at: string;
  5835. }
  5836. // Virtual Printer API
  5837. export const virtualPrinterApi = {
  5838. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  5839. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  5840. updateSettings: (data: {
  5841. enabled?: boolean;
  5842. access_code?: string;
  5843. mode?: 'immediate' | 'review' | 'print_queue' | 'proxy';
  5844. model?: string;
  5845. target_printer_id?: number;
  5846. remote_interface_ip?: string;
  5847. tailscale_disabled?: boolean;
  5848. archive_name_source?: 'metadata' | 'filename';
  5849. }) => {
  5850. const params = new URLSearchParams();
  5851. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  5852. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  5853. if (data.mode !== undefined) params.set('mode', data.mode);
  5854. if (data.model !== undefined) params.set('model', data.model);
  5855. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  5856. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  5857. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  5858. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  5859. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  5860. method: 'PUT',
  5861. });
  5862. },
  5863. };
  5864. // Multi Virtual Printer API
  5865. export interface VirtualPrinterConfig {
  5866. id: number;
  5867. name: string;
  5868. enabled: boolean;
  5869. mode: VirtualPrinterMode;
  5870. model: string | null;
  5871. model_name: string | null;
  5872. access_code_set: boolean;
  5873. serial: string;
  5874. target_printer_id: number | null;
  5875. auto_dispatch: boolean;
  5876. queue_force_color_match: boolean;
  5877. tailscale_disabled: boolean;
  5878. bind_ip: string | null;
  5879. remote_interface_ip: string | null;
  5880. position: number;
  5881. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  5882. }
  5883. export interface VirtualPrinterListResponse {
  5884. printers: VirtualPrinterConfig[];
  5885. models: Record<string, string>;
  5886. }
  5887. export const multiVirtualPrinterApi = {
  5888. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  5889. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  5890. create: (data: {
  5891. name?: string;
  5892. enabled?: boolean;
  5893. mode?: string;
  5894. model?: string;
  5895. access_code?: string;
  5896. target_printer_id?: number;
  5897. auto_dispatch?: boolean;
  5898. queue_force_color_match?: boolean;
  5899. bind_ip?: string;
  5900. remote_interface_ip?: string;
  5901. }) =>
  5902. request<VirtualPrinterConfig>('/virtual-printers', {
  5903. method: 'POST',
  5904. body: JSON.stringify(data),
  5905. }),
  5906. update: (id: number, data: {
  5907. name?: string;
  5908. enabled?: boolean;
  5909. mode?: string;
  5910. model?: string;
  5911. access_code?: string;
  5912. target_printer_id?: number;
  5913. auto_dispatch?: boolean;
  5914. queue_force_color_match?: boolean;
  5915. tailscale_disabled?: boolean;
  5916. bind_ip?: string;
  5917. remote_interface_ip?: string;
  5918. }) =>
  5919. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  5920. method: 'PUT',
  5921. body: JSON.stringify(data),
  5922. }),
  5923. remove: (id: number) =>
  5924. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  5925. method: 'DELETE',
  5926. }),
  5927. getTailscaleStatus: () =>
  5928. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  5929. };
  5930. export interface TailscaleStatusResponse {
  5931. available: boolean;
  5932. fqdn: string;
  5933. hostname: string;
  5934. tailnet_name: string;
  5935. tailscale_ips: string[];
  5936. error: string | null;
  5937. }
  5938. // Pending Uploads API
  5939. export const pendingUploadsApi = {
  5940. list: () => request<PendingUpload[]>('/pending-uploads/'),
  5941. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  5942. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  5943. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  5944. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  5945. method: 'POST',
  5946. body: JSON.stringify(data || {}),
  5947. }),
  5948. discard: (id: number) =>
  5949. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  5950. archiveAll: () =>
  5951. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  5952. discardAll: () =>
  5953. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  5954. };
  5955. // Firmware API Types
  5956. export interface AvailableFirmwareVersion {
  5957. version: string;
  5958. file_available: boolean;
  5959. download_url: string | null;
  5960. release_notes: string | null;
  5961. release_time: string | null;
  5962. }
  5963. export interface FirmwareUpdateInfo {
  5964. printer_id: number;
  5965. printer_name: string;
  5966. model: string | null;
  5967. current_version: string | null;
  5968. latest_version: string | null;
  5969. update_available: boolean;
  5970. download_url: string | null;
  5971. release_notes: string | null;
  5972. available_versions: AvailableFirmwareVersion[];
  5973. }
  5974. export interface FirmwareUploadPrepare {
  5975. can_proceed: boolean;
  5976. sd_card_present: boolean;
  5977. sd_card_free_space: number;
  5978. firmware_size: number;
  5979. space_sufficient: boolean;
  5980. update_available: boolean;
  5981. current_version: string | null;
  5982. latest_version: string | null;
  5983. target_version: string | null;
  5984. firmware_filename: string | null;
  5985. errors: string[];
  5986. }
  5987. export interface FirmwareUploadStatus {
  5988. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  5989. progress: number;
  5990. message: string;
  5991. error: string | null;
  5992. firmware_filename: string | null;
  5993. firmware_version: string | null;
  5994. }
  5995. // Firmware API
  5996. export const firmwareApi = {
  5997. checkUpdates: () =>
  5998. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  5999. checkPrinterUpdate: (printerId: number) =>
  6000. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  6001. prepareUpload: (printerId: number, version?: string) =>
  6002. request<FirmwareUploadPrepare>(
  6003. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  6004. ),
  6005. startUpload: (printerId: number, version?: string) =>
  6006. request<{ started: boolean; message: string }>(
  6007. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  6008. { method: 'POST' },
  6009. ),
  6010. getUploadStatus: (printerId: number) =>
  6011. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  6012. };
  6013. // Support types
  6014. export interface DebugLoggingState {
  6015. enabled: boolean;
  6016. enabled_at: string | null;
  6017. duration_seconds: number | null;
  6018. }
  6019. export interface LogEntry {
  6020. timestamp: string;
  6021. level: string;
  6022. logger_name: string;
  6023. message: string;
  6024. }
  6025. export interface LogsResponse {
  6026. entries: LogEntry[];
  6027. total_in_file: number;
  6028. filtered_count: number;
  6029. }
  6030. // Support API
  6031. export const supportApi = {
  6032. getDebugLoggingState: () =>
  6033. request<DebugLoggingState>('/support/debug-logging'),
  6034. setDebugLogging: (enabled: boolean) =>
  6035. request<DebugLoggingState>('/support/debug-logging', {
  6036. method: 'POST',
  6037. body: JSON.stringify({ enabled }),
  6038. }),
  6039. downloadSupportBundle: async () => {
  6040. const headers: Record<string, string> = {};
  6041. if (authToken) {
  6042. headers['Authorization'] = `Bearer ${authToken}`;
  6043. }
  6044. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  6045. if (!response.ok) {
  6046. const error = await response.json().catch(() => ({}));
  6047. throw new Error(error.detail || `HTTP ${response.status}`);
  6048. }
  6049. // Get filename from Content-Disposition header or use default
  6050. const disposition = response.headers.get('Content-Disposition');
  6051. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  6052. // Download the blob
  6053. const blob = await response.blob();
  6054. const url = window.URL.createObjectURL(blob);
  6055. const a = document.createElement('a');
  6056. a.href = url;
  6057. a.download = filename;
  6058. document.body.appendChild(a);
  6059. a.click();
  6060. document.body.removeChild(a);
  6061. window.URL.revokeObjectURL(url);
  6062. },
  6063. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  6064. const searchParams = new URLSearchParams();
  6065. if (params?.limit) searchParams.set('limit', params.limit.toString());
  6066. if (params?.level) searchParams.set('level', params.level);
  6067. if (params?.search) searchParams.set('search', params.search);
  6068. const query = searchParams.toString();
  6069. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  6070. },
  6071. clearLogs: () =>
  6072. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  6073. };
  6074. // SpoolBuddy types
  6075. export interface SpoolBuddyDevice {
  6076. id: number;
  6077. device_id: string;
  6078. hostname: string;
  6079. ip_address: string;
  6080. backend_url?: string | null;
  6081. firmware_version: string | null;
  6082. has_nfc: boolean;
  6083. has_scale: boolean;
  6084. tare_offset: number;
  6085. calibration_factor: number;
  6086. nfc_reader_type: string | null;
  6087. nfc_connection: string | null;
  6088. display_brightness: number;
  6089. display_blank_timeout: number;
  6090. has_backlight: boolean;
  6091. last_calibrated_at: string | null;
  6092. last_seen: string | null;
  6093. pending_command: string | null;
  6094. nfc_ok: boolean;
  6095. scale_ok: boolean;
  6096. uptime_s: number;
  6097. update_status: string | null;
  6098. update_message: string | null;
  6099. system_stats: {
  6100. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  6101. cpu_temp_c?: number;
  6102. cpu_count?: number;
  6103. load_avg?: number[];
  6104. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  6105. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  6106. system_uptime_s?: number;
  6107. } | null;
  6108. online: boolean;
  6109. }
  6110. export interface DaemonUpdateCheck {
  6111. current_version: string;
  6112. latest_version: string | null;
  6113. update_available: boolean;
  6114. }
  6115. // SpoolBuddy API
  6116. export const spoolbuddyApi = {
  6117. getDevices: () =>
  6118. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  6119. deleteDevice: (deviceId: string) =>
  6120. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  6121. method: 'DELETE',
  6122. }),
  6123. tare: (deviceId: string) =>
  6124. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  6125. method: 'POST',
  6126. body: '{}',
  6127. }),
  6128. getCalibration: (deviceId: string) =>
  6129. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration`),
  6130. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  6131. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  6132. method: 'POST',
  6133. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  6134. }),
  6135. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  6136. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  6137. method: 'POST',
  6138. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  6139. }),
  6140. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  6141. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  6142. method: 'PUT',
  6143. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  6144. }),
  6145. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  6146. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  6147. method: 'POST',
  6148. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  6149. }),
  6150. checkDaemonUpdate: (deviceId: string) =>
  6151. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  6152. triggerUpdate: (deviceId: string) =>
  6153. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  6154. method: 'POST',
  6155. body: '{}',
  6156. }),
  6157. getSSHPublicKey: () =>
  6158. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  6159. writeTag: (deviceId: string, spoolId: number) =>
  6160. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  6161. method: 'POST',
  6162. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  6163. }),
  6164. cancelWrite: (deviceId: string) =>
  6165. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  6166. method: 'POST',
  6167. body: '{}',
  6168. }),
  6169. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  6170. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  6171. method: 'POST',
  6172. body: JSON.stringify({ command }),
  6173. }),
  6174. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  6175. request<{ status: string; diagnostic: string; message: string }>(
  6176. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  6177. { method: 'POST', body: '{}' }
  6178. ),
  6179. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  6180. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  6181. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  6182. { method: 'GET' }
  6183. ),
  6184. };
  6185. export interface BugReportRequest {
  6186. description: string;
  6187. email?: string;
  6188. screenshot_base64?: string;
  6189. include_support_info?: boolean;
  6190. debug_logs?: string;
  6191. }
  6192. export interface BugReportResponse {
  6193. success: boolean;
  6194. message: string;
  6195. issue_url?: string;
  6196. issue_number?: number;
  6197. }
  6198. export const bugReportApi = {
  6199. submit: (data: BugReportRequest) =>
  6200. request<BugReportResponse>('/bug-report/submit', {
  6201. method: 'POST',
  6202. body: JSON.stringify(data),
  6203. }),
  6204. startLogging: () =>
  6205. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  6206. method: 'POST',
  6207. }),
  6208. stopLogging: (wasDebug: boolean) =>
  6209. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  6210. method: 'POST',
  6211. }),
  6212. };