client.ts 237 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998
  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 SliceRequest {
  1288. printer_preset_id?: number;
  1289. process_preset_id?: number;
  1290. filament_preset_id?: number;
  1291. printer_preset?: PresetRef;
  1292. process_preset?: PresetRef;
  1293. filament_preset?: PresetRef;
  1294. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1295. // preferred over the singular `filament_preset` when both are sent; the
  1296. // backend validator promotes a singular into a one-element list when this
  1297. // is omitted, so legacy single-color clients keep working unchanged.
  1298. filament_presets?: PresetRef[];
  1299. plate?: number;
  1300. export_3mf?: boolean;
  1301. // Build-plate override (#1337). When omitted, the slicer uses the process
  1302. // preset's curr_bed_type as-is. Canonical values match BambuStudio /
  1303. // OrcaSlicer's enum: "Cool Plate", "Engineering Plate", "High Temp Plate",
  1304. // "Textured PEI Plate", "Smooth PEI Plate", "Cool Plate (SuperTack)",
  1305. // "Supertack Plate".
  1306. bed_type?: string | null;
  1307. }
  1308. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1309. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1310. export interface UnifiedPreset {
  1311. id: string;
  1312. name: string;
  1313. source: PresetSource;
  1314. // Populated for the filament slot only — used by the SliceModal multi-color
  1315. // pre-pick to score presets against each plate slot's required (type,
  1316. // colour). Optional because the bundled / standard tier rarely carries a
  1317. // colour (colour is a runtime spool attribute on Bambu) and older API
  1318. // responses pre-date these fields entirely.
  1319. filament_type?: string | null;
  1320. filament_colour?: string | null;
  1321. // Printer-preset names a process / filament preset declares itself
  1322. // compatible with. Populated for the local tier (the slicer's own
  1323. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1324. // the process / filament dropdowns by the selected printer using this when
  1325. // present (#1325).
  1326. compatible_printers?: string[] | null;
  1327. }
  1328. export interface UnifiedPresetsBySlot {
  1329. printer: UnifiedPreset[];
  1330. process: UnifiedPreset[];
  1331. filament: UnifiedPreset[];
  1332. }
  1333. export interface UnifiedPresetsResponse {
  1334. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  1335. // dedup — every tier surfaces its full list so the user can pick from
  1336. // any source. The order drives auto-pick + visual group rendering only.
  1337. orca_cloud: UnifiedPresetsBySlot;
  1338. cloud: UnifiedPresetsBySlot;
  1339. local: UnifiedPresetsBySlot;
  1340. standard: UnifiedPresetsBySlot;
  1341. cloud_status: SlicerCloudStatus;
  1342. orca_cloud_status: SlicerCloudStatus;
  1343. }
  1344. export interface SliceResponse {
  1345. library_file_id: number;
  1346. name: string;
  1347. print_time_seconds: number;
  1348. filament_used_g: number;
  1349. filament_used_mm: number;
  1350. used_embedded_settings: boolean;
  1351. }
  1352. export interface SliceArchiveResponse {
  1353. archive_id: number;
  1354. name: string;
  1355. print_time_seconds: number;
  1356. filament_used_g: number;
  1357. filament_used_mm: number;
  1358. used_embedded_settings: boolean;
  1359. }
  1360. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  1361. // the frontend polls /slice-jobs/{id} until status is terminal.
  1362. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  1363. export interface SliceJobEnqueueResponse {
  1364. job_id: number;
  1365. status: SliceJobStatus;
  1366. status_url: string;
  1367. }
  1368. export interface SliceJobProgress {
  1369. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  1370. stage: string;
  1371. total_percent: number;
  1372. plate_percent: number;
  1373. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  1374. plate_index: number;
  1375. plate_count: number;
  1376. updated_at: number;
  1377. /** When the backend is in the cross-class slice-all loop (#1493), each
  1378. * per-plate sub-slice's progress is augmented with the loop position
  1379. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  1380. * fields are absent on a single-plate slice. */
  1381. multi_plate_index?: number;
  1382. multi_plate_count?: number;
  1383. }
  1384. export interface SliceJobState {
  1385. job_id: number;
  1386. status: SliceJobStatus;
  1387. kind: 'library_file' | 'archive';
  1388. source_id: number;
  1389. source_name: string;
  1390. created_at: string;
  1391. started_at: string | null;
  1392. completed_at: string | null;
  1393. /** Live progress fed by the sidecar's --pipe channel; null until the
  1394. * slicer emits its first frame (early "Initializing" phase) or when
  1395. * the sidecar doesn't support progress. */
  1396. progress: SliceJobProgress | null;
  1397. result?: SliceResponse | SliceArchiveResponse;
  1398. error_status?: number;
  1399. error_detail?: string;
  1400. }
  1401. // Local preset types (OrcaSlicer imports)
  1402. export interface LocalPreset {
  1403. id: number;
  1404. name: string;
  1405. preset_type: string;
  1406. source: string;
  1407. filament_type: string | null;
  1408. filament_vendor: string | null;
  1409. nozzle_temp_min: number | null;
  1410. nozzle_temp_max: number | null;
  1411. pressure_advance: string | null;
  1412. default_filament_colour: string | null;
  1413. filament_cost: string | null;
  1414. filament_density: string | null;
  1415. compatible_printers: string | null;
  1416. inherits: string | null;
  1417. version: string | null;
  1418. created_at: string;
  1419. updated_at: string;
  1420. }
  1421. export interface LocalPresetDetail extends LocalPreset {
  1422. setting: Record<string, unknown>;
  1423. }
  1424. export interface LocalPresetsResponse {
  1425. filament: LocalPreset[];
  1426. printer: LocalPreset[];
  1427. process: LocalPreset[];
  1428. }
  1429. export interface ImportResponse {
  1430. success: boolean;
  1431. imported: number;
  1432. skipped: number;
  1433. errors: string[];
  1434. }
  1435. export interface FieldOption {
  1436. value: string;
  1437. label: string;
  1438. }
  1439. export interface FieldDefinition {
  1440. key: string;
  1441. label: string;
  1442. type: 'text' | 'number' | 'boolean' | 'select';
  1443. category: string;
  1444. description?: string;
  1445. options?: FieldOption[];
  1446. unit?: string;
  1447. min?: number;
  1448. max?: number;
  1449. step?: number;
  1450. }
  1451. export interface FieldDefinitionsResponse {
  1452. version: string;
  1453. description: string;
  1454. fields: FieldDefinition[];
  1455. }
  1456. export interface CloudDevice {
  1457. dev_id: string;
  1458. name: string;
  1459. dev_model_name: string | null;
  1460. dev_product_name: string | null;
  1461. online: boolean;
  1462. }
  1463. // Smart Plug types
  1464. export interface SmartPlug {
  1465. id: number;
  1466. name: string;
  1467. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1468. ip_address: string | null; // Required for Tasmota
  1469. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  1470. // Home Assistant energy sensor entities (optional)
  1471. ha_power_entity: string | null;
  1472. ha_energy_today_entity: string | null;
  1473. ha_energy_total_entity: string | null;
  1474. // MQTT fields (required when plug_type="mqtt")
  1475. // Legacy field - kept for backward compatibility
  1476. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  1477. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  1478. // Power monitoring
  1479. mqtt_power_topic: string | null; // Topic for power data
  1480. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  1481. mqtt_power_multiplier: number; // Unit conversion for power
  1482. // Energy monitoring
  1483. mqtt_energy_topic: string | null; // Topic for energy data
  1484. mqtt_energy_path: string | null; // e.g., "energy_l1"
  1485. mqtt_energy_multiplier: number; // Unit conversion for energy
  1486. // State monitoring
  1487. mqtt_state_topic: string | null; // Topic for state data
  1488. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  1489. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  1490. // REST/Webhook fields (required when plug_type="rest")
  1491. rest_on_url: string | null;
  1492. rest_on_body: string | null;
  1493. rest_off_url: string | null;
  1494. rest_off_body: string | null;
  1495. rest_method: string | null;
  1496. rest_headers: string | null;
  1497. rest_status_url: string | null;
  1498. rest_status_path: string | null;
  1499. rest_status_on_value: string | null;
  1500. rest_power_url: string | null;
  1501. rest_power_path: string | null;
  1502. rest_power_multiplier: number;
  1503. rest_energy_url: string | null;
  1504. rest_energy_path: string | null;
  1505. rest_energy_multiplier: number;
  1506. printer_id: number | null;
  1507. enabled: boolean;
  1508. auto_on: boolean;
  1509. auto_off: boolean;
  1510. auto_off_persistent: boolean;
  1511. off_delay_mode: 'time' | 'temperature';
  1512. off_delay_minutes: number;
  1513. off_temp_threshold: number;
  1514. // #1349: auto-off after AMS drying completes.
  1515. auto_off_after_drying: boolean;
  1516. off_delay_after_drying_minutes: number;
  1517. username: string | null;
  1518. password: string | null;
  1519. // Power alerts
  1520. power_alert_enabled: boolean;
  1521. power_alert_high: number | null;
  1522. power_alert_low: number | null;
  1523. power_alert_last_triggered: string | null;
  1524. // Schedule
  1525. schedule_enabled: boolean;
  1526. schedule_on_time: string | null;
  1527. schedule_off_time: string | null;
  1528. // Visibility options
  1529. show_in_switchbar: boolean;
  1530. show_on_printer_card: boolean; // For scripts: show on printer card
  1531. // Status
  1532. last_state: string | null;
  1533. last_checked: string | null;
  1534. auto_off_executed: boolean; // True when auto-off was triggered after print
  1535. created_at: string;
  1536. updated_at: string;
  1537. }
  1538. export interface SmartPlugCreate {
  1539. name: string;
  1540. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1541. ip_address?: string | null; // Required for Tasmota
  1542. ha_entity_id?: string | null; // Required for Home Assistant
  1543. // Home Assistant energy sensor entities (optional)
  1544. ha_power_entity?: string | null;
  1545. ha_energy_today_entity?: string | null;
  1546. ha_energy_total_entity?: string | null;
  1547. // MQTT fields (required when plug_type="mqtt")
  1548. // Legacy fields - kept for backward compatibility
  1549. mqtt_topic?: string | null;
  1550. mqtt_multiplier?: number;
  1551. // Power monitoring
  1552. mqtt_power_topic?: string | null;
  1553. mqtt_power_path?: string | null;
  1554. mqtt_power_multiplier?: number;
  1555. // Energy monitoring
  1556. mqtt_energy_topic?: string | null;
  1557. mqtt_energy_path?: string | null;
  1558. mqtt_energy_multiplier?: number;
  1559. // State monitoring
  1560. mqtt_state_topic?: string | null;
  1561. mqtt_state_path?: string | null;
  1562. mqtt_state_on_value?: string | null;
  1563. // REST fields
  1564. rest_on_url?: string | null;
  1565. rest_on_body?: string | null;
  1566. rest_off_url?: string | null;
  1567. rest_off_body?: string | null;
  1568. rest_method?: string | null;
  1569. rest_headers?: string | null;
  1570. rest_status_url?: string | null;
  1571. rest_status_path?: string | null;
  1572. rest_status_on_value?: string | null;
  1573. rest_power_url?: string | null;
  1574. rest_power_path?: string | null;
  1575. rest_power_multiplier?: number;
  1576. rest_energy_url?: string | null;
  1577. rest_energy_path?: string | null;
  1578. rest_energy_multiplier?: number;
  1579. printer_id?: number | null;
  1580. enabled?: boolean;
  1581. auto_on?: boolean;
  1582. auto_off?: boolean;
  1583. auto_off_persistent?: boolean;
  1584. off_delay_mode?: 'time' | 'temperature';
  1585. off_delay_minutes?: number;
  1586. off_temp_threshold?: number;
  1587. // #1349
  1588. auto_off_after_drying?: boolean;
  1589. off_delay_after_drying_minutes?: number;
  1590. username?: string | null;
  1591. password?: string | null;
  1592. // Power alerts
  1593. power_alert_enabled?: boolean;
  1594. power_alert_high?: number | null;
  1595. power_alert_low?: number | null;
  1596. // Schedule
  1597. schedule_enabled?: boolean;
  1598. schedule_on_time?: string | null;
  1599. schedule_off_time?: string | null;
  1600. // Visibility options
  1601. show_in_switchbar?: boolean;
  1602. show_on_printer_card?: boolean;
  1603. }
  1604. export interface SmartPlugUpdate {
  1605. name?: string;
  1606. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  1607. ip_address?: string | null;
  1608. ha_entity_id?: string | null;
  1609. // Home Assistant energy sensor entities (optional)
  1610. ha_power_entity?: string | null;
  1611. ha_energy_today_entity?: string | null;
  1612. ha_energy_total_entity?: string | null;
  1613. // MQTT fields (legacy)
  1614. mqtt_topic?: string | null;
  1615. mqtt_multiplier?: number;
  1616. // MQTT power fields
  1617. mqtt_power_topic?: string | null;
  1618. mqtt_power_path?: string | null;
  1619. mqtt_power_multiplier?: number;
  1620. // MQTT energy fields
  1621. mqtt_energy_topic?: string | null;
  1622. mqtt_energy_path?: string | null;
  1623. mqtt_energy_multiplier?: number;
  1624. // MQTT state fields
  1625. mqtt_state_topic?: string | null;
  1626. mqtt_state_path?: string | null;
  1627. mqtt_state_on_value?: string | null;
  1628. // REST fields
  1629. rest_on_url?: string | null;
  1630. rest_on_body?: string | null;
  1631. rest_off_url?: string | null;
  1632. rest_off_body?: string | null;
  1633. rest_method?: string | null;
  1634. rest_headers?: string | null;
  1635. rest_status_url?: string | null;
  1636. rest_status_path?: string | null;
  1637. rest_status_on_value?: string | null;
  1638. rest_power_url?: string | null;
  1639. rest_power_path?: string | null;
  1640. rest_power_multiplier?: number;
  1641. rest_energy_url?: string | null;
  1642. rest_energy_path?: string | null;
  1643. rest_energy_multiplier?: number;
  1644. printer_id?: number | null;
  1645. enabled?: boolean;
  1646. auto_on?: boolean;
  1647. auto_off?: boolean;
  1648. auto_off_persistent?: boolean;
  1649. off_delay_mode?: 'time' | 'temperature';
  1650. off_delay_minutes?: number;
  1651. off_temp_threshold?: number;
  1652. // #1349
  1653. auto_off_after_drying?: boolean;
  1654. off_delay_after_drying_minutes?: number;
  1655. username?: string | null;
  1656. password?: string | null;
  1657. // Power alerts
  1658. power_alert_enabled?: boolean;
  1659. power_alert_high?: number | null;
  1660. power_alert_low?: number | null;
  1661. // Schedule
  1662. schedule_enabled?: boolean;
  1663. schedule_on_time?: string | null;
  1664. schedule_off_time?: string | null;
  1665. // Visibility options
  1666. show_in_switchbar?: boolean;
  1667. show_on_printer_card?: boolean;
  1668. }
  1669. // Home Assistant entity for smart plug selection
  1670. export interface HAEntity {
  1671. entity_id: string;
  1672. friendly_name: string;
  1673. state: string | null;
  1674. domain: string; // "switch", "light", "input_boolean", "script"
  1675. }
  1676. // Home Assistant sensor entity for energy monitoring
  1677. export interface HASensorEntity {
  1678. entity_id: string;
  1679. friendly_name: string;
  1680. state: string | null;
  1681. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  1682. }
  1683. export interface HATestConnectionResult {
  1684. success: boolean;
  1685. message: string | null;
  1686. error: string | null;
  1687. }
  1688. export interface SmartPlugEnergy {
  1689. power: number | null; // Current watts
  1690. voltage: number | null; // Volts
  1691. current: number | null; // Amps
  1692. today: number | null; // kWh used today
  1693. yesterday: number | null; // kWh used yesterday
  1694. total: number | null; // Total kWh
  1695. factor: number | null; // Power factor (0-1)
  1696. apparent_power: number | null; // VA
  1697. reactive_power: number | null; // VAr
  1698. }
  1699. export interface SmartPlugStatus {
  1700. state: string | null;
  1701. reachable: boolean;
  1702. device_name: string | null;
  1703. energy: SmartPlugEnergy | null;
  1704. }
  1705. export interface SmartPlugTestResult {
  1706. success: boolean;
  1707. state: string | null;
  1708. device_name: string | null;
  1709. }
  1710. // Tasmota Discovery types
  1711. export interface TasmotaScanStatus {
  1712. running: boolean;
  1713. scanned: number;
  1714. total: number;
  1715. }
  1716. export interface DiscoveredTasmotaDevice {
  1717. ip_address: string;
  1718. name: string;
  1719. module: number | null;
  1720. state: string | null;
  1721. discovered_at: string | null;
  1722. }
  1723. // Print Queue types
  1724. export interface PrintQueueItem {
  1725. id: number;
  1726. printer_id: number | null; // null = unassigned
  1727. target_model: string | null; // Target printer model for model-based assignment
  1728. target_location: string | null; // Target location filter for model-based assignment
  1729. required_filament_types: string[] | null; // Required filament types for model-based assignment
  1730. waiting_reason: string | null; // Why a model-based job hasn't started yet
  1731. // Either archive_id OR library_file_id must be set (archive created at print start)
  1732. archive_id: number | null;
  1733. library_file_id: number | null;
  1734. position: number;
  1735. scheduled_time: string | null;
  1736. require_previous_success: boolean;
  1737. auto_off_after: boolean;
  1738. manual_start: boolean; // Requires manual trigger to start (staged)
  1739. // Set by the dispatch scheduler when the assigned spool can't satisfy
  1740. // any required slot's grams (#1496). Surfaced on the queue row as a
  1741. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  1742. filament_short: boolean;
  1743. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  1744. // skips the deficit check for this item (#1698-followup). Set by the
  1745. // start route when skip_filament_check=true, or at queue creation if
  1746. // PrintModal's deficit warning was acknowledged.
  1747. skip_filament_check: boolean;
  1748. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  1749. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  1750. plate_id: number | null; // Plate ID for multi-plate 3MF files
  1751. // Print options
  1752. bed_levelling: boolean;
  1753. flow_cali: boolean;
  1754. vibration_cali: boolean;
  1755. layer_inspect: boolean;
  1756. timelapse: boolean;
  1757. use_ams: boolean;
  1758. nozzle_offset_cali: boolean;
  1759. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  1760. started_at: string | null;
  1761. completed_at: string | null;
  1762. error_message: string | null;
  1763. created_at: string;
  1764. archive_name?: string | null;
  1765. archive_thumbnail?: string | null;
  1766. // True when the linked archive has been soft-deleted; archive_name /
  1767. // archive_thumbnail / downstream metadata are left null in that case so
  1768. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  1769. archive_deleted?: boolean;
  1770. library_file_name?: string | null;
  1771. library_file_thumbnail?: string | null;
  1772. printer_name?: string | null;
  1773. print_time_seconds?: number | null; // Estimated print time from archive or library file
  1774. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  1775. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  1776. // User tracking (Issue #206)
  1777. created_by_id?: number | null;
  1778. created_by_username?: string | null;
  1779. // Batch grouping
  1780. batch_id?: number | null;
  1781. batch_name?: string | null;
  1782. // Shortest-job-first scheduling
  1783. been_jumped?: boolean;
  1784. // Auto-print G-code injection
  1785. gcode_injection?: boolean;
  1786. }
  1787. export interface PrintBatch {
  1788. id: number;
  1789. name: string;
  1790. archive_id: number | null;
  1791. library_file_id: number | null;
  1792. quantity: number;
  1793. status: string;
  1794. created_at: string;
  1795. created_by_id: number | null;
  1796. created_by_username: string | null;
  1797. pending_count: number;
  1798. printing_count: number;
  1799. completed_count: number;
  1800. failed_count: number;
  1801. cancelled_count: number;
  1802. }
  1803. export interface PrintQueueItemCreate {
  1804. printer_id?: number | null; // null = unassigned
  1805. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1806. target_location?: string | null; // Target location filter (only used with target_model)
  1807. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  1808. archive_id?: number | null;
  1809. library_file_id?: number | null;
  1810. scheduled_time?: string | null;
  1811. require_previous_success?: boolean;
  1812. auto_off_after?: boolean;
  1813. manual_start?: boolean; // Requires manual trigger to start (staged)
  1814. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  1815. // scheduler doesn't immediately re-flag this item (#1698-followup).
  1816. skip_filament_check?: boolean;
  1817. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  1818. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1819. // Print options
  1820. bed_levelling?: boolean;
  1821. flow_cali?: boolean;
  1822. vibration_cali?: boolean;
  1823. layer_inspect?: boolean;
  1824. timelapse?: boolean;
  1825. use_ams?: boolean;
  1826. nozzle_offset_cali?: boolean;
  1827. // Auto-print G-code injection
  1828. gcode_injection?: boolean;
  1829. // Batch: create multiple copies (creates a batch if > 1)
  1830. quantity?: number;
  1831. // Project to associate the resulting archive with
  1832. project_id?: number;
  1833. }
  1834. export interface PrintQueueItemUpdate {
  1835. printer_id?: number | null; // null = unassign
  1836. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  1837. target_location?: string | null; // Target location filter (only used with target_model)
  1838. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; force_color_match?: boolean }> | null;
  1839. position?: number;
  1840. scheduled_time?: string | null;
  1841. require_previous_success?: boolean;
  1842. auto_off_after?: boolean;
  1843. manual_start?: boolean;
  1844. ams_mapping?: number[];
  1845. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  1846. // Print options
  1847. bed_levelling?: boolean;
  1848. flow_cali?: boolean;
  1849. vibration_cali?: boolean;
  1850. layer_inspect?: boolean;
  1851. timelapse?: boolean;
  1852. use_ams?: boolean;
  1853. nozzle_offset_cali?: boolean;
  1854. // Auto-print G-code injection
  1855. gcode_injection?: boolean;
  1856. }
  1857. export interface PrintQueueBulkUpdate {
  1858. item_ids: number[];
  1859. printer_id?: number | null;
  1860. scheduled_time?: string | null;
  1861. require_previous_success?: boolean;
  1862. auto_off_after?: boolean;
  1863. manual_start?: boolean;
  1864. // Print options
  1865. bed_levelling?: boolean;
  1866. flow_cali?: boolean;
  1867. vibration_cali?: boolean;
  1868. layer_inspect?: boolean;
  1869. timelapse?: boolean;
  1870. use_ams?: boolean;
  1871. nozzle_offset_cali?: boolean;
  1872. // Auto-print G-code injection
  1873. gcode_injection?: boolean;
  1874. }
  1875. export interface PrintQueueBulkUpdateResponse {
  1876. updated_count: number;
  1877. skipped_count: number;
  1878. message: string;
  1879. }
  1880. // MQTT Logging types
  1881. export interface MQTTLogEntry {
  1882. timestamp: string;
  1883. topic: string;
  1884. direction: 'in' | 'out';
  1885. payload: Record<string, unknown>;
  1886. }
  1887. export interface MQTTLogsResponse {
  1888. logging_enabled: boolean;
  1889. logs: MQTTLogEntry[];
  1890. }
  1891. // K-Profile types
  1892. export interface KProfile {
  1893. slot_id: number;
  1894. extruder_id: number;
  1895. nozzle_id: string;
  1896. nozzle_diameter: string;
  1897. filament_id: string;
  1898. name: string;
  1899. k_value: string;
  1900. n_coef: string;
  1901. ams_id: number;
  1902. tray_id: number;
  1903. setting_id: string | null;
  1904. }
  1905. export interface KProfileCreate {
  1906. slot_id?: number; // Storage slot, 0 for new profiles
  1907. extruder_id?: number;
  1908. nozzle_id: string;
  1909. nozzle_diameter: string;
  1910. filament_id: string;
  1911. name: string;
  1912. k_value: string;
  1913. n_coef?: string;
  1914. ams_id?: number;
  1915. tray_id?: number;
  1916. setting_id?: string | null;
  1917. }
  1918. export interface KProfileDelete {
  1919. slot_id: number; // cali_idx - calibration index to delete
  1920. extruder_id: number;
  1921. nozzle_id: string; // e.g., "HH00-0.4"
  1922. nozzle_diameter: string; // e.g., "0.4"
  1923. filament_id: string; // Bambu filament identifier
  1924. setting_id?: string | null; // Setting ID (for X1C series)
  1925. }
  1926. export interface KProfilesResponse {
  1927. profiles: KProfile[];
  1928. nozzle_diameter: string;
  1929. }
  1930. export interface KProfileNote {
  1931. setting_id: string;
  1932. note: string;
  1933. }
  1934. export interface KProfileNotesResponse {
  1935. notes: Record<string, string>; // setting_id -> note
  1936. }
  1937. // Slot Preset Mapping
  1938. export interface SlotPresetMapping {
  1939. ams_id: number;
  1940. tray_id: number;
  1941. preset_id: string;
  1942. preset_name: string;
  1943. }
  1944. // Filament types
  1945. export interface Filament {
  1946. id: number;
  1947. name: string;
  1948. type: string; // PLA, PETG, ABS, etc.
  1949. brand: string | null;
  1950. color: string | null;
  1951. color_hex: string | null;
  1952. cost_per_kg: number;
  1953. spool_weight_g: number;
  1954. currency: string;
  1955. density: number | null;
  1956. print_temp_min: number | null;
  1957. print_temp_max: number | null;
  1958. bed_temp_min: number | null;
  1959. bed_temp_max: number | null;
  1960. created_at: string;
  1961. updated_at: string;
  1962. }
  1963. // Notification Provider types
  1964. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant';
  1965. export interface NotificationProvider {
  1966. id: number;
  1967. name: string;
  1968. provider_type: ProviderType;
  1969. enabled: boolean;
  1970. config: Record<string, unknown>;
  1971. // Print lifecycle events
  1972. on_print_start: boolean;
  1973. on_print_complete: boolean;
  1974. on_print_failed: boolean;
  1975. on_print_stopped: boolean;
  1976. on_print_progress: boolean;
  1977. on_print_missing_spool_assignment: boolean;
  1978. // Printer status events
  1979. on_printer_offline: boolean;
  1980. on_printer_error: boolean;
  1981. on_filament_low: boolean;
  1982. on_maintenance_due: boolean;
  1983. // AMS environmental alarms (regular AMS)
  1984. on_ams_humidity_high: boolean;
  1985. on_ams_temperature_high: boolean;
  1986. // AMS-HT environmental alarms
  1987. on_ams_ht_humidity_high: boolean;
  1988. on_ams_ht_temperature_high: boolean;
  1989. // Build plate detection
  1990. on_plate_not_empty: boolean;
  1991. // Bed cooled
  1992. on_bed_cooled: boolean;
  1993. // First layer complete
  1994. on_first_layer_complete: boolean;
  1995. // Inventory stock alerts
  1996. on_stock_reorder_alert: boolean;
  1997. on_stock_break_alert: boolean;
  1998. // Print queue events
  1999. on_queue_job_added: boolean;
  2000. on_queue_job_assigned: boolean;
  2001. on_queue_job_started: boolean;
  2002. on_queue_job_waiting: boolean;
  2003. on_queue_job_skipped: boolean;
  2004. on_queue_job_failed: boolean;
  2005. on_queue_completed: boolean;
  2006. // Quiet hours
  2007. quiet_hours_enabled: boolean;
  2008. quiet_hours_start: string | null;
  2009. quiet_hours_end: string | null;
  2010. // Daily digest
  2011. daily_digest_enabled: boolean;
  2012. daily_digest_time: string | null;
  2013. // Printer filter
  2014. printer_id: number | null;
  2015. // Status tracking
  2016. last_success: string | null;
  2017. last_error: string | null;
  2018. last_error_at: string | null;
  2019. // Timestamps
  2020. created_at: string;
  2021. updated_at: string;
  2022. }
  2023. export interface NotificationProviderCreate {
  2024. name: string;
  2025. provider_type: ProviderType;
  2026. enabled?: boolean;
  2027. config: Record<string, unknown>;
  2028. // Print lifecycle events
  2029. on_print_start?: boolean;
  2030. on_print_complete?: boolean;
  2031. on_print_failed?: boolean;
  2032. on_print_stopped?: boolean;
  2033. on_print_progress?: boolean;
  2034. on_print_missing_spool_assignment?: boolean;
  2035. // Printer status events
  2036. on_printer_offline?: boolean;
  2037. on_printer_error?: boolean;
  2038. on_filament_low?: boolean;
  2039. on_maintenance_due?: boolean;
  2040. // AMS environmental alarms (regular AMS)
  2041. on_ams_humidity_high?: boolean;
  2042. on_ams_temperature_high?: boolean;
  2043. // AMS-HT environmental alarms
  2044. on_ams_ht_humidity_high?: boolean;
  2045. on_ams_ht_temperature_high?: boolean;
  2046. // Build plate detection
  2047. on_plate_not_empty?: boolean;
  2048. // Bed cooled
  2049. on_bed_cooled?: boolean;
  2050. // First layer complete
  2051. on_first_layer_complete?: boolean;
  2052. // Inventory stock alerts
  2053. on_stock_reorder_alert?: boolean;
  2054. on_stock_break_alert?: boolean;
  2055. // Print queue events
  2056. on_queue_job_added?: boolean;
  2057. on_queue_job_assigned?: boolean;
  2058. on_queue_job_started?: boolean;
  2059. on_queue_job_waiting?: boolean;
  2060. on_queue_job_skipped?: boolean;
  2061. on_queue_job_failed?: boolean;
  2062. on_queue_completed?: boolean;
  2063. // Quiet hours
  2064. quiet_hours_enabled?: boolean;
  2065. quiet_hours_start?: string | null;
  2066. quiet_hours_end?: string | null;
  2067. // Daily digest
  2068. daily_digest_enabled?: boolean;
  2069. daily_digest_time?: string | null;
  2070. // Printer filter
  2071. printer_id?: number | null;
  2072. }
  2073. export interface NotificationProviderUpdate {
  2074. name?: string;
  2075. provider_type?: ProviderType;
  2076. enabled?: boolean;
  2077. config?: Record<string, unknown>;
  2078. // Print lifecycle events
  2079. on_print_start?: boolean;
  2080. on_print_complete?: boolean;
  2081. on_print_failed?: boolean;
  2082. on_print_stopped?: boolean;
  2083. on_print_progress?: boolean;
  2084. on_print_missing_spool_assignment?: boolean;
  2085. // Printer status events
  2086. on_printer_offline?: boolean;
  2087. on_printer_error?: boolean;
  2088. on_filament_low?: boolean;
  2089. on_maintenance_due?: boolean;
  2090. // AMS environmental alarms (regular AMS)
  2091. on_ams_humidity_high?: boolean;
  2092. on_ams_temperature_high?: boolean;
  2093. // AMS-HT environmental alarms
  2094. on_ams_ht_humidity_high?: boolean;
  2095. on_ams_ht_temperature_high?: boolean;
  2096. // Build plate detection
  2097. on_plate_not_empty?: boolean;
  2098. // Bed cooled
  2099. on_bed_cooled?: boolean;
  2100. // First layer complete
  2101. on_first_layer_complete?: boolean;
  2102. // Inventory stock alerts
  2103. on_stock_reorder_alert?: boolean;
  2104. on_stock_break_alert?: boolean;
  2105. // Print queue events
  2106. on_queue_job_added?: boolean;
  2107. on_queue_job_assigned?: boolean;
  2108. on_queue_job_started?: boolean;
  2109. on_queue_job_waiting?: boolean;
  2110. on_queue_job_skipped?: boolean;
  2111. on_queue_job_failed?: boolean;
  2112. on_queue_completed?: boolean;
  2113. // Quiet hours
  2114. quiet_hours_enabled?: boolean;
  2115. quiet_hours_start?: string | null;
  2116. quiet_hours_end?: string | null;
  2117. // Daily digest
  2118. daily_digest_enabled?: boolean;
  2119. daily_digest_time?: string | null;
  2120. // Printer filter
  2121. printer_id?: number | null;
  2122. }
  2123. // GitHub Backup types
  2124. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  2125. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  2126. export interface GitHubBackupConfig {
  2127. id: number;
  2128. repository_url: string;
  2129. has_token: boolean;
  2130. branch: string;
  2131. provider: GitProviderType;
  2132. allow_insecure_http: boolean;
  2133. schedule_enabled: boolean;
  2134. schedule_type: ScheduleType;
  2135. backup_kprofiles: boolean;
  2136. backup_cloud_profiles: boolean;
  2137. backup_settings: boolean;
  2138. backup_spools: boolean;
  2139. backup_archives: boolean;
  2140. enabled: boolean;
  2141. last_backup_at: string | null;
  2142. last_backup_status: string | null;
  2143. last_backup_message: string | null;
  2144. last_backup_commit_sha: string | null;
  2145. next_scheduled_run: string | null;
  2146. created_at: string;
  2147. updated_at: string;
  2148. }
  2149. export interface GitHubBackupConfigCreate {
  2150. repository_url: string;
  2151. access_token: string;
  2152. branch?: string;
  2153. provider?: GitProviderType;
  2154. allow_insecure_http?: boolean;
  2155. schedule_enabled?: boolean;
  2156. schedule_type?: ScheduleType;
  2157. backup_kprofiles?: boolean;
  2158. backup_cloud_profiles?: boolean;
  2159. backup_settings?: boolean;
  2160. backup_spools?: boolean;
  2161. backup_archives?: boolean;
  2162. enabled?: boolean;
  2163. }
  2164. export interface GitHubBackupLog {
  2165. id: number;
  2166. config_id: number;
  2167. started_at: string;
  2168. completed_at: string | null;
  2169. status: string;
  2170. trigger: string;
  2171. commit_sha: string | null;
  2172. files_changed: number;
  2173. error_message: string | null;
  2174. }
  2175. export interface GitHubBackupStatus {
  2176. configured: boolean;
  2177. enabled: boolean;
  2178. is_running: boolean;
  2179. progress: string | null;
  2180. last_backup_at: string | null;
  2181. last_backup_status: string | null;
  2182. next_scheduled_run: string | null;
  2183. }
  2184. export interface LocalBackupStatus {
  2185. enabled: boolean;
  2186. schedule: string;
  2187. time: string;
  2188. retention: number;
  2189. path: string;
  2190. default_path: string;
  2191. is_running: boolean;
  2192. last_backup_at: string | null;
  2193. last_status: string | null;
  2194. last_message: string | null;
  2195. next_run: string | null;
  2196. timezone: string;
  2197. }
  2198. export interface LocalBackupFile {
  2199. filename: string;
  2200. size: number;
  2201. created_at: string;
  2202. }
  2203. export interface ObicoDetectionEvent {
  2204. printer_id: number;
  2205. task_name: string;
  2206. timestamp: string;
  2207. current_p: number;
  2208. score: number;
  2209. class: 'safe' | 'warning' | 'failure';
  2210. detections: number;
  2211. }
  2212. export interface ObicoStatus {
  2213. is_running: boolean;
  2214. last_error: string | null;
  2215. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  2216. thresholds: { low: number; high: number };
  2217. history: ObicoDetectionEvent[];
  2218. enabled: boolean;
  2219. ml_url: string;
  2220. sensitivity: 'low' | 'medium' | 'high';
  2221. action: 'notify' | 'pause' | 'pause_and_off';
  2222. poll_interval: number;
  2223. external_url_configured: boolean;
  2224. }
  2225. export interface ObicoTestConnection {
  2226. ok: boolean;
  2227. status_code: number | null;
  2228. body: string | null;
  2229. error: string | null;
  2230. }
  2231. export interface GitHubTestConnectionResponse {
  2232. success: boolean;
  2233. message: string;
  2234. repo_name: string | null;
  2235. permissions: Record<string, boolean> | null;
  2236. // true = confirmed private, false = confirmed public/internal,
  2237. // null = could not determine. Backend rejects save unless true.
  2238. is_private: boolean | null;
  2239. }
  2240. export interface GitHubBackupTriggerResponse {
  2241. success: boolean;
  2242. message: string;
  2243. log_id: number | null;
  2244. commit_sha: string | null;
  2245. files_changed: number;
  2246. }
  2247. export interface NotificationTestRequest {
  2248. provider_type: ProviderType;
  2249. config: Record<string, unknown>;
  2250. }
  2251. export interface NotificationTestResponse {
  2252. success: boolean;
  2253. message: string;
  2254. }
  2255. export interface BackgroundDispatchResponse {
  2256. status: 'dispatched' | string;
  2257. printer_id: number;
  2258. archive_id?: number | null;
  2259. filename: string;
  2260. dispatch_job_id: number;
  2261. dispatch_position: number;
  2262. }
  2263. // Provider-specific config types for reference
  2264. export interface CallMeBotConfig {
  2265. phone: string;
  2266. apikey: string;
  2267. }
  2268. export interface NtfyConfig {
  2269. server?: string;
  2270. topic: string;
  2271. auth_token?: string | null;
  2272. }
  2273. export interface PushoverConfig {
  2274. user_key: string;
  2275. app_token: string;
  2276. priority?: number;
  2277. }
  2278. export interface TelegramConfig {
  2279. bot_token: string;
  2280. chat_id: string;
  2281. }
  2282. export interface EmailConfig {
  2283. smtp_server: string;
  2284. smtp_port?: number;
  2285. username: string;
  2286. password: string;
  2287. from_email: string;
  2288. to_email: string;
  2289. use_tls?: boolean;
  2290. }
  2291. // Notification Template types
  2292. export interface NotificationTemplate {
  2293. id: number;
  2294. event_type: string;
  2295. name: string;
  2296. title_template: string;
  2297. body_template: string;
  2298. is_default: boolean;
  2299. created_at: string;
  2300. updated_at: string;
  2301. }
  2302. export interface NotificationTemplateUpdate {
  2303. title_template?: string;
  2304. body_template?: string;
  2305. }
  2306. export interface EventVariablesResponse {
  2307. event_type: string;
  2308. event_name: string;
  2309. variables: string[];
  2310. }
  2311. export interface TemplatePreviewRequest {
  2312. event_type: string;
  2313. title_template: string;
  2314. body_template: string;
  2315. }
  2316. export interface TemplatePreviewResponse {
  2317. title: string;
  2318. body: string;
  2319. }
  2320. // Notification Log types
  2321. export interface NotificationLogEntry {
  2322. id: number;
  2323. provider_id: number;
  2324. provider_name: string | null;
  2325. provider_type: string | null;
  2326. event_type: string;
  2327. title: string;
  2328. message: string;
  2329. success: boolean;
  2330. error_message: string | null;
  2331. printer_id: number | null;
  2332. printer_name: string | null;
  2333. created_at: string;
  2334. }
  2335. export interface NotificationLogStats {
  2336. total: number;
  2337. success_count: number;
  2338. failure_count: number;
  2339. by_event_type: Record<string, number>;
  2340. by_provider: Record<string, number>;
  2341. }
  2342. // Spoolman types
  2343. export interface SpoolmanStatus {
  2344. enabled: boolean;
  2345. connected: boolean;
  2346. url: string | null;
  2347. }
  2348. export interface SkippedSpool {
  2349. location: string;
  2350. reason: string;
  2351. filament_type: string | null;
  2352. color: string | null;
  2353. }
  2354. export interface SpoolmanSyncResult {
  2355. success: boolean;
  2356. synced_count: number;
  2357. skipped_count: number;
  2358. skipped: SkippedSpool[];
  2359. errors: string[];
  2360. }
  2361. export interface UnlinkedSpool {
  2362. id: number;
  2363. filament_name: string | null;
  2364. filament_vendor: string | null;
  2365. filament_material: string | null;
  2366. filament_color_hex: string | null;
  2367. remaining_weight: number | null;
  2368. location: string | null;
  2369. }
  2370. export interface LinkedSpoolInfo {
  2371. id: number;
  2372. remaining_weight: number | null;
  2373. filament_weight: number | null;
  2374. }
  2375. export interface LinkedSpoolsMap {
  2376. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  2377. }
  2378. export interface SpoolmanVendor {
  2379. id: number;
  2380. name: string;
  2381. }
  2382. export interface SpoolmanFilamentEntry {
  2383. id: number;
  2384. name: string;
  2385. material: string | null;
  2386. color_hex: string | null;
  2387. color_name: string | null;
  2388. weight: number | null;
  2389. spool_weight: number | null;
  2390. vendor: SpoolmanVendor | null;
  2391. }
  2392. // Inventory types
  2393. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  2394. export type SpoolLabelTemplate =
  2395. | 'ams_holder_74x33'
  2396. | 'ams_holder_75x55'
  2397. | 'box_40x30'
  2398. | 'box_62x29'
  2399. | 'avery_5160'
  2400. | 'avery_l7160';
  2401. export interface InventorySpool {
  2402. id: number;
  2403. material: string;
  2404. subtype: string | null;
  2405. color_name: string | null;
  2406. // True when color_name was synthesised from subtype because Spoolman has no
  2407. // stored value (Spoolman-backed inventory only). The edit form uses this to
  2408. // leave the input blank, so the user doesn't round-trip the synth value
  2409. // back to Spoolman as if it were a real user-set color_name (#1319).
  2410. color_name_is_synthesized?: boolean;
  2411. rgba: string | null;
  2412. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  2413. extra_colors: string | null;
  2414. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  2415. effect_type: string | null;
  2416. brand: string | null;
  2417. label_weight: number;
  2418. core_weight: number;
  2419. core_weight_catalog_id: number | null;
  2420. weight_used: number;
  2421. // Anchor for the resettable "Total Consumed" display (#1390). The
  2422. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  2423. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  2424. // zeroes the counter without disturbing remaining. Optional for back-compat
  2425. // with rows from a pre-migration DB snapshot — default to 0.
  2426. weight_used_baseline?: number;
  2427. slicer_filament: string | null;
  2428. slicer_filament_name: string | null;
  2429. nozzle_temp_min: number | null;
  2430. nozzle_temp_max: number | null;
  2431. note: string | null;
  2432. added_full: boolean | null;
  2433. last_used: string | null;
  2434. encode_time: string | null;
  2435. tag_uid: string | null;
  2436. tray_uuid: string | null;
  2437. data_origin: string | null;
  2438. tag_type: string | null;
  2439. archived_at: string | null;
  2440. created_at: string;
  2441. updated_at: string;
  2442. cost_per_kg: number | null;
  2443. last_scale_weight: number | null;
  2444. last_weighed_at: string | null;
  2445. // User-defined category + per-spool low-stock threshold override (#729).
  2446. category: string | null;
  2447. low_stock_threshold_pct: number | null;
  2448. k_profiles?: SpoolKProfile[];
  2449. storage_location?: string | null;
  2450. }
  2451. export interface SpoolmanBulkCreateResult {
  2452. created: InventorySpool[];
  2453. requested_count: number;
  2454. failed_count: number;
  2455. }
  2456. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  2457. /** One row's outcome from the import preview / real import. */
  2458. export interface CsvImportRow {
  2459. row_number: number;
  2460. status: 'valid' | 'error' | 'skipped';
  2461. reason: string | null;
  2462. material: string | null;
  2463. brand: string | null;
  2464. color_name: string | null;
  2465. rgba: string | null;
  2466. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  2467. resolved_color: boolean;
  2468. /** The catalog match came from a different material's variant (no exact
  2469. * material match). Shown as a warning in the preview. */
  2470. cross_material_color: boolean;
  2471. /** An active spool with the same material+brand+color already exists.
  2472. * Informational only — the import still creates the row. */
  2473. duplicate_of_existing: boolean;
  2474. }
  2475. /** Dry-run preview: per-row classification, no rows written. */
  2476. export interface CsvImportPreview {
  2477. columns: string[];
  2478. total: number;
  2479. valid_count: number;
  2480. error_count: number;
  2481. skipped_count: number;
  2482. rows: CsvImportRow[];
  2483. warnings: string[];
  2484. }
  2485. /** Summary returned after a real (non-dry-run) import. */
  2486. export interface CsvImportResult {
  2487. created: number;
  2488. skipped: number;
  2489. errors: number;
  2490. error_rows: CsvImportRow[];
  2491. }
  2492. export interface SpoolUsageRecord {
  2493. id: number;
  2494. spool_id: number;
  2495. printer_id: number | null;
  2496. print_name: string | null;
  2497. weight_used: number;
  2498. percent_used: number;
  2499. status: string;
  2500. cost: number | null;
  2501. created_at: string;
  2502. }
  2503. export interface SpoolKProfile {
  2504. id: number;
  2505. spool_id: number;
  2506. printer_id: number;
  2507. extruder: number;
  2508. nozzle_diameter: string;
  2509. nozzle_type: string | null;
  2510. k_value: number;
  2511. name: string | null;
  2512. cali_idx: number | null;
  2513. setting_id: string | null;
  2514. created_at: string;
  2515. }
  2516. export interface SpoolKProfileInput {
  2517. printer_id: number;
  2518. extruder?: number;
  2519. nozzle_diameter?: string;
  2520. nozzle_type?: string | null;
  2521. k_value: number;
  2522. name?: string | null;
  2523. cali_idx?: number | null;
  2524. setting_id?: string | null;
  2525. }
  2526. export interface SpoolAssignment {
  2527. id: number;
  2528. spool_id: number;
  2529. printer_id: number;
  2530. printer_name: string | null;
  2531. ams_id: number;
  2532. tray_id: number;
  2533. fingerprint_color: string | null;
  2534. fingerprint_type: string | null;
  2535. spool?: InventorySpool | null;
  2536. configured: boolean;
  2537. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  2538. created_at: string;
  2539. ams_label?: string | null; // User-defined friendly name for the AMS unit
  2540. }
  2541. export interface FilamentSkuSettings {
  2542. id: number;
  2543. material: string;
  2544. subtype: string | null;
  2545. brand: string | null;
  2546. lead_time_days: number;
  2547. safety_margin_value: number;
  2548. safety_margin_unit: 'days' | 'g';
  2549. alerts_snoozed: boolean;
  2550. }
  2551. export interface ShoppingListItem {
  2552. id: number;
  2553. material: string;
  2554. subtype: string | null;
  2555. brand: string | null;
  2556. quantity_spools: number;
  2557. note: string | null;
  2558. status: 'pending' | 'purchased' | 'received';
  2559. purchased_at: string | null;
  2560. added_at: string;
  2561. }
  2562. export interface ShoppingListItemCreate {
  2563. material: string;
  2564. subtype: string | null;
  2565. brand: string | null;
  2566. quantity_spools: number;
  2567. note?: string | null;
  2568. }
  2569. // Update types
  2570. export interface VersionInfo {
  2571. version: string;
  2572. repo: string;
  2573. }
  2574. export interface UpdateCheckResult {
  2575. update_available: boolean;
  2576. current_version: string;
  2577. latest_version: string | null;
  2578. release_name?: string;
  2579. release_notes?: string;
  2580. release_url?: string;
  2581. published_at?: string;
  2582. error?: string;
  2583. message?: string;
  2584. is_docker?: boolean;
  2585. is_ha_addon?: boolean;
  2586. update_method?: 'docker' | 'git' | 'ha_addon';
  2587. }
  2588. export interface UpdateStatus {
  2589. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  2590. progress: number;
  2591. message: string;
  2592. error: string | null;
  2593. }
  2594. // Maintenance types
  2595. export interface MaintenanceType {
  2596. id: number;
  2597. name: string;
  2598. description: string | null;
  2599. default_interval_hours: number;
  2600. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  2601. icon: string | null;
  2602. wiki_url: string | null; // Documentation link
  2603. is_system: boolean;
  2604. created_at: string;
  2605. }
  2606. export interface MaintenanceTypeCreate {
  2607. name: string;
  2608. description?: string | null;
  2609. default_interval_hours?: number;
  2610. interval_type?: 'hours' | 'days';
  2611. icon?: string | null;
  2612. wiki_url?: string | null;
  2613. }
  2614. export interface MaintenanceStatus {
  2615. id: number;
  2616. printer_id: number;
  2617. printer_name: string;
  2618. printer_model: string | null;
  2619. maintenance_type_id: number;
  2620. maintenance_type_name: string;
  2621. maintenance_type_icon: string | null;
  2622. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  2623. enabled: boolean;
  2624. interval_hours: number; // For hours type: print hours; for days type: number of days
  2625. interval_type: 'hours' | 'days';
  2626. current_hours: number;
  2627. hours_since_maintenance: number;
  2628. hours_until_due: number;
  2629. days_since_maintenance: number | null; // For days type
  2630. days_until_due: number | null; // For days type
  2631. is_due: boolean;
  2632. is_warning: boolean;
  2633. last_performed_at: string | null;
  2634. }
  2635. export interface PrinterMaintenanceOverview {
  2636. printer_id: number;
  2637. printer_name: string;
  2638. printer_model: string | null;
  2639. total_print_hours: number;
  2640. maintenance_items: MaintenanceStatus[];
  2641. due_count: number;
  2642. warning_count: number;
  2643. }
  2644. export interface MaintenanceHistory {
  2645. id: number;
  2646. printer_maintenance_id: number;
  2647. performed_at: string;
  2648. hours_at_maintenance: number;
  2649. notes: string | null;
  2650. }
  2651. export interface MaintenanceSummary {
  2652. total_due: number;
  2653. total_warning: number;
  2654. printers_with_issues: Array<{
  2655. printer_id: number;
  2656. printer_name: string;
  2657. due_count: number;
  2658. warning_count: number;
  2659. }>;
  2660. }
  2661. // External Links (sidebar)
  2662. export interface ExternalLink {
  2663. id: number;
  2664. name: string;
  2665. url: string;
  2666. icon: string;
  2667. open_in_new_tab: boolean;
  2668. custom_icon: string | null;
  2669. sort_order: number;
  2670. created_at: string;
  2671. updated_at: string;
  2672. }
  2673. export interface ExternalLinkCreate {
  2674. name: string;
  2675. url: string;
  2676. icon: string;
  2677. open_in_new_tab?: boolean;
  2678. }
  2679. export interface ExternalLinkUpdate {
  2680. name?: string;
  2681. url?: string;
  2682. icon?: string;
  2683. open_in_new_tab?: boolean;
  2684. }
  2685. // Permission type - all available permissions
  2686. export type Permission =
  2687. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  2688. | 'archives:read' | 'archives:create'
  2689. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  2690. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  2691. | 'queue:read' | 'queue:create'
  2692. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  2693. | 'queue:reorder'
  2694. | 'library:read' | 'library:upload'
  2695. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  2696. | 'library:purge'
  2697. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  2698. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  2699. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  2700. | 'inventory:forecast_read' | 'inventory:forecast_write'
  2701. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  2702. | 'camera:view'
  2703. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  2704. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  2705. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  2706. | 'notification_templates:read' | 'notification_templates:update'
  2707. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  2708. | 'discovery:scan'
  2709. | 'firmware:read' | 'firmware:update'
  2710. | 'ams_history:read'
  2711. | 'stats:read' | 'stats:filter_by_user'
  2712. | 'system:read'
  2713. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  2714. | 'github:backup' | 'github:restore'
  2715. | 'cloud:auth' | 'orca_cloud:auth'
  2716. | 'makerworld:view' | 'makerworld:import'
  2717. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  2718. | 'users:read' | 'users:create' | 'users:update' | 'users:delete'
  2719. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  2720. | 'websocket:connect';
  2721. // Group types
  2722. export interface GroupBrief {
  2723. id: number;
  2724. name: string;
  2725. }
  2726. export interface Group {
  2727. id: number;
  2728. name: string;
  2729. description: string | null;
  2730. permissions: Permission[];
  2731. is_system: boolean;
  2732. user_count: number;
  2733. created_at: string;
  2734. updated_at: string;
  2735. }
  2736. export interface GroupDetail extends Group {
  2737. users: Array<{ id: number; username: string; is_active: boolean }>;
  2738. }
  2739. export interface GroupCreate {
  2740. name: string;
  2741. description?: string;
  2742. permissions: Permission[];
  2743. }
  2744. export interface GroupUpdate {
  2745. name?: string;
  2746. description?: string;
  2747. permissions?: Permission[];
  2748. }
  2749. export interface PermissionInfo {
  2750. value: Permission;
  2751. label: string;
  2752. }
  2753. export interface PermissionCategory {
  2754. name: string;
  2755. permissions: PermissionInfo[];
  2756. }
  2757. export interface PermissionsListResponse {
  2758. categories: PermissionCategory[];
  2759. all_permissions: Permission[];
  2760. }
  2761. // User email notification preferences
  2762. export interface UserEmailPreferences {
  2763. notify_print_start: boolean;
  2764. notify_print_complete: boolean;
  2765. notify_print_failed: boolean;
  2766. notify_print_stopped: boolean;
  2767. }
  2768. // Auth types
  2769. export interface LoginRequest {
  2770. username: string;
  2771. password: string;
  2772. }
  2773. export interface LoginResponse {
  2774. access_token?: string;
  2775. token_type?: string;
  2776. user?: UserResponse;
  2777. /** Set when 2FA verification is required before a full token is issued. */
  2778. requires_2fa?: boolean;
  2779. pre_auth_token?: string;
  2780. two_fa_methods?: string[];
  2781. }
  2782. export interface UserResponse {
  2783. id: number;
  2784. username: string;
  2785. email?: string;
  2786. role: string; // Deprecated, kept for backward compatibility
  2787. is_active: boolean;
  2788. is_admin: boolean; // Computed from role and group membership
  2789. auth_source: string; // "local" or "ldap"
  2790. groups: GroupBrief[];
  2791. permissions: Permission[]; // All permissions from groups
  2792. created_at: string;
  2793. }
  2794. export interface UserCreate {
  2795. username: string;
  2796. password?: string; // Optional when advanced auth is enabled
  2797. email?: string;
  2798. role: string;
  2799. group_ids?: number[];
  2800. }
  2801. export interface UserUpdate {
  2802. username?: string;
  2803. password?: string;
  2804. email?: string;
  2805. role?: string;
  2806. is_active?: boolean;
  2807. group_ids?: number[];
  2808. }
  2809. export interface SetupRequest {
  2810. auth_enabled: boolean;
  2811. admin_username?: string;
  2812. admin_password?: string;
  2813. }
  2814. export interface ForgotPasswordRequest {
  2815. email: string;
  2816. }
  2817. export interface ForgotPasswordResponse {
  2818. message: string;
  2819. }
  2820. export interface ResetPasswordRequest {
  2821. user_id: number;
  2822. }
  2823. export interface ResetPasswordResponse {
  2824. message: string;
  2825. }
  2826. export interface SMTPSettings {
  2827. smtp_host: string;
  2828. smtp_port: number;
  2829. smtp_username?: string;
  2830. smtp_password?: string;
  2831. smtp_security: 'starttls' | 'ssl' | 'none';
  2832. smtp_auth_enabled: boolean;
  2833. smtp_from_email: string;
  2834. smtp_from_name: string;
  2835. }
  2836. // 2FA / MFA interfaces
  2837. export interface TwoFAStatus {
  2838. totp_enabled: boolean;
  2839. email_otp_enabled: boolean;
  2840. backup_codes_remaining: number;
  2841. }
  2842. export interface TOTPSetupResponse {
  2843. secret: string;
  2844. qr_code_b64: string;
  2845. issuer: string;
  2846. }
  2847. export interface TOTPEnableResponse {
  2848. message: string;
  2849. backup_codes: string[];
  2850. }
  2851. export interface BackupCodesResponse {
  2852. backup_codes: string[];
  2853. message: string;
  2854. }
  2855. export interface TwoFAVerifyRequest {
  2856. pre_auth_token: string;
  2857. code: string;
  2858. method: 'totp' | 'email' | 'backup';
  2859. }
  2860. /**
  2861. * A URL that is known to be same-origin (a relative path starting with ``/``).
  2862. *
  2863. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  2864. * can be distinguished from arbitrary strings at the type level. The brand
  2865. * is compile-time only; at runtime these are plain strings.
  2866. *
  2867. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  2868. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  2869. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  2870. * that no external URL slips through.
  2871. */
  2872. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  2873. // OIDC interfaces
  2874. export interface OIDCProvider {
  2875. id: number;
  2876. name: string;
  2877. issuer_url: string;
  2878. client_id: string;
  2879. scopes: string;
  2880. is_enabled: boolean;
  2881. auto_create_users: boolean;
  2882. auto_link_existing_accounts: boolean;
  2883. email_claim: string;
  2884. require_email_verified: boolean;
  2885. icon_url?: string | null;
  2886. default_group_id?: number | null;
  2887. // True when the backend has cached icon bytes for this provider.
  2888. // Login page / admin preview consume this via the proxy URL
  2889. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  2890. // hotlinks the external icon URL — that would require loosening
  2891. // the strict img-src CSP. Required, not optional: the backend always
  2892. // includes this field in the response (Pydantic default-False is
  2893. // populated unconditionally in the route handler).
  2894. has_icon: boolean;
  2895. }
  2896. export interface OIDCProviderCreate {
  2897. name: string;
  2898. issuer_url: string;
  2899. client_id: string;
  2900. client_secret: string;
  2901. scopes?: string;
  2902. is_enabled?: boolean;
  2903. auto_create_users?: boolean;
  2904. auto_link_existing_accounts?: boolean;
  2905. email_claim?: string;
  2906. require_email_verified?: boolean;
  2907. icon_url?: string | null;
  2908. default_group_id?: number | null;
  2909. }
  2910. export interface OIDCLink {
  2911. id: number;
  2912. provider_id: number;
  2913. provider_name: string;
  2914. provider_email?: string | null;
  2915. created_at: string;
  2916. }
  2917. export interface TestSMTPRequest {
  2918. test_recipient: string;
  2919. }
  2920. export interface TestSMTPResponse {
  2921. success: boolean;
  2922. message: string;
  2923. }
  2924. export interface AdvancedAuthStatus {
  2925. advanced_auth_enabled: boolean;
  2926. smtp_configured: boolean;
  2927. }
  2928. export interface LDAPStatus {
  2929. ldap_enabled: boolean;
  2930. ldap_configured: boolean;
  2931. }
  2932. export interface EncryptionRowCounts {
  2933. oidc_providers: number;
  2934. user_totp: number;
  2935. }
  2936. export interface EncryptionStatus {
  2937. key_configured: boolean;
  2938. key_source: 'env' | 'file' | 'generated' | 'none';
  2939. legacy_plaintext_rows: EncryptionRowCounts;
  2940. encrypted_rows: EncryptionRowCounts;
  2941. decryption_broken: boolean;
  2942. // B2: count of rows skipped during the last legacy re-encryption migration.
  2943. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  2944. migration_error_count: number;
  2945. }
  2946. export interface LDAPTestResponse {
  2947. success: boolean;
  2948. message: string;
  2949. }
  2950. export interface LDAPSearchResult {
  2951. username: string;
  2952. email: string | null;
  2953. display_name: string | null;
  2954. dn: string;
  2955. already_provisioned: boolean;
  2956. }
  2957. export interface SetupResponse {
  2958. auth_enabled: boolean;
  2959. admin_created?: boolean;
  2960. }
  2961. export interface AuthStatus {
  2962. auth_enabled: boolean;
  2963. requires_setup: boolean;
  2964. }
  2965. // API functions
  2966. export const api = {
  2967. // Authentication
  2968. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  2969. setupAuth: (data: SetupRequest) =>
  2970. request<SetupResponse>('/auth/setup', {
  2971. method: 'POST',
  2972. body: JSON.stringify(data),
  2973. }),
  2974. login: (data: LoginRequest) =>
  2975. request<LoginResponse>('/auth/login', {
  2976. method: 'POST',
  2977. body: JSON.stringify(data),
  2978. }),
  2979. logout: () =>
  2980. request<{ message: string }>('/auth/logout', {
  2981. method: 'POST',
  2982. }),
  2983. getCurrentUser: () => request<UserResponse>('/auth/me'),
  2984. disableAuth: () =>
  2985. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  2986. method: 'POST',
  2987. }),
  2988. // Advanced Authentication
  2989. testSMTP: (data: TestSMTPRequest) =>
  2990. request<TestSMTPResponse>('/auth/smtp/test', {
  2991. method: 'POST',
  2992. body: JSON.stringify(data),
  2993. }),
  2994. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  2995. saveSMTPSettings: (data: SMTPSettings) =>
  2996. request<{ message: string }>('/auth/smtp', {
  2997. method: 'POST',
  2998. body: JSON.stringify(data),
  2999. }),
  3000. enableAdvancedAuth: () =>
  3001. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  3002. method: 'POST',
  3003. }),
  3004. disableAdvancedAuth: () =>
  3005. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  3006. method: 'POST',
  3007. }),
  3008. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  3009. // LDAP Authentication
  3010. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  3011. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  3012. testLDAP: () =>
  3013. request<LDAPTestResponse>('/auth/ldap/test', {
  3014. method: 'POST',
  3015. }),
  3016. searchLDAPDirectory: (q: string) =>
  3017. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  3018. provisionLDAPUser: (username: string) =>
  3019. request<UserResponse>('/auth/ldap/provision', {
  3020. method: 'POST',
  3021. body: JSON.stringify({ username }),
  3022. }),
  3023. forgotPassword: (data: ForgotPasswordRequest) =>
  3024. request<ForgotPasswordResponse>('/auth/forgot-password', {
  3025. method: 'POST',
  3026. body: JSON.stringify(data),
  3027. }),
  3028. // H-6: Confirm password reset using the token from the emailed link
  3029. forgotPasswordConfirm: (token: string, newPassword: string) =>
  3030. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  3031. method: 'POST',
  3032. body: JSON.stringify({ token, new_password: newPassword }),
  3033. }),
  3034. resetUserPassword: (data: ResetPasswordRequest) =>
  3035. request<ResetPasswordResponse>('/auth/reset-password', {
  3036. method: 'POST',
  3037. body: JSON.stringify(data),
  3038. }),
  3039. // 2FA - status
  3040. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  3041. // 2FA - TOTP
  3042. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  3043. enableTOTP: (code: string) =>
  3044. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  3045. method: 'POST',
  3046. body: JSON.stringify({ code }),
  3047. }),
  3048. disableTOTP: (code: string) =>
  3049. request<{ message: string }>('/auth/2fa/totp/disable', {
  3050. method: 'POST',
  3051. body: JSON.stringify({ code }),
  3052. }),
  3053. regenerateBackupCodes: (code: string) =>
  3054. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  3055. method: 'POST',
  3056. body: JSON.stringify({ code }),
  3057. }),
  3058. // 2FA - Email OTP
  3059. // Step 1: send a verification code to the user's email (proof of possession)
  3060. enableEmailOTP: () =>
  3061. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  3062. // Step 2: confirm with the code received by email
  3063. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  3064. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  3065. method: 'POST',
  3066. body: JSON.stringify({ setup_token, code }),
  3067. }),
  3068. // Disable requires account password for re-auth
  3069. disableEmailOTP: (password: string) =>
  3070. request<{ message: string }>('/auth/2fa/email/disable', {
  3071. method: 'POST',
  3072. body: JSON.stringify({ password }),
  3073. }),
  3074. sendEmailOTP: (preAuthToken: string) =>
  3075. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  3076. method: 'POST',
  3077. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  3078. }),
  3079. // 2FA - verify (completes login)
  3080. verify2FA: (data: TwoFAVerifyRequest) =>
  3081. request<LoginResponse>('/auth/2fa/verify', {
  3082. method: 'POST',
  3083. body: JSON.stringify(data),
  3084. }),
  3085. // 2FA - admin
  3086. admin2FADisable: (userId: number) =>
  3087. request<{ message: string }>(`/auth/2fa/admin/${userId}`, { method: 'DELETE' }),
  3088. // OIDC providers (public list)
  3089. getOIDCProviders: () => request<OIDCProvider[]>('/auth/oidc/providers'),
  3090. // OIDC providers (admin)
  3091. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  3092. createOIDCProvider: (data: OIDCProviderCreate) =>
  3093. request<OIDCProvider>('/auth/oidc/providers', {
  3094. method: 'POST',
  3095. body: JSON.stringify(data),
  3096. }),
  3097. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  3098. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  3099. method: 'PUT',
  3100. body: JSON.stringify(data),
  3101. }),
  3102. deleteOIDCProvider: (id: number) =>
  3103. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  3104. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  3105. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  3106. // so a future caller can't accidentally substitute an attacker-
  3107. // controlled URL where this is consumed.
  3108. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  3109. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  3110. deleteOIDCProviderIcon: (id: number) =>
  3111. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  3112. refreshOIDCProviderIcon: (id: number) =>
  3113. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  3114. // OIDC authorize URL
  3115. getOIDCAuthorizeUrl: (providerId: number) =>
  3116. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  3117. // OIDC exchange token for JWT
  3118. exchangeOIDCToken: (oidcToken: string) =>
  3119. request<LoginResponse>('/auth/oidc/exchange', {
  3120. method: 'POST',
  3121. body: JSON.stringify({ oidc_token: oidcToken }),
  3122. }),
  3123. // OIDC links for current user
  3124. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  3125. deleteOIDCLink: (providerId: number) =>
  3126. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  3127. // Users
  3128. getUsers: () => request<UserResponse[]>('/users/'),
  3129. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  3130. createUser: (data: UserCreate) =>
  3131. request<UserResponse>('/users/', {
  3132. method: 'POST',
  3133. body: JSON.stringify(data),
  3134. }),
  3135. updateUser: (id: number, data: UserUpdate) =>
  3136. request<UserResponse>(`/users/${id}`, {
  3137. method: 'PATCH',
  3138. body: JSON.stringify(data),
  3139. }),
  3140. deleteUser: (id: number, deleteItems: boolean = false) =>
  3141. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  3142. method: 'DELETE',
  3143. }),
  3144. getUserItemsCount: (id: number) =>
  3145. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  3146. changePassword: (currentPassword: string, newPassword: string) =>
  3147. request<{ message: string }>('/users/me/change-password', {
  3148. method: 'POST',
  3149. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  3150. }),
  3151. // User Email Notifications
  3152. getUserEmailPreferences: () =>
  3153. request<UserEmailPreferences>('/user-notifications/preferences'),
  3154. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  3155. request<UserEmailPreferences>('/user-notifications/preferences', {
  3156. method: 'PUT',
  3157. body: JSON.stringify(data),
  3158. }),
  3159. // Groups
  3160. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  3161. getGroups: () => request<Group[]>('/groups/'),
  3162. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  3163. createGroup: (data: GroupCreate) =>
  3164. request<Group>('/groups/', {
  3165. method: 'POST',
  3166. body: JSON.stringify(data),
  3167. }),
  3168. updateGroup: (id: number, data: GroupUpdate) =>
  3169. request<Group>(`/groups/${id}`, {
  3170. method: 'PATCH',
  3171. body: JSON.stringify(data),
  3172. }),
  3173. deleteGroup: (id: number) =>
  3174. request<void>(`/groups/${id}`, {
  3175. method: 'DELETE',
  3176. }),
  3177. addUserToGroup: (groupId: number, userId: number) =>
  3178. request<void>(`/groups/${groupId}/users/${userId}`, {
  3179. method: 'POST',
  3180. }),
  3181. removeUserFromGroup: (groupId: number, userId: number) =>
  3182. request<void>(`/groups/${groupId}/users/${userId}`, {
  3183. method: 'DELETE',
  3184. }),
  3185. // Printers
  3186. getPrinters: () => request<Printer[]>('/printers/'),
  3187. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  3188. createPrinter: (data: PrinterCreate) =>
  3189. request<Printer>('/printers/', {
  3190. method: 'POST',
  3191. body: JSON.stringify(data),
  3192. }),
  3193. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  3194. request<Printer>(`/printers/${id}`, {
  3195. method: 'PATCH',
  3196. body: JSON.stringify(data),
  3197. }),
  3198. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  3199. request<{ status: string; archives_deleted: boolean }>(
  3200. `/printers/${id}?delete_archives=${deleteArchives}`,
  3201. { method: 'DELETE' }
  3202. ),
  3203. getDeveloperModeWarnings: () =>
  3204. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  3205. getAvailableFilaments: (model: string, location?: string) => {
  3206. const params = new URLSearchParams({ model });
  3207. if (location) params.set('location', location);
  3208. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  3209. },
  3210. getPrinterStatus: (id: number) =>
  3211. request<PrinterStatus>(`/printers/${id}/status`),
  3212. refreshPrinterStatus: (id: number) =>
  3213. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  3214. method: 'POST',
  3215. }),
  3216. connectPrinter: (id: number) =>
  3217. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  3218. method: 'POST',
  3219. }),
  3220. disconnectPrinter: (id: number) =>
  3221. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  3222. method: 'POST',
  3223. }),
  3224. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  3225. request<{ success: boolean; error?: string; resolution?: string }>(
  3226. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  3227. { method: 'POST' }
  3228. ),
  3229. // Print Control
  3230. stopPrint: (printerId: number) =>
  3231. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  3232. method: 'POST',
  3233. }),
  3234. pausePrint: (printerId: number) =>
  3235. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  3236. method: 'POST',
  3237. }),
  3238. resumePrint: (printerId: number) =>
  3239. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  3240. method: 'POST',
  3241. }),
  3242. clearPlate: (printerId: number) =>
  3243. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  3244. method: 'POST',
  3245. }),
  3246. // Get current print user (for reprint tracking - Issue #206)
  3247. getCurrentPrintUser: (printerId: number) =>
  3248. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  3249. // Print Speed Control
  3250. setPrintSpeed: (printerId: number, mode: number) =>
  3251. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  3252. method: 'POST',
  3253. }),
  3254. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  3255. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  3256. method: 'POST',
  3257. }),
  3258. // Bed (Z-axis) jog
  3259. bedJog: (printerId: number, distance: number, force: boolean = false) =>
  3260. request<{ success: boolean; message: string }>(
  3261. `/printers/${printerId}/bed-jog?distance=${distance}&force=${force}`,
  3262. { method: 'POST' }
  3263. ),
  3264. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  3265. request<{ success: boolean; message: string }>(
  3266. `/printers/${printerId}/home-axes?axes=${axes}`,
  3267. { method: 'POST' }
  3268. ),
  3269. // Chamber Light Control
  3270. setChamberLight: (printerId: number, on: boolean) =>
  3271. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  3272. method: 'POST',
  3273. }),
  3274. // AMS Drying Control
  3275. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  3276. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  3277. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  3278. { method: 'POST' }
  3279. ),
  3280. stopDrying: (printerId: number, amsId: number) =>
  3281. request<{ status: string; ams_id: number }>(
  3282. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  3283. { method: 'POST' }
  3284. ),
  3285. // Skip Objects
  3286. getPrintableObjects: (printerId: number) =>
  3287. request<{
  3288. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  3289. total: number;
  3290. skipped_count: number;
  3291. is_printing: boolean;
  3292. bbox_all: [number, number, number, number] | null;
  3293. }>(`/printers/${printerId}/print/objects`),
  3294. skipObjects: (printerId: number, objectIds: number[]) =>
  3295. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  3296. `/printers/${printerId}/print/skip-objects`,
  3297. {
  3298. method: 'POST',
  3299. body: JSON.stringify(objectIds),
  3300. }
  3301. ),
  3302. // HMS Errors
  3303. clearHMSErrors: (printerId: number) =>
  3304. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  3305. // AMS Control
  3306. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  3307. request<{ success: boolean; message: string }>(
  3308. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  3309. { method: 'POST' }
  3310. ),
  3311. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 254 for external spool.
  3312. loadAmsTray: (printerId: number, trayId: number) =>
  3313. request<{ success: boolean; message: string }>(
  3314. `/printers/${printerId}/ams/load?tray_id=${trayId}`,
  3315. { method: 'POST' }
  3316. ),
  3317. // Unload the currently loaded filament.
  3318. unloadAms: (printerId: number) =>
  3319. request<{ success: boolean; message: string }>(
  3320. `/printers/${printerId}/ams/unload`,
  3321. { method: 'POST' }
  3322. ),
  3323. // MQTT Debug Logging
  3324. enableMQTTLogging: (printerId: number) =>
  3325. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  3326. method: 'POST',
  3327. }),
  3328. disableMQTTLogging: (printerId: number) =>
  3329. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  3330. method: 'POST',
  3331. }),
  3332. getMQTTLogs: (printerId: number) =>
  3333. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  3334. clearMQTTLogs: (printerId: number) =>
  3335. request<{ status: string }>(`/printers/${printerId}/logging`, {
  3336. method: 'DELETE',
  3337. }),
  3338. // Printer File Manager
  3339. getPrinterFiles: (printerId: number, path = '/') =>
  3340. request<{
  3341. path: string;
  3342. files: Array<{
  3343. name: string;
  3344. is_directory: boolean;
  3345. size: number;
  3346. path: string;
  3347. mtime?: string;
  3348. }>;
  3349. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  3350. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  3351. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3352. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  3353. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  3354. getPrinterFilePlates: (printerId: number, path: string) =>
  3355. request<{
  3356. printer_id: number;
  3357. path: string;
  3358. filename: string;
  3359. plates: Array<{
  3360. index: number;
  3361. name: string | null;
  3362. objects: string[];
  3363. has_thumbnail: boolean;
  3364. thumbnail_url: string | null;
  3365. print_time_seconds: number | null;
  3366. filament_used_grams: number | null;
  3367. filaments: Array<{
  3368. slot_id: number;
  3369. type: string;
  3370. color: string;
  3371. used_grams: number;
  3372. used_meters: number;
  3373. }>;
  3374. }>;
  3375. is_multi_plate: boolean;
  3376. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  3377. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  3378. withStreamToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  3379. downloadPrinterFile: async (printerId: number, path: string): Promise<void> => {
  3380. const headers: Record<string, string> = {};
  3381. if (authToken) {
  3382. headers['Authorization'] = `Bearer ${authToken}`;
  3383. }
  3384. const response = await fetch(
  3385. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  3386. { headers }
  3387. );
  3388. if (!response.ok) {
  3389. const error = await response.json().catch(() => ({}));
  3390. throw new Error(error.detail || `HTTP ${response.status}`);
  3391. }
  3392. const disposition = response.headers.get('Content-Disposition');
  3393. const filename = parseContentDispositionFilename(disposition) || path.split('/').pop() || 'download';
  3394. const blob = await response.blob();
  3395. const url = window.URL.createObjectURL(blob);
  3396. const a = document.createElement('a');
  3397. a.href = url;
  3398. a.download = filename;
  3399. document.body.appendChild(a);
  3400. a.click();
  3401. document.body.removeChild(a);
  3402. window.URL.revokeObjectURL(url);
  3403. },
  3404. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  3405. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  3406. if (authToken) {
  3407. headers['Authorization'] = `Bearer ${authToken}`;
  3408. }
  3409. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  3410. method: 'POST',
  3411. headers,
  3412. body: JSON.stringify({ paths }),
  3413. });
  3414. if (!response.ok) {
  3415. const error = await response.json().catch(() => ({}));
  3416. throw new Error(error.detail || `HTTP ${response.status}`);
  3417. }
  3418. return response.blob();
  3419. },
  3420. deletePrinterFile: (printerId: number, path: string) =>
  3421. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  3422. method: 'DELETE',
  3423. }),
  3424. getPrinterStorage: (printerId: number) =>
  3425. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  3426. // Archives
  3427. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  3428. const params = new URLSearchParams();
  3429. if (printerId) params.set('printer_id', String(printerId));
  3430. if (projectId) params.set('project_id', String(projectId));
  3431. params.set('limit', String(limit));
  3432. params.set('offset', String(offset));
  3433. if (dateFrom) params.set('date_from', dateFrom);
  3434. if (dateTo) params.set('date_to', dateTo);
  3435. return request<Archive[]>(`/archives/?${params}`);
  3436. },
  3437. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  3438. const params = new URLSearchParams();
  3439. if (dateFrom) params.set('date_from', dateFrom);
  3440. if (dateTo) params.set('date_to', dateTo);
  3441. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  3442. const qs = params.toString();
  3443. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  3444. },
  3445. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  3446. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  3447. /**
  3448. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  3449. * related queue items that will be removed along with the archive AND how
  3450. * many are currently printing (server 409s on delete if > 0).
  3451. */
  3452. getArchiveDeleteImpact: (id: number) =>
  3453. request<{ related_queue_items: number; currently_printing: number }>(
  3454. `/archives/${id}/delete-impact`
  3455. ),
  3456. searchArchives: (query: string, options?: {
  3457. printerId?: number;
  3458. projectId?: number;
  3459. status?: string;
  3460. limit?: number;
  3461. offset?: number;
  3462. }) => {
  3463. const params = new URLSearchParams();
  3464. params.set('q', query);
  3465. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3466. if (options?.projectId) params.set('project_id', String(options.projectId));
  3467. if (options?.status) params.set('status', options.status);
  3468. if (options?.limit) params.set('limit', String(options.limit));
  3469. if (options?.offset) params.set('offset', String(options.offset));
  3470. return request<Archive[]>(`/archives/search?${params}`);
  3471. },
  3472. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  3473. getNo3MFWarning: () => request<{ has_fallback: boolean }>('/archives/no-3mf-warning'),
  3474. updateArchive: (id: number, data: {
  3475. printer_id?: number | null;
  3476. project_id?: number | null;
  3477. print_name?: string;
  3478. is_favorite?: boolean;
  3479. tags?: string;
  3480. notes?: string;
  3481. cost?: number;
  3482. failure_reason?: string | null;
  3483. status?: string;
  3484. quantity?: number;
  3485. external_url?: string | null;
  3486. }) =>
  3487. request<Archive>(`/archives/${id}`, {
  3488. method: 'PATCH',
  3489. body: JSON.stringify(data),
  3490. }),
  3491. toggleFavorite: (id: number) =>
  3492. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  3493. // Soft-deletes by default (#1343): files removed from disk, row hidden
  3494. // from listings, but its filament / time / cost / energy contribution
  3495. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  3496. // row from statistics too.
  3497. deleteArchive: (id: number, purgeStats: boolean = false) =>
  3498. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  3499. // ========== Archive auto-purge (#1008 follow-up) ==========
  3500. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3501. request<ArchivePurgePreview>(
  3502. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  3503. ),
  3504. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  3505. // preserved, files removed from disk, row hidden via deleted_at. true matches
  3506. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  3507. // linked PrintLogEntry rows so the contribution drops from /stats too).
  3508. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  3509. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  3510. method: 'POST',
  3511. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  3512. }),
  3513. getArchivePurgeSettings: () =>
  3514. request<ArchivePurgeSettings>('/archives/purge/settings'),
  3515. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  3516. request<ArchivePurgeSettings>('/archives/purge/settings', {
  3517. method: 'PUT',
  3518. body: JSON.stringify(body),
  3519. }),
  3520. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  3521. const params = new URLSearchParams();
  3522. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3523. if (options?.dateTo) params.set('date_to', options.dateTo);
  3524. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3525. const qs = params.toString();
  3526. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  3527. },
  3528. // Tag management
  3529. getTags: () => request<TagInfo[]>('/archives/tags'),
  3530. renameTag: (oldName: string, newName: string) =>
  3531. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  3532. method: 'PUT',
  3533. body: JSON.stringify({ new_name: newName }),
  3534. }),
  3535. deleteTag: (name: string) =>
  3536. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  3537. method: 'DELETE',
  3538. }),
  3539. recalculateCosts: () =>
  3540. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  3541. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  3542. const params = new URLSearchParams();
  3543. if (options?.days) params.set('days', String(options.days));
  3544. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3545. if (options?.dateTo) params.set('date_to', options.dateTo);
  3546. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3547. if (options?.projectId) params.set('project_id', String(options.projectId));
  3548. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3549. const qs = params.toString();
  3550. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  3551. },
  3552. compareArchives: (archiveIds: number[]) =>
  3553. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  3554. findSimilarArchives: (archiveId: number, limit = 10) =>
  3555. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  3556. exportArchives: async (options?: {
  3557. format?: 'csv' | 'xlsx';
  3558. fields?: string[];
  3559. printerId?: number;
  3560. projectId?: number;
  3561. status?: string;
  3562. dateFrom?: string;
  3563. dateTo?: string;
  3564. search?: string;
  3565. }): Promise<{ blob: Blob; filename: string }> => {
  3566. const params = new URLSearchParams();
  3567. if (options?.format) params.set('format', options.format);
  3568. if (options?.fields) params.set('fields', options.fields.join(','));
  3569. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3570. if (options?.projectId) params.set('project_id', String(options.projectId));
  3571. if (options?.status) params.set('status', options.status);
  3572. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  3573. if (options?.dateTo) params.set('date_to', options.dateTo);
  3574. if (options?.search) params.set('search', options.search);
  3575. const headers: Record<string, string> = {};
  3576. if (authToken) {
  3577. headers['Authorization'] = `Bearer ${authToken}`;
  3578. }
  3579. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  3580. if (!response.ok) {
  3581. const error = await response.json().catch(() => ({}));
  3582. throw new Error(error.detail || `HTTP ${response.status}`);
  3583. }
  3584. const contentDisposition = response.headers.get('Content-Disposition');
  3585. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  3586. if (contentDisposition) {
  3587. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3588. if (match) filename = match[1];
  3589. }
  3590. const blob = await response.blob();
  3591. return { blob, filename };
  3592. },
  3593. exportStats: async (options?: {
  3594. format?: 'csv' | 'xlsx';
  3595. days?: number;
  3596. printerId?: number;
  3597. projectId?: number;
  3598. createdById?: number;
  3599. }): Promise<{ blob: Blob; filename: string }> => {
  3600. const params = new URLSearchParams();
  3601. if (options?.format) params.set('format', options.format);
  3602. if (options?.days) params.set('days', String(options.days));
  3603. if (options?.printerId) params.set('printer_id', String(options.printerId));
  3604. if (options?.projectId) params.set('project_id', String(options.projectId));
  3605. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  3606. const headers: Record<string, string> = {};
  3607. if (authToken) {
  3608. headers['Authorization'] = `Bearer ${authToken}`;
  3609. }
  3610. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  3611. if (!response.ok) {
  3612. const error = await response.json().catch(() => ({}));
  3613. throw new Error(error.detail || `HTTP ${response.status}`);
  3614. }
  3615. const contentDisposition = response.headers.get('Content-Disposition');
  3616. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  3617. if (contentDisposition) {
  3618. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  3619. if (match) filename = match[1];
  3620. }
  3621. const blob = await response.blob();
  3622. return { blob, filename };
  3623. },
  3624. getArchiveDuplicates: (id: number) =>
  3625. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  3626. backfillContentHashes: () =>
  3627. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  3628. method: 'POST',
  3629. }),
  3630. getArchiveThumbnail: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  3631. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  3632. withStreamToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  3633. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  3634. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  3635. const headers: Record<string, string> = {};
  3636. if (authToken) {
  3637. headers['Authorization'] = `Bearer ${authToken}`;
  3638. }
  3639. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  3640. if (!response.ok) {
  3641. const error = await response.json().catch(() => ({}));
  3642. throw new Error(error.detail || `HTTP ${response.status}`);
  3643. }
  3644. const disposition = response.headers.get('Content-Disposition');
  3645. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  3646. const blob = await response.blob();
  3647. const url = window.URL.createObjectURL(blob);
  3648. const a = document.createElement('a');
  3649. a.href = url;
  3650. a.download = downloadFilename;
  3651. document.body.appendChild(a);
  3652. a.click();
  3653. document.body.removeChild(a);
  3654. window.URL.revokeObjectURL(url);
  3655. },
  3656. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  3657. getArchivePlatePreview: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/plate-preview`),
  3658. getArchiveTimelapse: (id: number) => withStreamToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  3659. scanArchiveTimelapse: (id: number) =>
  3660. request<{
  3661. status: string;
  3662. message: string;
  3663. filename?: string;
  3664. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  3665. }>(`/archives/${id}/timelapse/scan`, {
  3666. method: 'POST',
  3667. }),
  3668. selectArchiveTimelapse: (id: number, filename: string) =>
  3669. request<{ status: string; message: string; filename: string }>(
  3670. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  3671. { method: 'POST' }
  3672. ),
  3673. deleteArchiveTimelapse: (id: number) =>
  3674. request<{ status: string }>(`/archives/${id}/timelapse`, {
  3675. method: 'DELETE',
  3676. }),
  3677. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3678. const formData = new FormData();
  3679. formData.append('file', file);
  3680. const headers: Record<string, string> = {};
  3681. if (authToken) {
  3682. headers['Authorization'] = `Bearer ${authToken}`;
  3683. }
  3684. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  3685. method: 'POST',
  3686. headers,
  3687. body: formData,
  3688. });
  3689. if (!response.ok) {
  3690. const error = await response.json().catch(() => ({}));
  3691. throw new Error(error.detail || `HTTP ${response.status}`);
  3692. }
  3693. return response.json();
  3694. },
  3695. // Timelapse Editor
  3696. getTimelapseInfo: (archiveId: number) =>
  3697. request<{
  3698. duration: number;
  3699. width: number;
  3700. height: number;
  3701. fps: number;
  3702. codec: string;
  3703. file_size: number;
  3704. has_audio: boolean;
  3705. }>(`/archives/${archiveId}/timelapse/info`),
  3706. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  3707. request<{
  3708. thumbnails: string[];
  3709. timestamps: number[];
  3710. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  3711. processTimelapse: async (
  3712. archiveId: number,
  3713. params: {
  3714. trimStart?: number;
  3715. trimEnd?: number;
  3716. speed?: number;
  3717. saveMode: 'replace' | 'new';
  3718. outputFilename?: string;
  3719. },
  3720. audioFile?: File
  3721. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  3722. const formData = new FormData();
  3723. formData.append('trim_start', String(params.trimStart ?? 0));
  3724. if (params.trimEnd !== undefined) {
  3725. formData.append('trim_end', String(params.trimEnd));
  3726. }
  3727. formData.append('speed', String(params.speed ?? 1));
  3728. formData.append('save_mode', params.saveMode);
  3729. if (params.outputFilename) {
  3730. formData.append('output_filename', params.outputFilename);
  3731. }
  3732. if (audioFile) {
  3733. formData.append('audio', audioFile);
  3734. }
  3735. const headers: Record<string, string> = {};
  3736. if (authToken) {
  3737. headers['Authorization'] = `Bearer ${authToken}`;
  3738. }
  3739. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  3740. method: 'POST',
  3741. headers,
  3742. body: formData,
  3743. });
  3744. if (!response.ok) {
  3745. const error = await response.json().catch(() => ({}));
  3746. throw new Error(error.detail || `HTTP ${response.status}`);
  3747. }
  3748. return response.json();
  3749. },
  3750. // Photos
  3751. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  3752. withStreamToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  3753. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  3754. const formData = new FormData();
  3755. formData.append('file', file);
  3756. const headers: Record<string, string> = {};
  3757. if (authToken) {
  3758. headers['Authorization'] = `Bearer ${authToken}`;
  3759. }
  3760. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  3761. headers,
  3762. method: 'POST',
  3763. body: formData,
  3764. });
  3765. if (!response.ok) {
  3766. const error = await response.json().catch(() => ({}));
  3767. throw new Error(error.detail || `HTTP ${response.status}`);
  3768. }
  3769. return response.json();
  3770. },
  3771. deleteArchivePhoto: (archiveId: number, filename: string) =>
  3772. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  3773. method: 'DELETE',
  3774. }),
  3775. // Source 3MF (original slicer project file)
  3776. getSource3mfDownloadUrl: (archiveId: number) =>
  3777. `${API_BASE}/archives/${archiveId}/source`,
  3778. downloadSource3mf: async (archiveId: number): Promise<void> => {
  3779. const headers: Record<string, string> = {};
  3780. if (authToken) {
  3781. headers['Authorization'] = `Bearer ${authToken}`;
  3782. }
  3783. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  3784. if (!response.ok) {
  3785. const error = await response.json().catch(() => ({}));
  3786. throw new Error(error.detail || `HTTP ${response.status}`);
  3787. }
  3788. const disposition = response.headers.get('Content-Disposition');
  3789. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  3790. const blob = await response.blob();
  3791. const url = window.URL.createObjectURL(blob);
  3792. const a = document.createElement('a');
  3793. a.href = url;
  3794. a.download = filename;
  3795. document.body.appendChild(a);
  3796. a.click();
  3797. document.body.removeChild(a);
  3798. window.URL.revokeObjectURL(url);
  3799. },
  3800. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  3801. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  3802. const safe = filename.replace(/[/\\?#]/g, '_');
  3803. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3804. },
  3805. createSourceSlicerToken: (archiveId: number) =>
  3806. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  3807. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3808. const safe = filename.replace(/[/\\?#]/g, '_');
  3809. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3810. },
  3811. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3812. const formData = new FormData();
  3813. formData.append('file', file);
  3814. const headers: Record<string, string> = {};
  3815. if (authToken) {
  3816. headers['Authorization'] = `Bearer ${authToken}`;
  3817. }
  3818. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  3819. method: 'POST',
  3820. headers,
  3821. body: formData,
  3822. });
  3823. if (!response.ok) {
  3824. const error = await response.json().catch(() => ({}));
  3825. throw new Error(error.detail || `HTTP ${response.status}`);
  3826. }
  3827. return response.json();
  3828. },
  3829. deleteSource3mf: (archiveId: number) =>
  3830. request<{ status: string }>(`/archives/${archiveId}/source`, {
  3831. method: 'DELETE',
  3832. }),
  3833. // F3D (Fusion 360 design file)
  3834. getF3dDownloadUrl: (archiveId: number) =>
  3835. `${API_BASE}/archives/${archiveId}/f3d`,
  3836. downloadF3d: async (archiveId: number): Promise<void> => {
  3837. const headers: Record<string, string> = {};
  3838. if (authToken) {
  3839. headers['Authorization'] = `Bearer ${authToken}`;
  3840. }
  3841. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  3842. if (!response.ok) {
  3843. const error = await response.json().catch(() => ({}));
  3844. throw new Error(error.detail || `HTTP ${response.status}`);
  3845. }
  3846. const disposition = response.headers.get('Content-Disposition');
  3847. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  3848. const blob = await response.blob();
  3849. const url = window.URL.createObjectURL(blob);
  3850. const a = document.createElement('a');
  3851. a.href = url;
  3852. a.download = filename;
  3853. document.body.appendChild(a);
  3854. a.click();
  3855. document.body.removeChild(a);
  3856. window.URL.revokeObjectURL(url);
  3857. },
  3858. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  3859. const formData = new FormData();
  3860. formData.append('file', file);
  3861. const headers: Record<string, string> = {};
  3862. if (authToken) {
  3863. headers['Authorization'] = `Bearer ${authToken}`;
  3864. }
  3865. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  3866. method: 'POST',
  3867. headers,
  3868. body: formData,
  3869. });
  3870. if (!response.ok) {
  3871. const error = await response.json().catch(() => ({}));
  3872. throw new Error(error.detail || `HTTP ${response.status}`);
  3873. }
  3874. return response.json();
  3875. },
  3876. deleteF3d: (archiveId: number) =>
  3877. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  3878. method: 'DELETE',
  3879. }),
  3880. // QR Code
  3881. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  3882. withStreamToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  3883. getArchiveCapabilities: (id: number) =>
  3884. request<{
  3885. has_model: boolean;
  3886. has_gcode: boolean;
  3887. has_source: boolean;
  3888. build_volume: { x: number; y: number; z: number };
  3889. filament_colors: string[];
  3890. }>(`/archives/${id}/capabilities`),
  3891. // Project Page
  3892. getArchiveProjectPage: (id: number) =>
  3893. request<{
  3894. title: string | null;
  3895. description: string | null;
  3896. designer: string | null;
  3897. designer_user_id: string | null;
  3898. license: string | null;
  3899. copyright: string | null;
  3900. creation_date: string | null;
  3901. modification_date: string | null;
  3902. origin: string | null;
  3903. profile_title: string | null;
  3904. profile_description: string | null;
  3905. profile_cover: string | null;
  3906. profile_user_id: string | null;
  3907. profile_user_name: string | null;
  3908. design_model_id: string | null;
  3909. design_profile_id: string | null;
  3910. design_region: string | null;
  3911. model_pictures: Array<{ name: string; path: string; url: string }>;
  3912. profile_pictures: Array<{ name: string; path: string; url: string }>;
  3913. thumbnails: Array<{ name: string; path: string; url: string }>;
  3914. }>(`/archives/${id}/project-page`),
  3915. updateArchiveProjectPage: (id: number, data: {
  3916. title?: string;
  3917. description?: string;
  3918. designer?: string;
  3919. license?: string;
  3920. copyright?: string;
  3921. profile_title?: string;
  3922. profile_description?: string;
  3923. }) =>
  3924. request(`/archives/${id}/project-page`, {
  3925. method: 'PATCH',
  3926. body: JSON.stringify(data),
  3927. }),
  3928. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  3929. withStreamToken(`${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`),
  3930. getArchiveForSlicer: (id: number, filename: string) => {
  3931. const safe = filename.replace(/[/\\?#]/g, '_');
  3932. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3933. },
  3934. createArchiveSlicerToken: (archiveId: number) =>
  3935. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  3936. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  3937. const safe = filename.replace(/[/\\?#]/g, '_');
  3938. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  3939. },
  3940. getArchivePlates: (archiveId: number) =>
  3941. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  3942. getArchiveFilamentRequirements: (
  3943. archiveId: number,
  3944. plateId?: number,
  3945. requestId?: string,
  3946. ) => {
  3947. const qs = new URLSearchParams();
  3948. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  3949. if (requestId) qs.set('request_id', requestId);
  3950. return request<{
  3951. archive_id: number;
  3952. filename: string;
  3953. plate_id: number | null;
  3954. filaments: Array<{
  3955. slot_id: number;
  3956. type: string;
  3957. color: string;
  3958. used_grams: number;
  3959. used_meters: number;
  3960. used_in_plate?: boolean;
  3961. }>;
  3962. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  3963. },
  3964. reprintArchive: (
  3965. archiveId: number,
  3966. printerId: number,
  3967. options?: {
  3968. plate_id?: number;
  3969. plate_name?: string;
  3970. ams_mapping?: number[];
  3971. timelapse?: boolean;
  3972. bed_levelling?: boolean;
  3973. flow_cali?: boolean;
  3974. vibration_cali?: boolean;
  3975. layer_inspect?: boolean;
  3976. use_ams?: boolean;
  3977. nozzle_offset_cali?: boolean;
  3978. }
  3979. ) =>
  3980. request<BackgroundDispatchResponse>(
  3981. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  3982. {
  3983. method: 'POST',
  3984. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  3985. body: options ? JSON.stringify(options) : undefined,
  3986. }
  3987. ),
  3988. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  3989. const formData = new FormData();
  3990. formData.append('file', file);
  3991. const url = printerId
  3992. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  3993. : `${API_BASE}/archives/upload`;
  3994. const headers: Record<string, string> = {};
  3995. if (authToken) {
  3996. headers['Authorization'] = `Bearer ${authToken}`;
  3997. }
  3998. const response = await fetch(url, {
  3999. method: 'POST',
  4000. headers,
  4001. body: formData,
  4002. });
  4003. if (!response.ok) {
  4004. const error = await response.json().catch(() => ({}));
  4005. throw new Error(error.detail || `HTTP ${response.status}`);
  4006. }
  4007. return response.json();
  4008. },
  4009. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  4010. const formData = new FormData();
  4011. files.forEach((file) => formData.append('files', file));
  4012. const url = printerId
  4013. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  4014. : `${API_BASE}/archives/upload-bulk`;
  4015. const headers: Record<string, string> = {};
  4016. if (authToken) {
  4017. headers['Authorization'] = `Bearer ${authToken}`;
  4018. }
  4019. const response = await fetch(url, {
  4020. method: 'POST',
  4021. headers,
  4022. body: formData,
  4023. });
  4024. if (!response.ok) {
  4025. const error = await response.json().catch(() => ({}));
  4026. throw new Error(error.detail || `HTTP ${response.status}`);
  4027. }
  4028. return response.json();
  4029. },
  4030. // Print Log
  4031. getPrintLog: (params?: {
  4032. search?: string;
  4033. printerId?: number;
  4034. username?: string;
  4035. status?: string;
  4036. dateFrom?: string;
  4037. dateTo?: string;
  4038. limit?: number;
  4039. offset?: number;
  4040. }) => {
  4041. const searchParams = new URLSearchParams();
  4042. if (params?.search) searchParams.set('search', params.search);
  4043. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  4044. if (params?.username) searchParams.set('created_by_username', params.username);
  4045. if (params?.status) searchParams.set('status', params.status);
  4046. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  4047. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  4048. if (params?.limit) searchParams.set('limit', String(params.limit));
  4049. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  4050. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  4051. },
  4052. getPrintLogThumbnail: (id: number) => withStreamToken(`${API_BASE}/print-log/${id}/thumbnail`),
  4053. clearPrintLog: () =>
  4054. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  4055. deletePrintLogEntry: (id: number) =>
  4056. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  4057. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  4058. // Distinct from updateArchive: archives describe the model, log entries
  4059. // describe a single print event. Orphan entries (no archive_id) have no
  4060. // archive to reach through and this is the only path to classify them.
  4061. updatePrintLogEntry: (
  4062. id: number,
  4063. body: { failure_reason?: string | null; status?: string },
  4064. ) =>
  4065. request<PrintLogEntry>(`/print-log/${id}`, {
  4066. method: 'PATCH',
  4067. body: JSON.stringify(body),
  4068. }),
  4069. // Settings
  4070. getSettings: () => request<AppSettings>('/settings/'),
  4071. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  4072. // Public subset of settings for UI rendering — no settings:read required.
  4073. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  4074. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  4075. // backend/app/api/routes/settings.py.
  4076. getUiPreferences: () =>
  4077. request<{
  4078. require_plate_clear?: boolean;
  4079. check_printer_firmware?: boolean;
  4080. camera_view_mode?: 'window' | 'embedded';
  4081. time_format?: 'system' | '12h' | '24h';
  4082. date_format?: string;
  4083. drying_presets?: string;
  4084. ams_humidity_good?: number;
  4085. ams_humidity_fair?: number;
  4086. ams_temp_good?: number;
  4087. ams_temp_fair?: number;
  4088. bed_cooled_threshold?: number;
  4089. }>('/settings/ui-preferences'),
  4090. updateSettings: (data: AppSettingsUpdate) =>
  4091. request<AppSettings>('/settings/', {
  4092. method: 'PUT',
  4093. body: JSON.stringify(data),
  4094. }),
  4095. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  4096. resetSettings: () =>
  4097. request<AppSettings>('/settings/reset', { method: 'POST' }),
  4098. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  4099. // New simplified backup - complete database + all files
  4100. const url = `${API_BASE}/settings/backup`;
  4101. const headers: Record<string, string> = {};
  4102. if (authToken) {
  4103. headers['Authorization'] = `Bearer ${authToken}`;
  4104. }
  4105. const response = await fetch(url, { headers });
  4106. // Check for errors
  4107. if (!response.ok) {
  4108. const errorText = await response.text();
  4109. throw new Error(errorText || `Backup failed with status ${response.status}`);
  4110. }
  4111. // Get filename from Content-Disposition header
  4112. const contentDisposition = response.headers.get('Content-Disposition');
  4113. let filename = 'bambuddy-backup.zip';
  4114. if (contentDisposition) {
  4115. const match = contentDisposition.match(/filename=([^;]+)/);
  4116. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  4117. }
  4118. const blob = await response.blob();
  4119. return { blob, filename };
  4120. },
  4121. importBackup: async (file: File) => {
  4122. // New simplified restore - replaces database + all directories
  4123. const formData = new FormData();
  4124. formData.append('file', file);
  4125. const url = `${API_BASE}/settings/restore`;
  4126. const headers: Record<string, string> = {};
  4127. if (authToken) {
  4128. headers['Authorization'] = `Bearer ${authToken}`;
  4129. }
  4130. const response = await fetch(url, {
  4131. method: 'POST',
  4132. headers,
  4133. body: formData,
  4134. });
  4135. return response.json() as Promise<{
  4136. success: boolean;
  4137. message: string;
  4138. }>;
  4139. },
  4140. checkFfmpeg: () =>
  4141. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  4142. getNetworkInterfaces: () =>
  4143. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  4144. // Cloud
  4145. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  4146. cloudLogin: (email: string, password: string, region = 'global') =>
  4147. request<CloudLoginResponse>('/cloud/login', {
  4148. method: 'POST',
  4149. body: JSON.stringify({ email, password, region }),
  4150. }),
  4151. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  4152. request<CloudLoginResponse>('/cloud/verify', {
  4153. method: 'POST',
  4154. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  4155. }),
  4156. cloudSetToken: (access_token: string, region: string = 'global') =>
  4157. request<CloudAuthStatus>('/cloud/token', {
  4158. method: 'POST',
  4159. body: JSON.stringify({ access_token, region }),
  4160. }),
  4161. cloudLogout: () =>
  4162. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  4163. // Orca Cloud — paste-based PKCE flow for OAuth (Google/Apple/GitHub),
  4164. // direct credentials for email+password. start() returns an auth URL the
  4165. // user opens in their browser; after sign-in they paste the callback URL
  4166. // back via finish(). password() skips the dance entirely.
  4167. orcaCloudStartAuth: (provider: OrcaOAuthProvider = 'google') =>
  4168. request<OrcaAuthStartResponse>('/orca-cloud/auth/start', {
  4169. method: 'POST',
  4170. body: JSON.stringify({ provider }),
  4171. }),
  4172. orcaCloudFinishAuth: (callback_url: string) =>
  4173. request<OrcaAuthStatusResponse>('/orca-cloud/auth/finish', {
  4174. method: 'POST',
  4175. body: JSON.stringify({ callback_url }),
  4176. }),
  4177. orcaCloudPasswordLogin: (email: string, password: string) =>
  4178. request<OrcaAuthStatusResponse>('/orca-cloud/auth/password', {
  4179. method: 'POST',
  4180. body: JSON.stringify({ email, password }),
  4181. }),
  4182. orcaCloudStatus: () =>
  4183. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  4184. orcaCloudLogout: () =>
  4185. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  4186. orcaCloudListProfiles: () =>
  4187. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  4188. orcaCloudGetProfile: (id: string) =>
  4189. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  4190. getCloudSettings: (version = '02.04.00.70') =>
  4191. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  4192. getBuiltinFilaments: () =>
  4193. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  4194. getFilamentIdMap: () =>
  4195. request<Record<string, string>>('/cloud/filament-id-map'),
  4196. /** Material-disambiguated hex→name lookup. Same hex can map to different
  4197. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  4198. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  4199. * collapses these to the first hit; this endpoint preserves the material
  4200. * context. Returns ``{color_name: null}`` when the hex isn't in the
  4201. * catalog at all. #1718. */
  4202. getColorByMaterial: (hex: string, material?: string) => {
  4203. const params = new URLSearchParams({ hex });
  4204. if (material) params.set('material', material);
  4205. return request<{ color_name: string | null }>(
  4206. `/inventory/colors/by-material?${params.toString()}`,
  4207. );
  4208. },
  4209. // MakerWorld URL-paste import flow.
  4210. getMakerworldStatus: () =>
  4211. request<MakerworldStatus>('/makerworld/status'),
  4212. resolveMakerworldUrl: (url: string) =>
  4213. request<MakerworldResolvedModel>('/makerworld/resolve', {
  4214. method: 'POST',
  4215. body: JSON.stringify({ url }),
  4216. }),
  4217. getMakerworldRecentImports: (limit = 10) =>
  4218. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  4219. importMakerworldInstance: (
  4220. model_id: number,
  4221. instance_id: number | null,
  4222. profile_id?: number | null,
  4223. folder_id?: number | null,
  4224. ) =>
  4225. request<MakerworldImportResponse>('/makerworld/import', {
  4226. method: 'POST',
  4227. body: JSON.stringify({
  4228. model_id,
  4229. instance_id: instance_id ?? null,
  4230. profile_id: profile_id ?? null,
  4231. folder_id: folder_id ?? null,
  4232. }),
  4233. }),
  4234. getCloudSettingDetail: (settingId: string) =>
  4235. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  4236. createCloudSetting: (data: SlicerSettingCreate) =>
  4237. request<SlicerSettingDetail>('/cloud/settings', {
  4238. method: 'POST',
  4239. body: JSON.stringify(data),
  4240. }),
  4241. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  4242. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  4243. method: 'PUT',
  4244. body: JSON.stringify(data),
  4245. }),
  4246. deleteCloudSetting: (settingId: string) =>
  4247. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  4248. method: 'DELETE',
  4249. }),
  4250. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  4251. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  4252. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  4253. getAllCloudFields: () =>
  4254. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  4255. getFilamentInfo: (settingIds: string[]) =>
  4256. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  4257. method: 'POST',
  4258. body: JSON.stringify(settingIds),
  4259. }),
  4260. // Smart Plugs
  4261. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  4262. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  4263. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  4264. getScriptPlugsByPrinter: (printerId: number) => request<SmartPlug[]>(`/smart-plugs/by-printer/${printerId}/scripts`),
  4265. createSmartPlug: (data: SmartPlugCreate) =>
  4266. request<SmartPlug>('/smart-plugs/', {
  4267. method: 'POST',
  4268. body: JSON.stringify(data),
  4269. }),
  4270. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  4271. request<SmartPlug>(`/smart-plugs/${id}`, {
  4272. method: 'PATCH',
  4273. body: JSON.stringify(data),
  4274. }),
  4275. deleteSmartPlug: (id: number) =>
  4276. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  4277. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  4278. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  4279. method: 'POST',
  4280. body: JSON.stringify({ action }),
  4281. }),
  4282. getSmartPlugStatus: (id: number) =>
  4283. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  4284. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  4285. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  4286. method: 'POST',
  4287. body: JSON.stringify({ ip_address, username, password }),
  4288. }),
  4289. // Tasmota Discovery (auto-detects network)
  4290. startTasmotaScan: () =>
  4291. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  4292. getTasmotaScanStatus: () =>
  4293. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  4294. stopTasmotaScan: () =>
  4295. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  4296. getDiscoveredTasmotaDevices: () =>
  4297. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  4298. // Home Assistant Integration
  4299. testHAConnection: (url: string, token: string) =>
  4300. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  4301. method: 'POST',
  4302. body: JSON.stringify({ url, token }),
  4303. }),
  4304. getHAEntities: (search?: string) => {
  4305. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  4306. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  4307. },
  4308. getHASensorEntities: () =>
  4309. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  4310. // REST smart plug
  4311. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null) =>
  4312. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  4313. method: 'POST',
  4314. body: JSON.stringify({ url, method, headers }),
  4315. }),
  4316. // Print Queue
  4317. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  4318. const params = new URLSearchParams();
  4319. if (printerId) params.set('printer_id', String(printerId));
  4320. if (status) params.set('status', status);
  4321. if (targetModel) params.set('target_model', targetModel);
  4322. return request<PrintQueueItem[]>(`/queue/?${params}`);
  4323. },
  4324. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  4325. addToQueue: (data: PrintQueueItemCreate) =>
  4326. request<PrintQueueItem>('/queue/', {
  4327. method: 'POST',
  4328. body: JSON.stringify(data),
  4329. }),
  4330. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  4331. request<PrintQueueItem>(`/queue/${id}`, {
  4332. method: 'PATCH',
  4333. body: JSON.stringify(data),
  4334. }),
  4335. removeFromQueue: (id: number) =>
  4336. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  4337. reorderQueue: (items: { id: number; position: number }[]) =>
  4338. request<{ message: string }>('/queue/reorder', {
  4339. method: 'POST',
  4340. body: JSON.stringify({ items }),
  4341. }),
  4342. cancelQueueItem: (id: number) =>
  4343. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  4344. stopQueueItem: (id: number) =>
  4345. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  4346. /**
  4347. * Start a staged queue item. The backend re-checks live filament deficit
  4348. * for the assigned spool and, when short, returns 409 with a structured
  4349. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  4350. * after the user confirms "Print Anyway" (#1496).
  4351. */
  4352. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  4353. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  4354. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  4355. },
  4356. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  4357. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  4358. method: 'PATCH',
  4359. body: JSON.stringify(data),
  4360. }),
  4361. // Batches
  4362. getBatches: (status?: string) => {
  4363. const params = status ? `?status=${status}` : '';
  4364. return request<PrintBatch[]>(`/queue/batches${params}`);
  4365. },
  4366. getBatch: (id: number) => request<PrintBatch>(`/queue/batches/${id}`),
  4367. cancelBatch: (id: number) =>
  4368. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  4369. // K-Profiles
  4370. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  4371. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  4372. setKProfile: (printerId: number, profile: KProfileCreate) =>
  4373. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4374. method: 'POST',
  4375. body: JSON.stringify(profile),
  4376. }),
  4377. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  4378. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  4379. method: 'DELETE',
  4380. body: JSON.stringify(profile),
  4381. }),
  4382. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  4383. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  4384. method: 'POST',
  4385. body: JSON.stringify(profiles),
  4386. }),
  4387. // K-Profile Notes (stored locally, not on printer)
  4388. getKProfileNotes: (printerId: number) =>
  4389. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  4390. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  4391. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  4392. method: 'PUT',
  4393. body: JSON.stringify({ setting_id: settingId, note }),
  4394. }),
  4395. deleteKProfileNote: (printerId: number, settingId: string) =>
  4396. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  4397. method: 'DELETE',
  4398. }),
  4399. // Slot Preset Mappings
  4400. getSlotPresets: (printerId: number) =>
  4401. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  4402. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4403. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  4404. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud') =>
  4405. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}`, {
  4406. method: 'PUT',
  4407. }),
  4408. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  4409. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  4410. method: 'DELETE',
  4411. }),
  4412. // AMS Labels (user-defined friendly names)
  4413. getAmsLabels: (printerId: number) =>
  4414. request<Record<number, string>>(`/printers/${printerId}/ams-labels`),
  4415. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  4416. request<{ ams_id: number; label: string }>(
  4417. `/printers/${printerId}/ams-labels/${amsId}`,
  4418. {
  4419. method: 'PUT',
  4420. body: JSON.stringify({ label, ams_serial: amsSerial }),
  4421. }
  4422. ),
  4423. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  4424. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  4425. method: 'DELETE',
  4426. }),
  4427. configureAmsSlot: (
  4428. printerId: number,
  4429. amsId: number,
  4430. trayId: number,
  4431. config: {
  4432. tray_info_idx: string;
  4433. tray_type: string;
  4434. tray_sub_brands: string;
  4435. tray_color: string;
  4436. nozzle_temp_min: number;
  4437. nozzle_temp_max: number;
  4438. cali_idx: number;
  4439. nozzle_diameter: string;
  4440. setting_id?: string;
  4441. kprofile_filament_id?: string;
  4442. kprofile_setting_id?: string;
  4443. k_value?: number;
  4444. }
  4445. ) => {
  4446. const params = new URLSearchParams({
  4447. tray_info_idx: config.tray_info_idx,
  4448. tray_type: config.tray_type,
  4449. tray_sub_brands: config.tray_sub_brands,
  4450. tray_color: config.tray_color,
  4451. nozzle_temp_min: config.nozzle_temp_min.toString(),
  4452. nozzle_temp_max: config.nozzle_temp_max.toString(),
  4453. cali_idx: config.cali_idx.toString(),
  4454. nozzle_diameter: config.nozzle_diameter,
  4455. });
  4456. if (config.setting_id) {
  4457. params.set('setting_id', config.setting_id);
  4458. }
  4459. if (config.kprofile_filament_id) {
  4460. params.set('kprofile_filament_id', config.kprofile_filament_id);
  4461. }
  4462. if (config.kprofile_setting_id) {
  4463. params.set('kprofile_setting_id', config.kprofile_setting_id);
  4464. }
  4465. if (config.k_value !== undefined && config.k_value > 0) {
  4466. params.set('k_value', config.k_value.toString());
  4467. }
  4468. return request<{ success: boolean; message: string }>(
  4469. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  4470. { method: 'POST' }
  4471. );
  4472. },
  4473. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  4474. request<{ success: boolean; message: string }>(
  4475. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  4476. { method: 'POST' }
  4477. ),
  4478. // Filament Catalog (material types with cost/temp data)
  4479. listFilaments: () => request<Filament[]>('/filament-catalog/'),
  4480. getFilament: (id: number) => request<Filament>(`/filament-catalog/${id}`),
  4481. getFilamentsByType: (type: string) => request<Filament[]>(`/filament-catalog/by-type/${type}`),
  4482. // Notification Providers
  4483. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  4484. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  4485. createNotificationProvider: (data: NotificationProviderCreate) =>
  4486. request<NotificationProvider>('/notifications/', {
  4487. method: 'POST',
  4488. body: JSON.stringify(data),
  4489. }),
  4490. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  4491. request<NotificationProvider>(`/notifications/${id}`, {
  4492. method: 'PATCH',
  4493. body: JSON.stringify(data),
  4494. }),
  4495. deleteNotificationProvider: (id: number) =>
  4496. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  4497. testNotificationProvider: (id: number) =>
  4498. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  4499. testNotificationConfig: (data: NotificationTestRequest) =>
  4500. request<NotificationTestResponse>('/notifications/test-config', {
  4501. method: 'POST',
  4502. body: JSON.stringify(data),
  4503. }),
  4504. testAllNotificationProviders: () =>
  4505. request<{
  4506. tested: number;
  4507. success: number;
  4508. failed: number;
  4509. results: Array<{
  4510. provider_id: number;
  4511. provider_name: string;
  4512. provider_type: string;
  4513. success: boolean;
  4514. message: string;
  4515. }>;
  4516. }>('/notifications/test-all', { method: 'POST' }),
  4517. // Notification Templates
  4518. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  4519. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  4520. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  4521. request<NotificationTemplate>(`/notification-templates/${id}`, {
  4522. method: 'PUT',
  4523. body: JSON.stringify(data),
  4524. }),
  4525. resetNotificationTemplate: (id: number) =>
  4526. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  4527. method: 'POST',
  4528. }),
  4529. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  4530. previewTemplate: (data: TemplatePreviewRequest) =>
  4531. request<TemplatePreviewResponse>('/notification-templates/preview', {
  4532. method: 'POST',
  4533. body: JSON.stringify(data),
  4534. }),
  4535. // Notification Logs
  4536. getNotificationLogs: (params?: {
  4537. limit?: number;
  4538. offset?: number;
  4539. provider_id?: number;
  4540. event_type?: string;
  4541. success?: boolean;
  4542. days?: number;
  4543. }) => {
  4544. const searchParams = new URLSearchParams();
  4545. if (params?.limit) searchParams.set('limit', String(params.limit));
  4546. if (params?.offset) searchParams.set('offset', String(params.offset));
  4547. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  4548. if (params?.event_type) searchParams.set('event_type', params.event_type);
  4549. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  4550. if (params?.days) searchParams.set('days', String(params.days));
  4551. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  4552. },
  4553. getNotificationLogStats: (days = 7) =>
  4554. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  4555. clearNotificationLogs: (olderThanDays = 30) =>
  4556. request<{ deleted: number; message: string }>(
  4557. `/notifications/logs?older_than_days=${olderThanDays}`,
  4558. { method: 'DELETE' }
  4559. ),
  4560. // Spoolman Integration
  4561. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  4562. connectSpoolman: () =>
  4563. request<{ success: boolean; message: string }>('/spoolman/connect', {
  4564. method: 'POST',
  4565. }),
  4566. disconnectSpoolman: () =>
  4567. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  4568. method: 'POST',
  4569. }),
  4570. syncPrinterAms: (printerId: number) =>
  4571. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  4572. method: 'POST',
  4573. }),
  4574. syncAllPrintersAms: () =>
  4575. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  4576. method: 'POST',
  4577. }),
  4578. getSpoolmanSpools: () =>
  4579. request<{ spools: unknown[] }>('/spoolman/spools'),
  4580. /** @deprecated Use getSpoolmanInventoryFilaments() — this endpoint has no SSRF guard */
  4581. getSpoolmanFilaments: () =>
  4582. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  4583. getSpoolmanInventoryFilaments: () =>
  4584. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  4585. patchSpoolmanFilament: (
  4586. filamentId: number,
  4587. data: { name?: string; spool_weight?: number | null; keep_existing_spools?: boolean },
  4588. ) =>
  4589. request<SpoolmanFilamentEntry>(`/spoolman/inventory/filaments/${filamentId}`, {
  4590. method: 'PATCH',
  4591. body: JSON.stringify(data),
  4592. }),
  4593. getUnlinkedSpools: () =>
  4594. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  4595. getLinkedSpools: () =>
  4596. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  4597. linkSpool: (
  4598. spoolId: number,
  4599. context: {
  4600. spoolTag: string;
  4601. printerId: number;
  4602. amsId: number;
  4603. trayId: number;
  4604. }
  4605. ) =>
  4606. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  4607. method: 'POST',
  4608. body: JSON.stringify({
  4609. spool_tag: context.spoolTag,
  4610. printer_id: context.printerId,
  4611. ams_id: context.amsId,
  4612. tray_id: context.trayId,
  4613. }),
  4614. }),
  4615. unlinkSpool: (spoolId: number) =>
  4616. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  4617. method: 'POST',
  4618. }),
  4619. getSpoolmanSettings: () =>
  4620. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman'),
  4621. updateSpoolmanSettings: (data: { spoolman_enabled?: string; spoolman_url?: string; spoolman_sync_mode?: string; spoolman_disable_weight_sync?: string; spoolman_report_partial_usage?: string; }) =>
  4622. request<{ spoolman_enabled: string; spoolman_url: string; spoolman_sync_mode: string; spoolman_disable_weight_sync: string; spoolman_report_partial_usage: string; }>('/settings/spoolman', {
  4623. method: 'PUT',
  4624. body: JSON.stringify(data),
  4625. }),
  4626. // Inventory
  4627. getSpools: (includeArchived = false) =>
  4628. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  4629. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  4630. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4631. request<InventorySpool>('/inventory/spools', {
  4632. method: 'POST',
  4633. body: JSON.stringify(data),
  4634. }),
  4635. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  4636. request<InventorySpool[]>('/inventory/spools/bulk', {
  4637. method: 'POST',
  4638. body: JSON.stringify({ spool: data, quantity }),
  4639. }),
  4640. // ── CSV import/export (#1576) ────────────────────────────────────────────
  4641. // dry_run=true → preview (no write); omitted → real import. Both share one
  4642. // multipart upload helper; see `uploadSpoolsCsv` below.
  4643. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  4644. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  4645. exportSpoolsCsv: async (): Promise<void> => {
  4646. const headers: Record<string, string> = {};
  4647. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4648. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  4649. if (!response.ok) {
  4650. const error = await response.json().catch(() => ({}));
  4651. throw new Error(error.detail || `HTTP ${response.status}`);
  4652. }
  4653. const disposition = response.headers.get('Content-Disposition');
  4654. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  4655. const blob = await response.blob();
  4656. const url = window.URL.createObjectURL(blob);
  4657. const a = document.createElement('a');
  4658. a.href = url;
  4659. a.download = filename;
  4660. document.body.appendChild(a);
  4661. a.click();
  4662. document.body.removeChild(a);
  4663. window.URL.revokeObjectURL(url);
  4664. },
  4665. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  4666. request<InventorySpool>(`/inventory/spools/${id}`, {
  4667. method: 'PATCH',
  4668. body: JSON.stringify(data),
  4669. }),
  4670. deleteSpool: (id: number) =>
  4671. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  4672. archiveSpool: (id: number) =>
  4673. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  4674. restoreSpool: (id: number) =>
  4675. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  4676. resetSpoolConsumedCounter: (id: number) =>
  4677. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  4678. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  4679. request<{ reset: number }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  4680. method: 'POST',
  4681. body: JSON.stringify({ spool_ids: spoolIds }),
  4682. }),
  4683. getSpoolKProfiles: (spoolId: number) =>
  4684. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  4685. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4686. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  4687. method: 'PUT',
  4688. body: JSON.stringify(profiles),
  4689. }),
  4690. getAssignments: (printerId?: number) =>
  4691. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  4692. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4693. request<SpoolAssignment>('/inventory/assignments', {
  4694. method: 'POST',
  4695. body: JSON.stringify(data),
  4696. }),
  4697. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  4698. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  4699. // ── Spool label printing (#809) ──────────────────────────────────────────
  4700. // Both endpoints return application/pdf. Frontend opens the resulting Blob
  4701. // in a new tab so the user can print or save from the browser's PDF viewer.
  4702. printSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate }): Promise<Blob> => {
  4703. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4704. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4705. const response = await fetch(`${API_BASE}/inventory/labels`, {
  4706. method: 'POST',
  4707. headers,
  4708. body: JSON.stringify(data),
  4709. });
  4710. if (!response.ok) {
  4711. const error = await response.json().catch(() => ({}));
  4712. throw new Error(error.detail || `HTTP ${response.status}`);
  4713. }
  4714. return response.blob();
  4715. },
  4716. printSpoolmanSpoolLabels: async (data: { spool_ids: number[]; template: SpoolLabelTemplate }): Promise<Blob> => {
  4717. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  4718. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  4719. const response = await fetch(`${API_BASE}/spoolman/labels`, {
  4720. method: 'POST',
  4721. headers,
  4722. body: JSON.stringify(data),
  4723. });
  4724. if (!response.ok) {
  4725. const error = await response.json().catch(() => ({}));
  4726. throw new Error(error.detail || `HTTP ${response.status}`);
  4727. }
  4728. return response.blob();
  4729. },
  4730. getSpoolCatalog: () =>
  4731. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  4732. addCatalogEntry: (data: { name: string; weight: number }) =>
  4733. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  4734. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  4735. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4736. deleteCatalogEntry: (id: number) =>
  4737. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  4738. bulkDeleteCatalogEntries: (ids: number[]) =>
  4739. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4740. resetSpoolCatalog: () =>
  4741. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  4742. getColorCatalog: () =>
  4743. request<ColorCatalogEntry[]>('/inventory/colors'),
  4744. getColorNameMap: () =>
  4745. request<{ colors: Record<string, string> }>('/inventory/colors/map'),
  4746. addColorEntry: (data: {
  4747. manufacturer: string;
  4748. color_name: string;
  4749. hex_color: string;
  4750. material: string | null;
  4751. extra_colors?: string | null;
  4752. effect_type?: string | null;
  4753. }) =>
  4754. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  4755. updateColorEntry: (
  4756. id: number,
  4757. data: {
  4758. manufacturer: string;
  4759. color_name: string;
  4760. hex_color: string;
  4761. material: string | null;
  4762. extra_colors?: string | null;
  4763. effect_type?: string | null;
  4764. },
  4765. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  4766. deleteColorEntry: (id: number) =>
  4767. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  4768. bulkDeleteColorEntries: (ids: number[]) =>
  4769. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  4770. resetColorCatalog: () =>
  4771. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  4772. lookupColor: (manufacturer: string, colorName: string, material?: string) =>
  4773. request<ColorLookupResult>(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(manufacturer)}&color_name=${encodeURIComponent(colorName)}${material ? `&material=${encodeURIComponent(material)}` : ''}`),
  4774. searchColors: (manufacturer?: string, material?: string) =>
  4775. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  4776. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  4777. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  4778. method: 'PATCH',
  4779. body: JSON.stringify(data),
  4780. }),
  4781. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  4782. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  4783. getAllUsageHistory: (limit = 100, printerId?: number) =>
  4784. request<SpoolUsageRecord[]>(`/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}`),
  4785. clearSpoolUsageHistory: (spoolId: number) =>
  4786. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  4787. syncWeightsFromAms: () =>
  4788. request<{ synced: number; skipped: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  4789. getSkuSettings: () =>
  4790. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  4791. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  4792. request<FilamentSkuSettings>('/inventory/sku-settings', {
  4793. method: 'POST',
  4794. body: JSON.stringify(data),
  4795. }),
  4796. getShoppingList: () =>
  4797. request<ShoppingListItem[]>('/inventory/shopping-list'),
  4798. addToShoppingList: (data: ShoppingListItemCreate) =>
  4799. request<ShoppingListItem>('/inventory/shopping-list', {
  4800. method: 'POST',
  4801. body: JSON.stringify(data),
  4802. }),
  4803. removeFromShoppingList: (id: number) =>
  4804. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  4805. clearShoppingList: () =>
  4806. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  4807. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  4808. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  4809. method: 'PATCH',
  4810. body: JSON.stringify({ status }),
  4811. }),
  4812. getFilamentPresets: () =>
  4813. request<SlicerSetting[]>('/cloud/filaments'),
  4814. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  4815. getSpoolmanInventorySpools: (includeArchived = false) =>
  4816. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  4817. getSpoolmanInventorySpool: (id: number) =>
  4818. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  4819. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  4820. request<InventorySpool>('/spoolman/inventory/spools', {
  4821. method: 'POST',
  4822. body: JSON.stringify(data),
  4823. }),
  4824. bulkCreateSpoolmanInventorySpools: (
  4825. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  4826. quantity: number,
  4827. ) =>
  4828. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  4829. method: 'POST',
  4830. body: JSON.stringify({ spool: data, quantity }),
  4831. }),
  4832. updateSpoolmanInventorySpool: (
  4833. id: number,
  4834. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  4835. ) =>
  4836. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  4837. method: 'PATCH',
  4838. body: JSON.stringify(data),
  4839. }),
  4840. deleteSpoolmanInventorySpool: (id: number) =>
  4841. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  4842. archiveSpoolmanInventorySpool: (id: number) =>
  4843. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  4844. restoreSpoolmanInventorySpool: (id: number) =>
  4845. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  4846. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  4847. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  4848. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  4849. request<{ reset: number }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  4850. method: 'POST',
  4851. body: JSON.stringify({ spool_ids: spoolIds }),
  4852. }),
  4853. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  4854. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  4855. method: 'PATCH',
  4856. body: JSON.stringify(data),
  4857. }),
  4858. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  4859. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  4860. method: 'PATCH',
  4861. body: JSON.stringify({ weight_grams: weightGrams }),
  4862. }),
  4863. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number }) =>
  4864. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  4865. method: 'POST',
  4866. body: JSON.stringify(data),
  4867. }),
  4868. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  4869. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  4870. getSpoolmanSlotAssignment: (printerId: number, amsId: number, trayId: number) =>
  4871. request<InventorySpool | null>(
  4872. `/spoolman/inventory/slot-assignments?printer_id=${printerId}&ams_id=${amsId}&tray_id=${trayId}`,
  4873. ),
  4874. getSpoolmanSlotAssignments: (printerId?: number) =>
  4875. request<Array<{
  4876. printer_id: number;
  4877. printer_name: string | null;
  4878. ams_id: number;
  4879. tray_id: number;
  4880. spoolman_spool_id: number;
  4881. ams_label: string | null;
  4882. }>>(
  4883. printerId !== undefined
  4884. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  4885. : '/spoolman/inventory/slot-assignments/all',
  4886. ),
  4887. syncSpoolmanAmsWeights: () =>
  4888. request<{ synced: number; skipped: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  4889. getSpoolmanKProfiles: (spoolId: number) =>
  4890. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`),
  4891. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  4892. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  4893. method: 'PUT',
  4894. body: JSON.stringify(profiles),
  4895. }),
  4896. // Updates
  4897. getVersion: () => request<VersionInfo>('/updates/version'),
  4898. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  4899. applyUpdate: () =>
  4900. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean }>('/updates/apply', {
  4901. method: 'POST',
  4902. }),
  4903. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  4904. // Maintenance
  4905. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  4906. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  4907. request<MaintenanceType>('/maintenance/types', {
  4908. method: 'POST',
  4909. body: JSON.stringify(data),
  4910. }),
  4911. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  4912. request<MaintenanceType>(`/maintenance/types/${id}`, {
  4913. method: 'PATCH',
  4914. body: JSON.stringify(data),
  4915. }),
  4916. deleteMaintenanceType: (id: number) =>
  4917. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  4918. restoreDefaultMaintenanceTypes: () =>
  4919. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  4920. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  4921. getPrinterMaintenance: (printerId: number) =>
  4922. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  4923. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  4924. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  4925. method: 'PATCH',
  4926. body: JSON.stringify(data),
  4927. }),
  4928. performMaintenance: (itemId: number, notes?: string) =>
  4929. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  4930. method: 'POST',
  4931. body: JSON.stringify({ notes }),
  4932. }),
  4933. getMaintenanceHistory: (itemId: number) =>
  4934. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  4935. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  4936. setPrinterHours: (printerId: number, totalHours: number) =>
  4937. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  4938. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  4939. { method: 'PATCH' }
  4940. ),
  4941. assignMaintenanceType: (printerId: number, typeId: number) =>
  4942. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  4943. method: 'POST',
  4944. }),
  4945. removeMaintenanceItem: (itemId: number) =>
  4946. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  4947. method: 'DELETE',
  4948. }),
  4949. // Camera
  4950. getCameraStreamToken: () =>
  4951. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  4952. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  4953. // the /ws connection. Browsers can't attach Authorization headers to a
  4954. // WebSocket handshake, so the token rides in the ?token= query param.
  4955. getWebSocketToken: () =>
  4956. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  4957. // Long-lived camera-stream tokens (#1108)
  4958. createLongLivedCameraToken: (payload: { name: string; expires_in_days: number }) =>
  4959. request<LongLivedCameraToken>('/auth/tokens', {
  4960. method: 'POST',
  4961. body: JSON.stringify({ ...payload, scope: 'camera_stream' }),
  4962. }),
  4963. listMyLongLivedCameraTokens: () =>
  4964. request<LongLivedCameraToken[]>('/auth/tokens'),
  4965. listAllLongLivedCameraTokens: () =>
  4966. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  4967. listLongLivedCameraTokensForUser: (userId: number) =>
  4968. request<LongLivedCameraToken[]>(`/auth/tokens?user_id=${userId}`),
  4969. revokeLongLivedCameraToken: (tokenId: number) =>
  4970. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  4971. getCameraStreamUrl: (printerId: number, fps = 10) =>
  4972. withStreamToken(`${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`),
  4973. getCameraSnapshotUrl: (printerId: number) =>
  4974. withStreamToken(`${API_BASE}/printers/${printerId}/camera/snapshot`),
  4975. testCameraConnection: (printerId: number) =>
  4976. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  4977. getCameraStatus: (printerId: number) =>
  4978. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  4979. diagnoseCamera: (printerId: number) =>
  4980. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  4981. diagnosePrinter: (printerId: number) =>
  4982. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  4983. diagnoseConnection: (body: {
  4984. ip_address: string;
  4985. serial_number?: string;
  4986. access_code?: string;
  4987. }) =>
  4988. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  4989. method: 'POST',
  4990. body: JSON.stringify(body),
  4991. }),
  4992. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  4993. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  4994. const params = new URLSearchParams();
  4995. // Only forward use_external when the caller explicitly sets it. Omitted →
  4996. // backend derives the default from the printer's external_camera_enabled
  4997. // setting so calibration and runtime checks use the same camera (#1359).
  4998. if (options?.useExternal !== undefined) {
  4999. params.set('use_external', String(options.useExternal));
  5000. }
  5001. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  5002. return request<PlateDetectionResult>(
  5003. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  5004. );
  5005. },
  5006. getPlateDetectionStatus: (printerId: number) => {
  5007. return request<PlateDetectionStatus & { chamber_light?: boolean }>(
  5008. `/printers/${printerId}/camera/plate-detection/status`
  5009. );
  5010. },
  5011. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  5012. const params = new URLSearchParams();
  5013. if (options?.label) params.set('label', options.label);
  5014. if (options?.useExternal !== undefined) {
  5015. params.set('use_external', String(options.useExternal));
  5016. }
  5017. return request<CalibrationResult & { index: number }>(
  5018. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  5019. { method: 'POST' }
  5020. );
  5021. },
  5022. deletePlateCalibration: (printerId: number) => {
  5023. return request<CalibrationResult>(
  5024. `/printers/${printerId}/camera/plate-detection/calibrate`,
  5025. { method: 'DELETE' }
  5026. );
  5027. },
  5028. getPlateReferences: (printerId: number) => {
  5029. return request<{
  5030. references: PlateReference[];
  5031. max_references: number;
  5032. }>(`/printers/${printerId}/camera/plate-detection/references`);
  5033. },
  5034. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  5035. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  5036. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  5037. const params = new URLSearchParams();
  5038. params.set('label', label);
  5039. return request<{ success: boolean; index: number; label: string }>(
  5040. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  5041. { method: 'PUT' }
  5042. );
  5043. },
  5044. deletePlateReference: (printerId: number, index: number) => {
  5045. return request<{ success: boolean; message: string }>(
  5046. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  5047. { method: 'DELETE' }
  5048. );
  5049. },
  5050. // External Links
  5051. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  5052. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  5053. createExternalLink: (data: ExternalLinkCreate) =>
  5054. request<ExternalLink>('/external-links/', {
  5055. method: 'POST',
  5056. body: JSON.stringify(data),
  5057. }),
  5058. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  5059. request<ExternalLink>(`/external-links/${id}`, {
  5060. method: 'PATCH',
  5061. body: JSON.stringify(data),
  5062. }),
  5063. deleteExternalLink: (id: number) =>
  5064. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  5065. reorderExternalLinks: (ids: number[]) =>
  5066. request<ExternalLink[]>('/external-links/reorder', {
  5067. method: 'PUT',
  5068. body: JSON.stringify({ ids }),
  5069. }),
  5070. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  5071. const formData = new FormData();
  5072. formData.append('file', file);
  5073. const headers: Record<string, string> = {};
  5074. if (authToken) {
  5075. headers['Authorization'] = `Bearer ${authToken}`;
  5076. }
  5077. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  5078. method: 'POST',
  5079. headers,
  5080. body: formData,
  5081. });
  5082. if (!response.ok) {
  5083. const error = await response.json().catch(() => ({}));
  5084. throw new Error(error.detail || `HTTP ${response.status}`);
  5085. }
  5086. return response.json();
  5087. },
  5088. deleteExternalLinkIcon: (id: number) =>
  5089. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  5090. getExternalLinkIconUrl: (id: number) => withStreamToken(`${API_BASE}/external-links/${id}/icon`),
  5091. // Projects
  5092. getProjects: (status?: string) => {
  5093. const params = new URLSearchParams();
  5094. if (status) params.set('status', status);
  5095. return request<ProjectListItem[]>(`/projects/?${params}`);
  5096. },
  5097. getProject: (id: number) => request<Project>(`/projects/${id}`),
  5098. createProject: (data: ProjectCreate) =>
  5099. request<Project>('/projects/', {
  5100. method: 'POST',
  5101. body: JSON.stringify(data),
  5102. }),
  5103. updateProject: (id: number, data: ProjectUpdate) =>
  5104. request<Project>(`/projects/${id}`, {
  5105. method: 'PATCH',
  5106. body: JSON.stringify(data),
  5107. }),
  5108. deleteProject: (id: number) =>
  5109. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  5110. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  5111. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  5112. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  5113. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  5114. method: 'POST',
  5115. body: JSON.stringify({ archive_ids: archiveIds }),
  5116. }),
  5117. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  5118. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  5119. method: 'POST',
  5120. body: JSON.stringify({ archive_ids: archiveIds }),
  5121. }),
  5122. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  5123. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  5124. method: 'POST',
  5125. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  5126. }),
  5127. // Project Attachments
  5128. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  5129. status: string;
  5130. filename: string;
  5131. original_name: string;
  5132. attachments: ProjectAttachment[];
  5133. }> => {
  5134. const formData = new FormData();
  5135. formData.append('file', file);
  5136. const headers: Record<string, string> = {};
  5137. if (authToken) {
  5138. headers['Authorization'] = `Bearer ${authToken}`;
  5139. }
  5140. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  5141. method: 'POST',
  5142. headers,
  5143. body: formData,
  5144. });
  5145. if (!response.ok) {
  5146. const error = await response.json().catch(() => ({}));
  5147. throw new Error(error.detail || `HTTP ${response.status}`);
  5148. }
  5149. return response.json();
  5150. },
  5151. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  5152. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  5153. deleteProjectAttachment: (projectId: number, filename: string) =>
  5154. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  5155. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  5156. { method: 'DELETE' }
  5157. ),
  5158. // #1155: Cover image
  5159. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  5160. // append the stream-token query string the same way archive thumbnails do.
  5161. getProjectCoverImageUrl: (projectId: number) =>
  5162. withStreamToken(`${API_BASE}/projects/${projectId}/cover-image`),
  5163. uploadProjectCoverImage: async (
  5164. projectId: number,
  5165. file: File
  5166. ): Promise<{ status: string; filename: string; size: number }> => {
  5167. const formData = new FormData();
  5168. formData.append('file', file);
  5169. const headers: Record<string, string> = {};
  5170. if (authToken) {
  5171. headers['Authorization'] = `Bearer ${authToken}`;
  5172. }
  5173. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  5174. method: 'POST',
  5175. headers,
  5176. body: formData,
  5177. });
  5178. if (!response.ok) {
  5179. const error = await response.json().catch(() => ({}));
  5180. throw new Error(error.detail || `HTTP ${response.status}`);
  5181. }
  5182. return response.json();
  5183. },
  5184. deleteProjectCoverImage: (projectId: number) =>
  5185. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  5186. // BOM (Bill of Materials)
  5187. getProjectBOM: (projectId: number) =>
  5188. request<BOMItem[]>(`/projects/${projectId}/bom`),
  5189. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  5190. request<BOMItem>(`/projects/${projectId}/bom`, {
  5191. method: 'POST',
  5192. body: JSON.stringify(data),
  5193. }),
  5194. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  5195. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  5196. method: 'PATCH',
  5197. body: JSON.stringify(data),
  5198. }),
  5199. deleteBOMItem: (projectId: number, itemId: number) =>
  5200. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  5201. method: 'DELETE',
  5202. }),
  5203. // Templates
  5204. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  5205. createTemplateFromProject: (projectId: number) =>
  5206. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  5207. createProjectFromTemplate: (templateId: number, name?: string) =>
  5208. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  5209. method: 'POST',
  5210. }),
  5211. // Timeline
  5212. getProjectTimeline: (projectId: number, limit = 50) =>
  5213. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  5214. // Project Export/Import
  5215. exportProjectJson: (projectId: number) =>
  5216. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  5217. importProject: (data: ProjectImport) =>
  5218. request<Project>('/projects/import', {
  5219. method: 'POST',
  5220. body: JSON.stringify(data),
  5221. }),
  5222. importProjectFile: async (file: File): Promise<Project> => {
  5223. const formData = new FormData();
  5224. formData.append('file', file);
  5225. const headers: Record<string, string> = {};
  5226. if (authToken) {
  5227. headers['Authorization'] = `Bearer ${authToken}`;
  5228. }
  5229. const response = await fetch(`${API_BASE}/projects/import/file`, {
  5230. method: 'POST',
  5231. headers,
  5232. body: formData,
  5233. });
  5234. if (!response.ok) {
  5235. const error = await response.json().catch(() => ({}));
  5236. throw new Error(error.detail || `HTTP ${response.status}`);
  5237. }
  5238. return response.json();
  5239. },
  5240. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  5241. const headers: Record<string, string> = {};
  5242. if (authToken) {
  5243. headers['Authorization'] = `Bearer ${authToken}`;
  5244. }
  5245. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  5246. headers,
  5247. });
  5248. if (!response.ok) {
  5249. const error = await response.json().catch(() => ({}));
  5250. throw new Error(error.detail || `HTTP ${response.status}`);
  5251. }
  5252. const contentDisposition = response.headers.get('Content-Disposition');
  5253. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  5254. const blob = await response.blob();
  5255. return { blob, filename };
  5256. },
  5257. // API Keys
  5258. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  5259. createAPIKey: (data: APIKeyCreate) =>
  5260. request<APIKeyCreateResponse>('/api-keys/', {
  5261. method: 'POST',
  5262. body: JSON.stringify(data),
  5263. }),
  5264. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  5265. request<APIKey>(`/api-keys/${id}`, {
  5266. method: 'PATCH',
  5267. body: JSON.stringify(data),
  5268. }),
  5269. deleteAPIKey: (id: number) =>
  5270. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  5271. // AMS History
  5272. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  5273. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  5274. // System Info
  5275. getSystemInfo: () => request<SystemInfo>('/system/info'),
  5276. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  5277. getStorageUsage: (options?: { refresh?: boolean }) => {
  5278. const params = new URLSearchParams();
  5279. if (options?.refresh) {
  5280. params.set('refresh', 'true');
  5281. }
  5282. const query = params.toString();
  5283. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  5284. },
  5285. // Library (File Manager)
  5286. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  5287. createLibraryFolder: (data: LibraryFolderCreate) =>
  5288. request<LibraryFolder>('/library/folders', {
  5289. method: 'POST',
  5290. body: JSON.stringify(data),
  5291. }),
  5292. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  5293. request<LibraryFolder>(`/library/folders/${id}`, {
  5294. method: 'PUT',
  5295. body: JSON.stringify(data),
  5296. }),
  5297. deleteLibraryFolder: (id: number) =>
  5298. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  5299. createExternalFolder: (data: ExternalFolderCreate) =>
  5300. request<LibraryFolder>('/library/folders/external', {
  5301. method: 'POST',
  5302. body: JSON.stringify(data),
  5303. }),
  5304. scanExternalFolder: (folderId: number) =>
  5305. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  5306. method: 'POST',
  5307. }),
  5308. getLibraryFoldersByProject: (projectId: number) =>
  5309. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  5310. getLibraryFoldersByArchive: (archiveId: number) =>
  5311. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  5312. getLibraryFiles: (
  5313. folderId?: number | null,
  5314. includeRoot = true,
  5315. projectId?: number,
  5316. scope?: 'internal' | 'external',
  5317. ) => {
  5318. const params = new URLSearchParams();
  5319. if (folderId !== undefined && folderId !== null) {
  5320. params.set('folder_id', String(folderId));
  5321. }
  5322. if (projectId !== undefined) {
  5323. params.set('project_id', String(projectId));
  5324. }
  5325. params.set('include_root', String(includeRoot));
  5326. if (scope === 'internal') params.set('internal_only', 'true');
  5327. else if (scope === 'external') params.set('external_only', 'true');
  5328. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  5329. },
  5330. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  5331. uploadLibraryFile: async (
  5332. file: File,
  5333. folderId?: number | null,
  5334. generateStlThumbnails: boolean = true
  5335. ): Promise<LibraryFileUploadResponse> => {
  5336. const formData = new FormData();
  5337. formData.append('file', file);
  5338. const params = new URLSearchParams();
  5339. if (folderId) params.set('folder_id', String(folderId));
  5340. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5341. const headers: Record<string, string> = {};
  5342. if (authToken) {
  5343. headers['Authorization'] = `Bearer ${authToken}`;
  5344. }
  5345. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  5346. method: 'POST',
  5347. headers,
  5348. body: formData,
  5349. });
  5350. if (!response.ok) {
  5351. const error = await response.json().catch(() => ({}));
  5352. throw new Error(error.detail || `HTTP ${response.status}`);
  5353. }
  5354. return response.json();
  5355. },
  5356. extractZipFile: async (
  5357. file: File,
  5358. folderId?: number | null,
  5359. preserveStructure: boolean = true,
  5360. createFolderFromZip: boolean = false,
  5361. generateStlThumbnails: boolean = true
  5362. ): Promise<ZipExtractResponse> => {
  5363. const formData = new FormData();
  5364. formData.append('file', file);
  5365. const params = new URLSearchParams();
  5366. if (folderId) params.set('folder_id', String(folderId));
  5367. params.set('preserve_structure', String(preserveStructure));
  5368. params.set('create_folder_from_zip', String(createFolderFromZip));
  5369. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  5370. const headers: Record<string, string> = {};
  5371. if (authToken) {
  5372. headers['Authorization'] = `Bearer ${authToken}`;
  5373. }
  5374. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  5375. method: 'POST',
  5376. headers,
  5377. body: formData,
  5378. });
  5379. if (!response.ok) {
  5380. const error = await response.json().catch(() => ({}));
  5381. throw new Error(error.detail || `HTTP ${response.status}`);
  5382. }
  5383. return response.json();
  5384. },
  5385. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  5386. request<LibraryFile>(`/library/files/${id}`, {
  5387. method: 'PUT',
  5388. body: JSON.stringify(data),
  5389. }),
  5390. deleteLibraryFile: (id: number) =>
  5391. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  5392. // ========== Library Trash (#1008) ==========
  5393. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5394. request<LibraryPurgePreview>(
  5395. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  5396. ),
  5397. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  5398. request<{ moved_to_trash: number }>('/library/purge', {
  5399. method: 'POST',
  5400. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  5401. }),
  5402. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  5403. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  5404. restoreLibraryTrash: (fileId: number) =>
  5405. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  5406. hardDeleteLibraryTrash: (fileId: number) =>
  5407. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  5408. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  5409. getLibraryTrashSettings: () =>
  5410. request<LibraryTrashSettings>('/library/trash/settings'),
  5411. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  5412. request<LibraryTrashSettings>('/library/trash/settings', {
  5413. method: 'PUT',
  5414. body: JSON.stringify(body),
  5415. }),
  5416. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  5417. createLibrarySlicerToken: (fileId: number) =>
  5418. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  5419. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  5420. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  5421. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  5422. const headers: Record<string, string> = {};
  5423. if (authToken) {
  5424. headers['Authorization'] = `Bearer ${authToken}`;
  5425. }
  5426. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  5427. if (!response.ok) {
  5428. const error = await response.json().catch(() => ({}));
  5429. throw new Error(error.detail || `HTTP ${response.status}`);
  5430. }
  5431. const disposition = response.headers.get('Content-Disposition');
  5432. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  5433. const blob = await response.blob();
  5434. const url = window.URL.createObjectURL(blob);
  5435. const a = document.createElement('a');
  5436. a.href = url;
  5437. a.download = downloadFilename;
  5438. document.body.appendChild(a);
  5439. a.click();
  5440. document.body.removeChild(a);
  5441. window.URL.revokeObjectURL(url);
  5442. },
  5443. getLibraryFileThumbnailUrl: (id: number) => withStreamToken(`${API_BASE}/library/files/${id}/thumbnail`),
  5444. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  5445. withStreamToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  5446. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  5447. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  5448. request<{ status: string; moved: number }>('/library/files/move', {
  5449. method: 'POST',
  5450. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  5451. }),
  5452. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  5453. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  5454. method: 'POST',
  5455. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  5456. }),
  5457. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  5458. batchGenerateStlThumbnails: (options: {
  5459. file_ids?: number[];
  5460. folder_id?: number;
  5461. all_missing?: boolean;
  5462. }) =>
  5463. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  5464. method: 'POST',
  5465. body: JSON.stringify(options),
  5466. }),
  5467. addLibraryFilesToQueue: (fileIds: number[]) =>
  5468. request<AddToQueueResponse>('/library/files/add-to-queue', {
  5469. method: 'POST',
  5470. body: JSON.stringify({ file_ids: fileIds }),
  5471. }),
  5472. printLibraryFile: (
  5473. fileId: number,
  5474. printerId: number,
  5475. options?: {
  5476. plate_id?: number;
  5477. plate_name?: string;
  5478. ams_mapping?: number[];
  5479. bed_levelling?: boolean;
  5480. flow_cali?: boolean;
  5481. vibration_cali?: boolean;
  5482. layer_inspect?: boolean;
  5483. timelapse?: boolean;
  5484. use_ams?: boolean;
  5485. nozzle_offset_cali?: boolean;
  5486. project_id?: number;
  5487. cleanup_library_after_dispatch?: boolean;
  5488. }
  5489. ) =>
  5490. request<BackgroundDispatchResponse>(
  5491. `/library/files/${fileId}/print?printer_id=${printerId}`,
  5492. {
  5493. method: 'POST',
  5494. body: options ? JSON.stringify(options) : undefined,
  5495. }
  5496. ),
  5497. cancelBackgroundDispatchJob: (jobId: number) =>
  5498. request<{
  5499. status: 'cancelled' | 'cancelling';
  5500. job_id: number;
  5501. source_name: string;
  5502. printer_id: number;
  5503. printer_name: string;
  5504. }>(`/background-dispatch/${jobId}`, {
  5505. method: 'DELETE',
  5506. }),
  5507. getLibraryFilePlates: (fileId: number) =>
  5508. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  5509. getLibraryFileFilamentRequirements: (
  5510. fileId: number,
  5511. plateId?: number,
  5512. requestId?: string,
  5513. ) => {
  5514. const qs = new URLSearchParams();
  5515. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  5516. if (requestId) qs.set('request_id', requestId);
  5517. return request<{
  5518. file_id: number;
  5519. filename: string;
  5520. filaments: Array<{
  5521. slot_id: number;
  5522. type: string;
  5523. color: string;
  5524. used_grams: number;
  5525. used_meters: number;
  5526. used_in_plate?: boolean;
  5527. }>;
  5528. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  5529. },
  5530. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  5531. * proxy. Used by the SliceModal's filament-discovery path so the inline
  5532. * spinner + persistent toast can show "Generating G-code (45%)" while
  5533. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  5534. * have an entry — early race window — or it expired) so the poller
  5535. * can keep trying. */
  5536. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  5537. try {
  5538. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  5539. } catch {
  5540. return null;
  5541. }
  5542. },
  5543. // GitHub Backup
  5544. getGitHubBackupConfig: () =>
  5545. request<GitHubBackupConfig | null>('/github-backup/config'),
  5546. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  5547. request<GitHubBackupConfig>('/github-backup/config', {
  5548. method: 'POST',
  5549. body: JSON.stringify(config),
  5550. }),
  5551. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  5552. request<GitHubBackupConfig>('/github-backup/config', {
  5553. method: 'PATCH',
  5554. body: JSON.stringify(config),
  5555. }),
  5556. deleteGitHubBackupConfig: () =>
  5557. request<{ message: string }>('/github-backup/config', { method: 'DELETE' }),
  5558. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  5559. request<GitHubTestConnectionResponse>(
  5560. `/github-backup/test?repo_url=${encodeURIComponent(repoUrl)}&token=${encodeURIComponent(token)}&provider=${encodeURIComponent(provider)}`,
  5561. { method: 'POST' }
  5562. ),
  5563. testGitHubStoredConnection: () =>
  5564. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  5565. triggerGitHubBackup: () =>
  5566. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  5567. getGitHubBackupStatus: () =>
  5568. request<GitHubBackupStatus>('/github-backup/status'),
  5569. getGitHubBackupLogs: (limit: number = 50) =>
  5570. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  5571. clearGitHubBackupLogs: (keepLast: number = 10) =>
  5572. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  5573. // Scheduled local backups
  5574. getLocalBackupStatus: () =>
  5575. request<LocalBackupStatus>('/local-backup/status'),
  5576. triggerLocalBackup: () =>
  5577. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  5578. getLocalBackups: () =>
  5579. request<LocalBackupFile[]>('/local-backup/backups'),
  5580. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  5581. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  5582. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5583. });
  5584. if (!response.ok) throw new Error('Download failed');
  5585. const blob = await response.blob();
  5586. return { blob, filename };
  5587. },
  5588. restoreLocalBackup: (filename: string) =>
  5589. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  5590. deleteLocalBackup: (filename: string) =>
  5591. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  5592. // Obico AI failure detection
  5593. getObicoStatus: () =>
  5594. request<ObicoStatus>('/obico/status'),
  5595. testObicoConnection: (url: string) =>
  5596. request<ObicoTestConnection>('/obico/test-connection', {
  5597. method: 'POST',
  5598. body: JSON.stringify({ url }),
  5599. }),
  5600. // Slicer API — slice in the background. Both endpoints return 202 + a
  5601. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  5602. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  5603. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  5604. method: 'POST',
  5605. body: JSON.stringify(body),
  5606. }),
  5607. sliceArchive: (archiveId: number, body: SliceRequest) =>
  5608. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  5609. method: 'POST',
  5610. body: JSON.stringify(body),
  5611. }),
  5612. getSliceJob: (jobId: number) =>
  5613. request<SliceJobState>(`/slice-jobs/${jobId}`),
  5614. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  5615. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  5616. // backend/app/api/routes/slicer_presets.py for the priority rules.
  5617. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  5618. // backend; the SliceModal's Refresh button passes true so a preset deleted
  5619. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  5620. getSlicerPresets: (options?: { refresh?: boolean }) =>
  5621. request<UnifiedPresetsResponse>(
  5622. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  5623. ),
  5624. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  5625. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  5626. // SliceModal uses this to classify cloud / standard presets by their
  5627. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  5628. getSlicerPrinterModels: () =>
  5629. request<Record<string, string>>('/slicer/printer-models'),
  5630. // Local Presets (OrcaSlicer imports)
  5631. getLocalPresets: () =>
  5632. request<LocalPresetsResponse>('/local-presets/'),
  5633. getLocalPresetDetail: (id: number) =>
  5634. request<LocalPresetDetail>(`/local-presets/${id}`),
  5635. importLocalPresets: (formData: FormData) =>
  5636. fetch(`${API_BASE}/local-presets/import`, {
  5637. method: 'POST',
  5638. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  5639. body: formData,
  5640. }).then(async (res) => {
  5641. if (!res.ok) {
  5642. const err = await res.json().catch(() => ({}));
  5643. throw new Error(err.detail || `HTTP ${res.status}`);
  5644. }
  5645. return res.json() as Promise<ImportResponse>;
  5646. }),
  5647. createLocalPreset: (data: { name: string; preset_type: string; setting: Record<string, unknown> }) =>
  5648. request<LocalPreset>('/local-presets/', {
  5649. method: 'POST',
  5650. body: JSON.stringify(data),
  5651. }),
  5652. updateLocalPreset: (id: number, data: { name?: string; setting?: Record<string, unknown> }) =>
  5653. request<LocalPreset>(`/local-presets/${id}`, {
  5654. method: 'PUT',
  5655. body: JSON.stringify(data),
  5656. }),
  5657. deleteLocalPreset: (id: number) =>
  5658. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  5659. refreshBaseProfileCache: () =>
  5660. request<{ refreshed: number; failed: number; total: number }>('/local-presets/base-cache/refresh', { method: 'POST' }),
  5661. };
  5662. // AMS History types
  5663. export interface AMSHistoryPoint {
  5664. recorded_at: string;
  5665. humidity: number | null;
  5666. humidity_raw: number | null;
  5667. temperature: number | null;
  5668. }
  5669. export interface AMSHistoryResponse {
  5670. printer_id: number;
  5671. ams_id: number;
  5672. data: AMSHistoryPoint[];
  5673. min_humidity: number | null;
  5674. max_humidity: number | null;
  5675. avg_humidity: number | null;
  5676. min_temperature: number | null;
  5677. max_temperature: number | null;
  5678. avg_temperature: number | null;
  5679. }
  5680. // System Info types
  5681. export interface SystemInfo {
  5682. app: {
  5683. version: string;
  5684. base_dir: string;
  5685. archive_dir: string;
  5686. };
  5687. database: {
  5688. engine: string;
  5689. version: string;
  5690. archives: number;
  5691. archives_completed: number;
  5692. archives_failed: number;
  5693. archives_printing: number;
  5694. printers: number;
  5695. filaments: number;
  5696. projects: number;
  5697. smart_plugs: number;
  5698. total_print_time_seconds: number;
  5699. total_print_time_formatted: string;
  5700. total_filament_grams: number;
  5701. total_filament_kg: number;
  5702. };
  5703. printers: {
  5704. total: number;
  5705. connected: number;
  5706. connected_list: Array<{
  5707. id: number;
  5708. name: string;
  5709. state: string;
  5710. model: string;
  5711. }>;
  5712. };
  5713. storage: {
  5714. archive_size_bytes: number;
  5715. archive_size_formatted: string;
  5716. database_size_bytes: number;
  5717. database_size_formatted: string;
  5718. disk_total_bytes: number;
  5719. disk_total_formatted: string;
  5720. disk_used_bytes: number;
  5721. disk_used_formatted: string;
  5722. disk_free_bytes: number;
  5723. disk_free_formatted: string;
  5724. disk_percent_used: number;
  5725. };
  5726. system: {
  5727. platform: string;
  5728. platform_release: string;
  5729. platform_version: string;
  5730. architecture: string;
  5731. hostname: string;
  5732. python_version: string;
  5733. uptime_seconds: number;
  5734. uptime_formatted: string;
  5735. boot_time: string;
  5736. };
  5737. memory: {
  5738. total_bytes: number;
  5739. total_formatted: string;
  5740. available_bytes: number;
  5741. available_formatted: string;
  5742. used_bytes: number;
  5743. used_formatted: string;
  5744. percent_used: number;
  5745. };
  5746. cpu: {
  5747. count: number;
  5748. count_logical: number;
  5749. percent: number;
  5750. };
  5751. }
  5752. export interface StorageUsageCategory {
  5753. key: string;
  5754. label: string;
  5755. bytes: number;
  5756. formatted: string;
  5757. percent_of_total: number;
  5758. }
  5759. export interface StorageUsageOtherItem {
  5760. bucket: string;
  5761. label: string;
  5762. kind: 'system' | 'data';
  5763. deletable: boolean;
  5764. bytes: number;
  5765. formatted: string;
  5766. percent_of_total: number;
  5767. }
  5768. export interface StorageUsageResponse {
  5769. roots: string[];
  5770. total_bytes: number;
  5771. total_formatted: string;
  5772. categories: StorageUsageCategory[];
  5773. other_breakdown: StorageUsageOtherItem[];
  5774. scan_errors: number;
  5775. generated_at: string;
  5776. cache: {
  5777. hit: boolean;
  5778. age_seconds: number;
  5779. max_age_seconds: number;
  5780. };
  5781. }
  5782. // Library (File Manager) types
  5783. export interface LibraryFolderTree {
  5784. id: number;
  5785. name: string;
  5786. parent_id: number | null;
  5787. project_id: number | null;
  5788. archive_id: number | null;
  5789. project_name: string | null;
  5790. archive_name: string | null;
  5791. is_external: boolean;
  5792. external_path: string | null;
  5793. external_readonly: boolean;
  5794. file_count: number;
  5795. children: LibraryFolderTree[];
  5796. }
  5797. export interface LibraryFolder {
  5798. id: number;
  5799. name: string;
  5800. parent_id: number | null;
  5801. project_id: number | null;
  5802. archive_id: number | null;
  5803. project_name: string | null;
  5804. archive_name: string | null;
  5805. is_external: boolean;
  5806. external_path: string | null;
  5807. external_readonly: boolean;
  5808. external_show_hidden: boolean;
  5809. file_count: number;
  5810. created_at: string;
  5811. updated_at: string;
  5812. }
  5813. export interface LibraryFolderCreate {
  5814. name: string;
  5815. parent_id?: number | null;
  5816. project_id?: number | null;
  5817. archive_id?: number | null;
  5818. }
  5819. export interface ExternalFolderCreate {
  5820. name: string;
  5821. external_path: string;
  5822. readonly?: boolean;
  5823. show_hidden?: boolean;
  5824. parent_id?: number | null;
  5825. }
  5826. export interface LibraryFolderUpdate {
  5827. name?: string;
  5828. parent_id?: number | null;
  5829. project_id?: number | null; // 0 to unlink
  5830. archive_id?: number | null; // 0 to unlink
  5831. }
  5832. export interface LibraryFileDuplicate {
  5833. id: number;
  5834. filename: string;
  5835. folder_id: number | null;
  5836. folder_name: string | null;
  5837. created_at: string;
  5838. }
  5839. export interface LibraryFile {
  5840. id: number;
  5841. folder_id: number | null;
  5842. folder_name: string | null;
  5843. project_id: number | null;
  5844. project_name: string | null;
  5845. is_external: boolean;
  5846. filename: string;
  5847. file_path: string;
  5848. file_type: string;
  5849. file_size: number;
  5850. file_hash: string | null;
  5851. thumbnail_path: string | null;
  5852. metadata: Record<string, unknown> | null;
  5853. print_count: number;
  5854. last_printed_at: string | null;
  5855. notes: string | null;
  5856. duplicates: LibraryFileDuplicate[] | null;
  5857. duplicate_count: number;
  5858. // User tracking (Issue #206)
  5859. created_by_id: number | null;
  5860. created_by_username: string | null;
  5861. created_at: string;
  5862. updated_at: string;
  5863. // Metadata fields
  5864. print_name: string | null;
  5865. print_time_seconds: number | null;
  5866. filament_used_grams: number | null;
  5867. sliced_for_model: string | null;
  5868. }
  5869. export interface LibraryFileListItem {
  5870. id: number;
  5871. folder_id: number | null;
  5872. is_external: boolean;
  5873. filename: string;
  5874. file_type: string;
  5875. file_size: number;
  5876. thumbnail_path: string | null;
  5877. print_count: number;
  5878. duplicate_count: number;
  5879. // User tracking (Issue #206)
  5880. created_by_id: number | null;
  5881. created_by_username: string | null;
  5882. created_at: string;
  5883. print_name: string | null;
  5884. print_time_seconds: number | null;
  5885. filament_used_grams: number | null;
  5886. sliced_for_model: string | null;
  5887. }
  5888. export interface LibraryFileUpdate {
  5889. filename?: string;
  5890. folder_id?: number | null;
  5891. project_id?: number | null;
  5892. notes?: string | null;
  5893. }
  5894. // Library trash (#1008)
  5895. export interface LibraryTrashItem {
  5896. id: number;
  5897. filename: string;
  5898. file_size: number;
  5899. thumbnail_path: string | null;
  5900. folder_id: number | null;
  5901. folder_name: string | null;
  5902. created_by_id: number | null;
  5903. created_by_username: string | null;
  5904. deleted_at: string;
  5905. auto_purge_at: string;
  5906. }
  5907. export interface LibraryTrashListResponse {
  5908. items: LibraryTrashItem[];
  5909. total: number;
  5910. retention_days: number;
  5911. }
  5912. export interface LibraryPurgePreview {
  5913. count: number;
  5914. total_bytes: number;
  5915. sample_filenames: string[];
  5916. older_than_days: number;
  5917. include_never_printed: boolean;
  5918. }
  5919. export interface LibraryTrashSettings {
  5920. retention_days: number;
  5921. auto_purge_enabled: boolean;
  5922. auto_purge_days: number;
  5923. auto_purge_include_never_printed: boolean;
  5924. }
  5925. export interface ArchivePurgePreview {
  5926. count: number;
  5927. total_bytes: number;
  5928. sample_filenames: string[];
  5929. older_than_days: number;
  5930. }
  5931. export interface ArchivePurgeSettings {
  5932. enabled: boolean;
  5933. days: number;
  5934. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  5935. // contribution drops from Quick Stats too. Default false — soft-delete,
  5936. // Quick Stats preserved.
  5937. purge_stats: boolean;
  5938. }
  5939. export interface LibraryFileUploadResponse {
  5940. id: number;
  5941. filename: string;
  5942. file_type: string;
  5943. file_size: number;
  5944. thumbnail_path: string | null;
  5945. duplicate_of: number | null;
  5946. metadata: Record<string, unknown> | null;
  5947. }
  5948. export interface LibraryStats {
  5949. total_files: number;
  5950. total_folders: number;
  5951. total_size_bytes: number;
  5952. files_by_type: Record<string, number>;
  5953. total_prints: number;
  5954. disk_free_bytes: number;
  5955. disk_total_bytes: number;
  5956. disk_used_bytes: number;
  5957. }
  5958. export interface ZipExtractResult {
  5959. filename: string;
  5960. file_id: number;
  5961. folder_id: number | null;
  5962. }
  5963. export interface ZipExtractError {
  5964. filename: string;
  5965. error: string;
  5966. }
  5967. export interface ZipExtractResponse {
  5968. extracted: number;
  5969. folders_created: number;
  5970. files: ZipExtractResult[];
  5971. errors: ZipExtractError[];
  5972. }
  5973. // STL Thumbnail Generation types
  5974. export interface BatchThumbnailResult {
  5975. file_id: number;
  5976. filename: string;
  5977. success: boolean;
  5978. error?: string | null;
  5979. }
  5980. export interface BatchThumbnailResponse {
  5981. processed: number;
  5982. succeeded: number;
  5983. failed: number;
  5984. results: BatchThumbnailResult[];
  5985. }
  5986. // Library Queue types
  5987. export interface AddToQueueResult {
  5988. file_id: number;
  5989. filename: string;
  5990. queue_item_id: number;
  5991. archive_id: number;
  5992. }
  5993. export interface AddToQueueError {
  5994. file_id: number;
  5995. filename: string;
  5996. error: string;
  5997. }
  5998. export interface AddToQueueResponse {
  5999. added: AddToQueueResult[];
  6000. errors: AddToQueueError[];
  6001. }
  6002. // Discovery types
  6003. export interface DiscoveredPrinter {
  6004. serial: string;
  6005. name: string;
  6006. ip_address: string;
  6007. model: string | null;
  6008. discovered_at: string | null;
  6009. }
  6010. export interface DiscoveryStatus {
  6011. running: boolean;
  6012. }
  6013. export interface DiscoveryInfo {
  6014. is_docker: boolean;
  6015. ssdp_running: boolean;
  6016. scan_running: boolean;
  6017. subnets: string[];
  6018. }
  6019. export interface SubnetScanStatus {
  6020. running: boolean;
  6021. scanned: number;
  6022. total: number;
  6023. }
  6024. // Discovery API
  6025. export const discoveryApi = {
  6026. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  6027. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  6028. startDiscovery: (duration: number = 10) =>
  6029. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  6030. stopDiscovery: () =>
  6031. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  6032. getDiscoveredPrinters: () =>
  6033. request<DiscoveredPrinter[]>('/discovery/printers'),
  6034. // Subnet scanning (for Docker environments)
  6035. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  6036. request<SubnetScanStatus>('/discovery/scan', {
  6037. method: 'POST',
  6038. body: JSON.stringify({ subnet, timeout }),
  6039. }),
  6040. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  6041. stopSubnetScan: () =>
  6042. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  6043. };
  6044. // Virtual Printer types
  6045. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  6046. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  6047. // accepted by the backend so older API clients keep working, but new code
  6048. // should send the canonical names.
  6049. export type VirtualPrinterMode = 'archive' | 'review' | 'queue' | 'proxy' | 'immediate' | 'print_queue';
  6050. export interface VirtualPrinterProxyStatus {
  6051. running: boolean;
  6052. target_host: string;
  6053. ftp_port: number;
  6054. mqtt_port: number;
  6055. ftp_connections: number;
  6056. mqtt_connections: number;
  6057. }
  6058. export interface VirtualPrinterStatus {
  6059. enabled: boolean;
  6060. running: boolean;
  6061. mode: VirtualPrinterMode;
  6062. name: string;
  6063. serial: string;
  6064. model: string;
  6065. model_name: string;
  6066. pending_files: number;
  6067. target_printer_ip?: string; // For proxy mode
  6068. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  6069. }
  6070. export interface VirtualPrinterSettings {
  6071. enabled: boolean;
  6072. access_code_set: boolean;
  6073. mode: VirtualPrinterMode;
  6074. model: string;
  6075. target_printer_id: number | null; // For proxy mode
  6076. remote_interface_ip: string | null; // For SSDP proxy across networks
  6077. tailscale_disabled: boolean;
  6078. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  6079. status: VirtualPrinterStatus;
  6080. }
  6081. export interface NetworkInterface {
  6082. name: string;
  6083. ip: string;
  6084. netmask: string;
  6085. subnet: string;
  6086. is_alias?: boolean;
  6087. label?: string;
  6088. }
  6089. export interface VirtualPrinterModels {
  6090. models: Record<string, string>; // SSDP code -> display name
  6091. default: string;
  6092. }
  6093. export interface PendingUpload {
  6094. id: number;
  6095. filename: string;
  6096. // Resolved name the review card should show — mirrors what archive_print
  6097. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  6098. // back to the stripped filename stem when the 3MF has no embedded title or
  6099. // the operator has chosen the "filename" archive-name source.
  6100. display_name: string;
  6101. file_size: number;
  6102. source_ip: string | null;
  6103. status: string;
  6104. tags: string | null;
  6105. notes: string | null;
  6106. project_id: number | null;
  6107. uploaded_at: string;
  6108. }
  6109. // Virtual Printer API
  6110. export const virtualPrinterApi = {
  6111. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  6112. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  6113. updateSettings: (data: {
  6114. enabled?: boolean;
  6115. access_code?: string;
  6116. mode?: 'archive' | 'review' | 'queue' | 'proxy';
  6117. model?: string;
  6118. target_printer_id?: number;
  6119. remote_interface_ip?: string;
  6120. tailscale_disabled?: boolean;
  6121. archive_name_source?: 'metadata' | 'filename';
  6122. }) => {
  6123. const params = new URLSearchParams();
  6124. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  6125. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  6126. if (data.mode !== undefined) params.set('mode', data.mode);
  6127. if (data.model !== undefined) params.set('model', data.model);
  6128. if (data.target_printer_id !== undefined) params.set('target_printer_id', String(data.target_printer_id));
  6129. if (data.remote_interface_ip !== undefined) params.set('remote_interface_ip', data.remote_interface_ip);
  6130. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  6131. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  6132. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  6133. method: 'PUT',
  6134. });
  6135. },
  6136. };
  6137. // Multi Virtual Printer API
  6138. export interface VirtualPrinterConfig {
  6139. id: number;
  6140. name: string;
  6141. enabled: boolean;
  6142. mode: VirtualPrinterMode;
  6143. model: string | null;
  6144. model_name: string | null;
  6145. access_code_set: boolean;
  6146. serial: string;
  6147. target_printer_id: number | null;
  6148. auto_dispatch: boolean;
  6149. queue_force_color_match: boolean;
  6150. tailscale_disabled: boolean;
  6151. bind_ip: string | null;
  6152. remote_interface_ip: string | null;
  6153. position: number;
  6154. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  6155. }
  6156. export interface VirtualPrinterListResponse {
  6157. printers: VirtualPrinterConfig[];
  6158. models: Record<string, string>;
  6159. }
  6160. export const multiVirtualPrinterApi = {
  6161. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  6162. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  6163. create: (data: {
  6164. name?: string;
  6165. enabled?: boolean;
  6166. mode?: string;
  6167. model?: string;
  6168. access_code?: string;
  6169. target_printer_id?: number;
  6170. auto_dispatch?: boolean;
  6171. queue_force_color_match?: boolean;
  6172. bind_ip?: string;
  6173. remote_interface_ip?: string;
  6174. }) =>
  6175. request<VirtualPrinterConfig>('/virtual-printers', {
  6176. method: 'POST',
  6177. body: JSON.stringify(data),
  6178. }),
  6179. update: (id: number, data: {
  6180. name?: string;
  6181. enabled?: boolean;
  6182. mode?: string;
  6183. model?: string;
  6184. access_code?: string;
  6185. target_printer_id?: number;
  6186. auto_dispatch?: boolean;
  6187. queue_force_color_match?: boolean;
  6188. tailscale_disabled?: boolean;
  6189. bind_ip?: string;
  6190. remote_interface_ip?: string;
  6191. }) =>
  6192. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  6193. method: 'PUT',
  6194. body: JSON.stringify(data),
  6195. }),
  6196. remove: (id: number) =>
  6197. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  6198. method: 'DELETE',
  6199. }),
  6200. getTailscaleStatus: () =>
  6201. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  6202. getCaCertificate: () =>
  6203. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  6204. diagnose: (id: number) =>
  6205. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  6206. };
  6207. /** The shared CA certificate every virtual printer presents — imported once
  6208. * into the slicer's trust store. Only the public certificate is returned. */
  6209. export interface VPCaCertificate {
  6210. pem: string;
  6211. fingerprint_sha256: string;
  6212. not_valid_after: string;
  6213. }
  6214. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  6215. export interface VPDiagnosticCheck {
  6216. id:
  6217. | 'enabled'
  6218. | 'running'
  6219. | 'bind_interface'
  6220. | 'access_code'
  6221. | 'target_printer'
  6222. | 'port_ftps'
  6223. | 'port_mqtt'
  6224. | 'port_bind'
  6225. | 'certificate';
  6226. status: VPDiagnosticStatus;
  6227. params: Record<string, string | number>;
  6228. }
  6229. export interface VPDiagnosticResult {
  6230. vp_id: number;
  6231. vp_name: string;
  6232. mode: string;
  6233. overall: 'ok' | 'warnings' | 'problems';
  6234. checks: VPDiagnosticCheck[];
  6235. }
  6236. export interface TailscaleStatusResponse {
  6237. available: boolean;
  6238. fqdn: string;
  6239. hostname: string;
  6240. tailnet_name: string;
  6241. tailscale_ips: string[];
  6242. error: string | null;
  6243. }
  6244. // Pending Uploads API
  6245. export const pendingUploadsApi = {
  6246. list: () => request<PendingUpload[]>('/pending-uploads/'),
  6247. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  6248. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  6249. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  6250. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  6251. method: 'POST',
  6252. body: JSON.stringify(data || {}),
  6253. }),
  6254. discard: (id: number) =>
  6255. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  6256. archiveAll: () =>
  6257. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  6258. discardAll: () =>
  6259. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  6260. };
  6261. // Firmware API Types
  6262. export interface AvailableFirmwareVersion {
  6263. version: string;
  6264. file_available: boolean;
  6265. download_url: string | null;
  6266. release_notes: string | null;
  6267. release_time: string | null;
  6268. }
  6269. export interface FirmwareUpdateInfo {
  6270. printer_id: number;
  6271. printer_name: string;
  6272. model: string | null;
  6273. current_version: string | null;
  6274. latest_version: string | null;
  6275. update_available: boolean;
  6276. download_url: string | null;
  6277. release_notes: string | null;
  6278. available_versions: AvailableFirmwareVersion[];
  6279. }
  6280. export interface FirmwareUploadPrepare {
  6281. can_proceed: boolean;
  6282. sd_card_present: boolean;
  6283. sd_card_free_space: number;
  6284. firmware_size: number;
  6285. space_sufficient: boolean;
  6286. update_available: boolean;
  6287. current_version: string | null;
  6288. latest_version: string | null;
  6289. target_version: string | null;
  6290. firmware_filename: string | null;
  6291. errors: string[];
  6292. }
  6293. export interface FirmwareUploadStatus {
  6294. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  6295. progress: number;
  6296. message: string;
  6297. error: string | null;
  6298. firmware_filename: string | null;
  6299. firmware_version: string | null;
  6300. }
  6301. // Firmware API
  6302. export const firmwareApi = {
  6303. checkUpdates: () =>
  6304. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  6305. checkPrinterUpdate: (printerId: number) =>
  6306. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  6307. prepareUpload: (printerId: number, version?: string) =>
  6308. request<FirmwareUploadPrepare>(
  6309. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  6310. ),
  6311. startUpload: (printerId: number, version?: string) =>
  6312. request<{ started: boolean; message: string }>(
  6313. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  6314. { method: 'POST' },
  6315. ),
  6316. getUploadStatus: (printerId: number) =>
  6317. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  6318. };
  6319. // Support types
  6320. export interface DebugLoggingState {
  6321. enabled: boolean;
  6322. enabled_at: string | null;
  6323. duration_seconds: number | null;
  6324. }
  6325. export interface LogEntry {
  6326. timestamp: string;
  6327. level: string;
  6328. logger_name: string;
  6329. message: string;
  6330. }
  6331. export interface LogsResponse {
  6332. entries: LogEntry[];
  6333. total_in_file: number;
  6334. filtered_count: number;
  6335. }
  6336. // Support API
  6337. export const supportApi = {
  6338. getDebugLoggingState: () =>
  6339. request<DebugLoggingState>('/support/debug-logging'),
  6340. setDebugLogging: (enabled: boolean) =>
  6341. request<DebugLoggingState>('/support/debug-logging', {
  6342. method: 'POST',
  6343. body: JSON.stringify({ enabled }),
  6344. }),
  6345. downloadSupportBundle: async () => {
  6346. const headers: Record<string, string> = {};
  6347. if (authToken) {
  6348. headers['Authorization'] = `Bearer ${authToken}`;
  6349. }
  6350. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  6351. if (!response.ok) {
  6352. const error = await response.json().catch(() => ({}));
  6353. throw new Error(error.detail || `HTTP ${response.status}`);
  6354. }
  6355. // Get filename from Content-Disposition header or use default
  6356. const disposition = response.headers.get('Content-Disposition');
  6357. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  6358. // Download the blob
  6359. const blob = await response.blob();
  6360. const url = window.URL.createObjectURL(blob);
  6361. const a = document.createElement('a');
  6362. a.href = url;
  6363. a.download = filename;
  6364. document.body.appendChild(a);
  6365. a.click();
  6366. document.body.removeChild(a);
  6367. window.URL.revokeObjectURL(url);
  6368. },
  6369. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  6370. const searchParams = new URLSearchParams();
  6371. if (params?.limit) searchParams.set('limit', params.limit.toString());
  6372. if (params?.level) searchParams.set('level', params.level);
  6373. if (params?.search) searchParams.set('search', params.search);
  6374. const query = searchParams.toString();
  6375. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  6376. },
  6377. clearLogs: () =>
  6378. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  6379. };
  6380. // SpoolBuddy types
  6381. export interface SpoolBuddyDevice {
  6382. id: number;
  6383. device_id: string;
  6384. hostname: string;
  6385. ip_address: string;
  6386. backend_url?: string | null;
  6387. firmware_version: string | null;
  6388. has_nfc: boolean;
  6389. has_scale: boolean;
  6390. tare_offset: number;
  6391. calibration_factor: number;
  6392. nfc_reader_type: string | null;
  6393. nfc_connection: string | null;
  6394. display_brightness: number;
  6395. display_blank_timeout: number;
  6396. has_backlight: boolean;
  6397. last_calibrated_at: string | null;
  6398. last_seen: string | null;
  6399. pending_command: string | null;
  6400. nfc_ok: boolean;
  6401. scale_ok: boolean;
  6402. uptime_s: number;
  6403. update_status: string | null;
  6404. update_message: string | null;
  6405. system_stats: {
  6406. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  6407. cpu_temp_c?: number;
  6408. cpu_count?: number;
  6409. load_avg?: number[];
  6410. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  6411. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  6412. system_uptime_s?: number;
  6413. } | null;
  6414. online: boolean;
  6415. }
  6416. export interface DaemonUpdateCheck {
  6417. current_version: string;
  6418. latest_version: string | null;
  6419. update_available: boolean;
  6420. }
  6421. // SpoolBuddy API
  6422. export const spoolbuddyApi = {
  6423. getDevices: () =>
  6424. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  6425. deleteDevice: (deviceId: string) =>
  6426. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  6427. method: 'DELETE',
  6428. }),
  6429. tare: (deviceId: string) =>
  6430. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  6431. method: 'POST',
  6432. body: '{}',
  6433. }),
  6434. getCalibration: (deviceId: string) =>
  6435. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration`),
  6436. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  6437. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  6438. method: 'POST',
  6439. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  6440. }),
  6441. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  6442. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  6443. method: 'POST',
  6444. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  6445. }),
  6446. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  6447. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  6448. method: 'PUT',
  6449. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  6450. }),
  6451. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  6452. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  6453. method: 'POST',
  6454. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  6455. }),
  6456. checkDaemonUpdate: (deviceId: string) =>
  6457. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  6458. triggerUpdate: (deviceId: string) =>
  6459. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  6460. method: 'POST',
  6461. body: '{}',
  6462. }),
  6463. getSSHPublicKey: () =>
  6464. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  6465. writeTag: (deviceId: string, spoolId: number) =>
  6466. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  6467. method: 'POST',
  6468. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  6469. }),
  6470. cancelWrite: (deviceId: string) =>
  6471. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  6472. method: 'POST',
  6473. body: '{}',
  6474. }),
  6475. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  6476. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  6477. method: 'POST',
  6478. body: JSON.stringify({ command }),
  6479. }),
  6480. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  6481. request<{ status: string; diagnostic: string; message: string }>(
  6482. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  6483. { method: 'POST', body: '{}' }
  6484. ),
  6485. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  6486. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  6487. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  6488. { method: 'GET' }
  6489. ),
  6490. };
  6491. export interface BugReportRequest {
  6492. description: string;
  6493. email?: string;
  6494. screenshot_base64?: string;
  6495. include_support_info?: boolean;
  6496. debug_logs?: string;
  6497. }
  6498. export interface BugReportResponse {
  6499. success: boolean;
  6500. message: string;
  6501. issue_url?: string;
  6502. issue_number?: number;
  6503. }
  6504. export const bugReportApi = {
  6505. submit: (data: BugReportRequest) =>
  6506. request<BugReportResponse>('/bug-report/submit', {
  6507. method: 'POST',
  6508. body: JSON.stringify(data),
  6509. }),
  6510. startLogging: () =>
  6511. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  6512. method: 'POST',
  6513. }),
  6514. stopLogging: (wasDebug: boolean) =>
  6515. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  6516. method: 'POST',
  6517. }),
  6518. };