client.ts 220 KB

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