client.ts 229 KB

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