client.ts 255 KB

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