client.ts 239 KB

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