client.ts 353 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868
  1. import type { KProfileWriteResult } from '../utils/kprofileWrite';
  2. import type { BambuCatalogColor } from '../utils/colors';
  3. import type { ArchivePlatesResponse, LibraryFilePlatesResponse } from '../types/plates';
  4. import { batched, byField, byId } from './batch';
  5. const API_BASE = '/api/v1';
  6. export class ApiError extends Error {
  7. status: number;
  8. /** Stable error code from a structured backend detail (`{code, message}`).
  9. * Frontend uses this to look up an i18n key instead of showing the raw
  10. * English fallback. Null when the backend returned a plain-string detail. */
  11. code: string | null;
  12. /** Full structured detail object when the backend returned `{code, ...}`
  13. * with additional fields (e.g. the deficit list for 409s on queue
  14. * start, #1496). Null for plain-string or array-shaped details. */
  15. detail: Record<string, unknown> | null;
  16. constructor(
  17. message: string,
  18. status: number,
  19. code: string | null = null,
  20. detail: Record<string, unknown> | null = null,
  21. ) {
  22. super(message);
  23. this.name = 'ApiError';
  24. this.status = status;
  25. this.code = code;
  26. this.detail = detail;
  27. }
  28. }
  29. // Auth token storage
  30. // By default tokens are stored in sessionStorage (tab-scoped, cleared on close).
  31. // When the token originates from the ?token= URL param (kiosk bootstrap), it is
  32. // additionally persisted in localStorage so the kiosk survives page reloads.
  33. // 'persistent' also writes to localStorage so the token survives tab close
  34. // (used by Remember Me and the ?token= kiosk bootstrap).
  35. let authToken: string | null =
  36. sessionStorage.getItem('auth_token') ?? localStorage.getItem('auth_token');
  37. export type TokenPersistence = 'session' | 'persistent';
  38. export function setAuthToken(token: string | null, persistence: TokenPersistence = 'session') {
  39. authToken = token;
  40. try {
  41. if (token) {
  42. sessionStorage.setItem('auth_token', token);
  43. } else {
  44. sessionStorage.removeItem('auth_token');
  45. }
  46. } catch (err) {
  47. // Storage unavailable (quota exceeded, private mode): in-memory token still works for this tab.
  48. console.warn('setAuthToken: sessionStorage unavailable, token kept in-memory only', err);
  49. }
  50. try {
  51. if (!token) {
  52. localStorage.removeItem('auth_token');
  53. } else if (persistence === 'persistent') {
  54. localStorage.setItem('auth_token', token);
  55. }
  56. } catch (err) {
  57. console.warn('setAuthToken: localStorage operation failed', err);
  58. }
  59. }
  60. export function getAuthToken(): string | null {
  61. return authToken;
  62. }
  63. // Query-param tokens for <img>/<video> src URLs, which can't carry an
  64. // Authorization header. There are two, and which one a URL takes is decided
  65. // by what the URL points at, not by convenience:
  66. //
  67. // streamToken — live camera only. Minting one costs camera:view.
  68. // mediaToken — thumbnails, previews, timelapses, covers, icons. Minted by
  69. // any signed-in user and carries their identity, so those
  70. // routes can apply the same ownership rules as everywhere else.
  71. //
  72. // Before #3025 the stream token served both, which meant a user could not see
  73. // a library thumbnail without also being granted the live feed of the room the
  74. // printer sits in — and, because a stream token names nobody, those routes had
  75. // no identity to scope by and served any row to any holder.
  76. let streamToken: string | null = null;
  77. let mediaToken: string | null = null;
  78. export function setStreamToken(token: string | null) {
  79. streamToken = token;
  80. }
  81. export function getStreamToken(): string | null {
  82. return streamToken;
  83. }
  84. export function setMediaToken(token: string | null) {
  85. mediaToken = token;
  86. }
  87. export function getMediaToken(): string | null {
  88. return mediaToken;
  89. }
  90. /** Append the camera stream token to a URL if available (live camera only). */
  91. export function withStreamToken(url: string): string {
  92. if (!streamToken) return url;
  93. const sep = url.includes('?') ? '&' : '?';
  94. return `${url}${sep}token=${encodeURIComponent(streamToken)}`;
  95. }
  96. /** Append the media token to a URL if available (for <img>/<video> src). */
  97. export function withMediaToken(url: string): string {
  98. if (!mediaToken) return url;
  99. const sep = url.includes('?') ? '&' : '?';
  100. return `${url}${sep}token=${encodeURIComponent(mediaToken)}`;
  101. }
  102. function parseContentDispositionFilename(header: string | null): string | null {
  103. if (!header) return null;
  104. // RFC 5987: filename*=utf-8''percent-encoded-name
  105. const rfc5987Match = header.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);
  106. if (rfc5987Match) {
  107. try { return decodeURIComponent(rfc5987Match[1]); } catch { /* fall through */ }
  108. }
  109. // Standard: filename="name" or filename=name
  110. const standardMatch = header.match(/filename="?([^";\n]+)"?/);
  111. return standardMatch?.[1] || null;
  112. }
  113. function buildSlicerUrlFilename(filename: string): string {
  114. const safe = filename.replace(/[/\\?#]/g, '_');
  115. return safe.toLowerCase().endsWith('.3mf') ? safe : `${safe}.3mf`;
  116. }
  117. /** POST JSON and return the response body as a Blob (label PDFs and images). */
  118. async function postForBlob(endpoint: string, data: unknown, signal?: AbortSignal): Promise<Blob> {
  119. const headers: Record<string, string> = { 'Content-Type': 'application/json' };
  120. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  121. const response = await fetch(`${API_BASE}${endpoint}`, {
  122. method: 'POST',
  123. headers,
  124. body: JSON.stringify(data),
  125. signal,
  126. });
  127. if (!response.ok) {
  128. const error = await response.json().catch(() => ({}));
  129. throw new Error(typeof error.detail === 'string' ? error.detail : `HTTP ${response.status}`);
  130. }
  131. return response.blob();
  132. }
  133. async function request<T>(
  134. endpoint: string,
  135. options: RequestInit = {}
  136. ): Promise<T> {
  137. const headers: Record<string, string> = {
  138. 'Content-Type': 'application/json',
  139. ...options.headers as Record<string, string>,
  140. };
  141. // Add auth token if available
  142. if (authToken) {
  143. headers['Authorization'] = `Bearer ${authToken}`;
  144. }
  145. const response = await fetch(`${API_BASE}${endpoint}`, {
  146. ...options,
  147. cache: 'no-store', // Prevent browser caching of API responses
  148. credentials: 'include', // Required for HttpOnly cookies (e.g. 2fa_challenge)
  149. headers,
  150. });
  151. if (!response.ok) {
  152. const error = await response.json().catch(() => ({}));
  153. const detail = error.detail;
  154. let message: string;
  155. let code: string | null = null;
  156. if (typeof detail === 'string') {
  157. message = detail;
  158. } else if (Array.isArray(detail)) {
  159. // FastAPI 422 shape: each entry has `msg` like "Value error, <real msg>".
  160. // Strip the prefix and join. Fall back to raw JSON if every entry has an
  161. // empty msg (defensive — shouldn't happen with stock Pydantic, but the
  162. // previous fallback masked the real cause as a bare "HTTP 422" toast).
  163. const joined = detail
  164. .map((e: { msg?: string }) => (e.msg ?? '').replace(/^Value error,\s*/i, ''))
  165. .filter(Boolean)
  166. .join('; ');
  167. message = joined || JSON.stringify(detail) || `HTTP ${response.status}`;
  168. } else if (detail && typeof detail === 'object') {
  169. // Structured detail `{code, message, ...}` — frontend uses the code
  170. // to pick an i18n key, message is the English fallback, any extra
  171. // fields land on ApiError.detail (e.g. `deficit` for #1496).
  172. code = typeof detail.code === 'string' ? detail.code : null;
  173. message = typeof detail.message === 'string' ? detail.message : `HTTP ${response.status}`;
  174. } else {
  175. message = `HTTP ${response.status}`;
  176. }
  177. const structuredDetail = detail && typeof detail === 'object' && !Array.isArray(detail)
  178. ? (detail as Record<string, unknown>)
  179. : null;
  180. // Handle 401 Unauthorized - only clear token if it's actually invalid
  181. // Don't clear on "Authentication required" which might be a timing issue
  182. if (response.status === 401) {
  183. const invalidTokenMessages = [
  184. 'Could not validate credentials',
  185. 'Token has expired',
  186. 'User not found or inactive',
  187. 'Invalid API key',
  188. 'API key has expired',
  189. ];
  190. if (invalidTokenMessages.some(m => message.includes(m))) {
  191. setAuthToken(null);
  192. // Notify AuthContext so the protected route guard re-evaluates and
  193. // redirects to /login on the same tab — without this, AuthContext.user
  194. // stays cached and the tab silently fails every request until a manual
  195. // refresh remounts AuthProvider (#1698, reported by @TCL987).
  196. if (typeof window !== 'undefined') {
  197. window.dispatchEvent(new CustomEvent('auth:expired'));
  198. }
  199. }
  200. }
  201. throw new ApiError(message, response.status, code, structuredDetail);
  202. }
  203. // Handle empty responses (204 No Content, etc.)
  204. const contentLength = response.headers.get('content-length');
  205. if (response.status === 204 || contentLength === '0') {
  206. return undefined as T;
  207. }
  208. return await response.json();
  209. }
  210. /** Upload a CSV to the spool import endpoint (#1576). Multipart, so it bypasses
  211. * `request<T>()` (which sends JSON): the browser must set the form-data
  212. * boundary itself. `dryRun` toggles preview-only vs. real import. */
  213. async function uploadSpoolsCsv<T>(file: File, dryRun: boolean): Promise<T> {
  214. const form = new FormData();
  215. form.append('file', file);
  216. const headers: Record<string, string> = {};
  217. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  218. const response = await fetch(`${API_BASE}/inventory/spools/import${dryRun ? '?dry_run=true' : ''}`, {
  219. method: 'POST',
  220. headers,
  221. body: form,
  222. });
  223. if (!response.ok) {
  224. const error = await response.json().catch(() => ({}));
  225. // detail may be a plain string or a structured {code, message} object
  226. // (e.g. the 413 too-large response). Surface the human message either way.
  227. const detail = error?.detail;
  228. const message = typeof detail === 'string' ? detail : detail?.message;
  229. throw new Error(message || `HTTP ${response.status}`);
  230. }
  231. return response.json();
  232. }
  233. // Camera diagnostic result (#1395 follow-up). Returned by
  234. // POST /printers/{id}/camera/diagnose; the frontend modal renders one
  235. // row per stage and looks up the summary code in i18n for the user-
  236. // facing remediation hint.
  237. export interface CameraDiagnoseStage {
  238. name: 'tcp_reachable' | 'first_frame' | 'live_stream_active';
  239. status: 'ok' | 'failed' | 'skipped';
  240. duration_ms: number;
  241. code: string | null;
  242. }
  243. export interface CameraDiagnoseResult {
  244. printer_id: number;
  245. protocol: 'rtsp' | 'chamber_image';
  246. port: number;
  247. // 'default' = historical X1/H2 tuning. Anything else = this model has
  248. // an override entry in backend/app/services/camera_profiles.py.
  249. profile: string;
  250. overall_status: 'ok' | 'failed';
  251. stages: CameraDiagnoseStage[];
  252. // i18n key under `camera.diagnose.summary.*`.
  253. summary_code: string;
  254. }
  255. // Connection diagnostic (GET /printers/{id}/diagnostic and
  256. // POST /printers/diagnostic). Each check's `id` + `status` resolve a
  257. // localized title/fix under `diagnostic.check.*`; `params` interpolate it.
  258. export type DiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  259. export interface DiagnosticCheck {
  260. id:
  261. | 'port_mqtt'
  262. | 'port_ftps'
  263. | 'port_rtsps'
  264. | 'network_mode'
  265. | 'subnet'
  266. | 'mqtt_auth'
  267. | 'developer_mode';
  268. status: DiagnosticStatus;
  269. params: Record<string, string | number>;
  270. }
  271. export interface PrinterDiagnosticResult {
  272. printer_id: number | null;
  273. ip_address: string;
  274. overall: 'ok' | 'warnings' | 'problems';
  275. checks: DiagnosticCheck[];
  276. }
  277. // --- Log-health scan: self-service triage on the System page + bug reporter.
  278. // The backend matches recent logs against a curated known-issue catalog;
  279. // human-readable cause/fix text is rendered from i18n keys keyed by signature_id.
  280. export type LogFindingSeverity = 'error' | 'warning';
  281. export type LogFindingCategory = 'layer8' | 'environment' | 'bug';
  282. export interface LogFinding {
  283. signature_id: string;
  284. severity: LogFindingSeverity;
  285. category: LogFindingCategory;
  286. wiki_anchor: string;
  287. count: number;
  288. first_seen: string;
  289. last_seen: string;
  290. sample: string;
  291. }
  292. export interface SystemHealthResult {
  293. findings: LogFinding[];
  294. scanned_entries: number;
  295. log_available: boolean;
  296. summary: {
  297. total: number;
  298. layer8: number;
  299. environment: number;
  300. bug: number;
  301. };
  302. }
  303. // Long-lived camera tokens (#1108). The `token` field is populated only on the
  304. // create response — listing endpoints set it to null because the plaintext
  305. // value is shown to the user exactly once.
  306. //
  307. // 'camera_stream' reaches the video endpoints only. 'camwall' additionally
  308. // reaches the read-only Cam Wall feed, which names the printers (#2531), so it
  309. // is a separate scope rather than a widening of tokens already in the wild.
  310. export type LongLivedTokenScope = 'camera_stream' | 'camwall' | 'overlay';
  311. export interface LongLivedCameraToken {
  312. id: number;
  313. user_id: number;
  314. name: string;
  315. scope: LongLivedTokenScope;
  316. lookup_prefix: string;
  317. created_at: string;
  318. expires_at: string;
  319. last_used_at: string | null;
  320. token: string | null;
  321. }
  322. // An external application that signs users in with their Bambuddy account.
  323. // `client_secret` is present only in the create / rotate responses.
  324. export interface ConnectedApp {
  325. id: number;
  326. name: string;
  327. client_id: string;
  328. redirect_uri: string;
  329. enabled: boolean;
  330. created_at: string;
  331. last_used_at: string | null;
  332. client_secret?: string;
  333. }
  334. export interface ConnectAuthorizeInfo {
  335. app_name: string;
  336. username: string;
  337. already_granted: boolean;
  338. }
  339. // One row of the token-authenticated Cam Wall feed (#2531). Deliberately
  340. // smaller than PrinterStatus: no serial, no IP, no print filename — a kiosk URL
  341. // is not a secret, so the payload behind it must not be either.
  342. export interface CamWallPrinter {
  343. id: number;
  344. name: string;
  345. camera_rotation: number;
  346. connected: boolean;
  347. state: string | null;
  348. progress: number | null;
  349. remaining_time: number | null;
  350. layer_num: number | null;
  351. total_layers: number | null;
  352. hms_errors: HMSError[];
  353. }
  354. // Streaming-overlay feed (#2613). The subset of print state the /overlay page
  355. // draws for one printer, served behind an `overlay`-scoped token so OBS embeds
  356. // with no login session can read it. Unlike CamWallPrinter this names the file
  357. // being printed (the overlay shows the part on screen).
  358. export interface OverlayStatus {
  359. id: number;
  360. name: string;
  361. model: string | null;
  362. camera_rotation: number;
  363. connected: boolean;
  364. state: string | null;
  365. current_print: string | null;
  366. gcode_file: string | null;
  367. progress: number | null;
  368. remaining_time: number | null;
  369. layer_num: number | null;
  370. total_layers: number | null;
  371. stg_cur_name: string | null;
  372. // Nozzle / bed / chamber readings for the overlay's temperature fields
  373. // (#1422). Only the keys a viewer is shown; chamber is absent on models
  374. // without a real sensor.
  375. temperatures: Record<string, number>;
  376. time_format: 'system' | '12h' | '24h';
  377. }
  378. // Printer types
  379. // Printer locations (groups) and their appearance (#2962). `id` is null for a
  380. // location only printers carry, with no row of its own yet.
  381. export interface PrinterLocation {
  382. id: number | null;
  383. name: string;
  384. icon: string | null;
  385. color: string | null;
  386. printer_count: number;
  387. }
  388. export interface PrinterLocationUpdate {
  389. name: string;
  390. new_name?: string;
  391. icon?: string | null;
  392. color?: string | null;
  393. }
  394. export interface WLEDPresets {
  395. idle: number | null;
  396. prepare: number | null;
  397. printing: number | null;
  398. paused: number | null;
  399. finished: number | null;
  400. error: number | null;
  401. queue_waiting: number | null;
  402. filament_problem: number | null;
  403. hms_error: number | null;
  404. offline: number | null;
  405. }
  406. export interface WLEDConfig {
  407. enabled: boolean;
  408. base_url: string | null;
  409. presets: WLEDPresets;
  410. finished_timeout_seconds: number | null;
  411. }
  412. export interface WLEDPreset {
  413. id: number;
  414. name: string;
  415. }
  416. export interface WLEDConnectionInfo {
  417. name: string | null;
  418. version: string | null;
  419. }
  420. export interface Printer {
  421. id: number;
  422. name: string;
  423. serial_number: string;
  424. ip_address: string;
  425. // Optional because the backend only returns access_code when the caller has
  426. // PRINTERS_UPDATE — Admin / Operator JWTs or auth-disabled mode. Viewers and
  427. // API keys receive a Printer without this field.
  428. access_code?: string;
  429. model: string | null;
  430. location: string | null; // Group/location name
  431. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  432. // Model is sold with both Standard and High Flow nozzles, so a K-profile's
  433. // flow type is a real choice. Derived from the model, not the nozzle count —
  434. // only the A-series has a single variant.
  435. supports_nozzle_flow_type: boolean;
  436. is_active: boolean;
  437. auto_archive: boolean;
  438. external_camera_url: string | null;
  439. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  440. external_camera_enabled: boolean;
  441. external_camera_snapshot_url: string | null; // optional single-frame override (#1177)
  442. camera_rotation: number; // 0, 90, 180, 270 degrees
  443. camera_light_auto: boolean; // picked for the chamber light when camera_light_mode is 'selected' (#1655)
  444. plate_detection_enabled: boolean; // Check plate before print
  445. plate_detection_roi?: PlateDetectionROI; // ROI for plate detection
  446. wear_cost_per_hour: number | null; // Wear cost per printing hour (#694)
  447. dispatch_priority: number | null; // Place in the pick order of any-model jobs, lowest first (#2915)
  448. wled_config: WLEDConfig | null;
  449. created_at: string;
  450. updated_at: string;
  451. }
  452. export interface HMSError {
  453. code: string;
  454. attr: number; // Attribute value for constructing wiki URL
  455. module: number;
  456. // Bambu's alert level: 1 error (task stopped), 2 warning (task paused),
  457. // 3 notification, 0 invalid (#2728).
  458. severity: number;
  459. actions?: string[]; // List of user-facing action keys (e.g. "CHECK_FILAMENT")
  460. job_id?: string; // Optional job ID for actions that require it (e.g. "CHECK_ASSISTANT")
  461. // Canonical hex identifier the firmware matches against — 8 chars for
  462. // print_error-sourced faults, 16 chars for hms[]-array-sourced faults. Send
  463. // this back as HmsActionBody.print_error so we don't truncate the 64-bit
  464. // identifier into the silent-rejection short code (#1830).
  465. full_code?: string;
  466. // The backend's catalogue sentence for this fault (#2926), from the table
  467. // generated out of Bambu Studio for this printer model (#2728). English only.
  468. // Null when Bambu publishes no text for the code. The frontend has no table of
  469. // its own: this field decides both the text and whether the fault counts.
  470. description?: string | null;
  471. }
  472. export interface HMSActionBody {
  473. print_error: string; // HMS error code (e.g. "05000070")
  474. action: string; // "HMS action to execute (e.g. 'resume_after_error')"
  475. job_id: string | null; // Optional job ID for context (if applicable)
  476. }
  477. export interface AMSTray {
  478. id: number;
  479. tray_color: string | null;
  480. tray_type: string | null;
  481. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  482. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  483. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  484. remain: number;
  485. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  486. cali_idx: number | null; // Calibration index for K-profile lookup
  487. tag_uid: string | null; // RFID tag UID (any tag)
  488. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  489. nozzle_temp_min: number | null; // Min nozzle temperature
  490. nozzle_temp_max: number | null; // Max nozzle temperature
  491. drying_temp: number | null; // RFID-recommended drying temp
  492. drying_time: number | null; // RFID-recommended drying time (hours)
  493. state: number | null; // AMS tray state: 9=empty, 10=spool present not loaded, 11=loaded
  494. exists?: boolean | null; // Firmware tray_exist_bits: spool physically present (non-RFID → "?" not "Empty", #2527)
  495. }
  496. export interface AMSUnit {
  497. id: number;
  498. humidity: number | null;
  499. temp: number | null;
  500. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  501. tray: AMSTray[];
  502. serial_number: string; // AMS unit serial number (from MQTT sn field)
  503. sw_ver: string; // AMS firmware version (from get_version info.module ams/* entry)
  504. dry_time: number; // Minutes remaining (0 = not drying, >0 = drying active)
  505. dry_countdown_stalled?: boolean; // Timer set but countdown not ticking (never started or paused)
  506. dry_status: number; // 0=Off, 1=Checking, 2=Drying, 3=Cooling, 4=Stopping, 5=Error
  507. dry_sub_status: number; // 0=Off, 1=Heating, 2=Dehumidify
  508. dry_sf_reason: number[]; // Cannot-dry reasons (1=InsufficientPower, 8=NeedPluginPower)
  509. dry_target_temp: number | null; // Active-cycle target °C (Bambu does not echo)
  510. dry_filament: string | null; // Active-cycle filament name we sent
  511. module_type: string; // "ams", "ams_f1", "n3f", "n3s", "n10a" (H3C AMS 3H)
  512. ams_type?: number | null; // Bambu Studio's AMS type (utils/trayIds AmsType), 6 = AMS 3H
  513. // The AMS 3H dryer: its two slots (tray ids 0-8) and that zone's humidity (%) and temperature.
  514. dryer_slots?: number[];
  515. dryer_humidity?: number | null;
  516. dryer_temp?: number | null;
  517. }
  518. export interface ScheduledDrying {
  519. id: number;
  520. printer_id: number;
  521. ams_id: number;
  522. temp: number;
  523. duration_hours: number;
  524. filament: string;
  525. rotate_tray: boolean;
  526. start_after: string | null; // UTC ISO with Z suffix, like the queue routes
  527. status: string;
  528. waiting_reason: string | null;
  529. error_message: string | null;
  530. // Why a failed run failed (screen_only / unsupported / did_not_start); null on
  531. // rows that failed before codes existed, which show error_message instead.
  532. error_code?: string | null;
  533. created_at: string;
  534. started_at: string | null;
  535. completed_at: string | null;
  536. }
  537. export interface NozzleInfo {
  538. // Two vocabularies live in this field, by printer generation. Legacy
  539. // printers (X1/P1) report the nozzle MATERIAL -- "stainless_steel",
  540. // "hardened_steel". H2-series report a FLOW code -- "HH01" (high flow),
  541. // "HS01" (standard); measured on an H2D. utils/nozzleFlow reads only the
  542. // latter and treats anything else as "unknown", which is what makes the
  543. // material spelling harmless here.
  544. nozzle_type: string;
  545. nozzle_diameter: string; // e.g., "0.4"
  546. }
  547. export interface NozzleRackSlot {
  548. id: number;
  549. nozzle_type: string;
  550. nozzle_diameter: string;
  551. wear: number | null;
  552. print_time_s?: number | null; // H2C: seconds this nozzle has printed (#1908); null when not reported
  553. stat: number | null; // Nozzle status (e.g. mounted/docked)
  554. max_temp: number;
  555. serial_number: string;
  556. filament_color: string; // RGBA hex ("00000000" = no filament)
  557. filament_id: string;
  558. filament_type: string; // Material type (e.g. "PLA", "PETG")
  559. addr_id?: number | null; // H3C: home rack position 0-8 (the mounted hotend reports id 0)
  560. }
  561. export interface PrintOptions {
  562. // Core AI detectors
  563. spaghetti_detector: boolean;
  564. print_halt: boolean;
  565. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  566. first_layer_inspector: boolean;
  567. printing_monitor: boolean;
  568. buildplate_marker_detector: boolean;
  569. allow_skip_parts: boolean;
  570. // Additional AI detectors (decoded from cfg bitmask)
  571. nozzle_clumping_detector: boolean;
  572. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  573. pileup_detector: boolean;
  574. pileup_sensitivity: string; // "low", "medium", "high"
  575. airprint_detector: boolean;
  576. airprint_sensitivity: string; // "low", "medium", "high"
  577. auto_recovery_step_loss: boolean;
  578. filament_tangle_detect: boolean;
  579. }
  580. export interface FilaSwitchState {
  581. installed: boolean;
  582. // Raw wire arrays, ordered **In-B first, then In-A** (BambuStudio's SwitchPos
  583. // enum). in[] values are snow-encoded (bits 8-15 = AMS id, bits 0-7 = slot,
  584. // -1 = empty); out[] values are the extruder each *outlet* terminates at, or
  585. // 0xE when unset. Neither array says which inlet is currently routed to which
  586. // outlet — that pairing is not reported. For per-AMS side information use
  587. // PrinterStatus.ams_switch_inlet instead.
  588. in_slots: number[];
  589. out_extruders: number[];
  590. stat: number;
  591. info: number;
  592. // Whether every AMS is bound to one of the switch's two inlets. Until it is,
  593. // the switch cannot route a load anywhere and the printer has to be set up
  594. // first ("Manual AMS Setup" on its screen).
  595. ready: boolean;
  596. }
  597. // Which AMS slot one hotend is currently fed from. ams_id/slot_id are null when
  598. // the hotend holds nothing. Keyed by extruder id ('0' = right, '1' = left).
  599. // tray_now cannot answer this — it is one value for the whole printer, so on a
  600. // dual-nozzle machine it names only one of the two loaded hotends.
  601. export interface ExtruderSlot {
  602. ams_id: number | null;
  603. slot_id: number | null;
  604. has_filament: boolean;
  605. }
  606. // Which FTS inlet an AMS is plumbed into: 'A' | 'B'.
  607. export type FtsInlet = 'A' | 'B';
  608. // A video device the server can see, for a USB camera (GET /printers/usb-cameras).
  609. export interface UsbCamera {
  610. device: string;
  611. name: string;
  612. capabilities: string[];
  613. driver?: string;
  614. formats?: string[];
  615. }
  616. export interface PrinterStatus {
  617. id: number;
  618. name: string;
  619. connected: boolean;
  620. state: string | null;
  621. current_print: string | null;
  622. subtask_name: string | null;
  623. current_archive_id: number | null;
  624. current_plate_id: number | null;
  625. gcode_file: string | null;
  626. progress: number | null;
  627. remaining_time: number | null;
  628. layer_num: number | null;
  629. total_layers: number | null;
  630. temperatures: {
  631. bed?: number;
  632. bed_target?: number;
  633. bed_heating?: boolean; // Actual heater state from MQTT
  634. nozzle?: number;
  635. nozzle_target?: number;
  636. nozzle_heating?: boolean; // Actual heater state from MQTT
  637. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  638. nozzle_2_target?: number;
  639. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  640. chamber?: number;
  641. chamber_target?: number;
  642. chamber_heating?: boolean; // Actual heater state from MQTT
  643. } | null;
  644. cover_url: string | null;
  645. hms_errors: HMSError[];
  646. // Live updates send null when no AMS is attached; the REST status sends [].
  647. ams: AMSUnit[] | null;
  648. ams_exists: boolean;
  649. vt_tray: AMSTray[]; // Virtual tray / external spool(s)
  650. store_to_sdcard: boolean; // Store sent files on SD card
  651. timelapse: boolean; // Timelapse recording active
  652. ipcam: boolean; // Live view enabled
  653. wifi_signal: number | null; // WiFi signal strength in dBm
  654. wired_network: boolean; // Ethernet connection detected
  655. door_open: boolean; // Enclosure door open (models with a door sensor: X1/X1C/X1E/X2D/P2S/H2*)
  656. // Indexed by EXTRUDER id: [0] is the right hotend, [1] the left. Measured
  657. // on an H2D with 0.4 left / 0.6 right. Read it through the helpers in
  658. // utils/amsHelpers rather than indexing it directly.
  659. nozzles: NozzleInfo[];
  660. nozzle_rack: NozzleRackSlot[]; // H2C 6-nozzle tool-changer rack
  661. print_options: PrintOptions | null; // AI detection and print options
  662. // Calibration stage tracking
  663. stg_cur: number; // Current stage number (-1 = not calibrating)
  664. stg_cur_name: string | null; // Human-readable current stage name
  665. stg: number[]; // List of stage numbers in calibration sequence
  666. // Air conditioning mode (0=cooling, 1=heating)
  667. airduct_mode: number;
  668. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  669. speed_level: number;
  670. // Chamber light on/off
  671. chamber_light: boolean;
  672. // Active extruder for dual nozzle (0=right, 1=left)
  673. active_extruder: number;
  674. // AMS mapping - which AMS is connected to which nozzle
  675. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  676. ams_mapping: number[];
  677. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  678. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  679. // Note: JSON keys are always strings
  680. ams_extruder_map: Record<string, number>;
  681. // Filament Track Switch accessory — null when not installed. When present,
  682. // AMS slots aren't tied to a specific extruder; the FTS routes any slot to
  683. // either extruder, so per-extruder slot filtering must be skipped.
  684. fila_switch: FilaSwitchState | null;
  685. // Per-AMS FTS inlet binding, {ams_id: 'A' | 'B'}, as set on the printer's
  686. // "Manual AMS Setup" screen. Empty unless a switch is installed. An AMS with
  687. // an entry here reaches BOTH nozzles through the switch, which is why it has
  688. // no ams_extruder_map entry and must not be badged left or right.
  689. ams_switch_inlet: Record<string, FtsInlet>;
  690. // Which AMS slot each hotend is fed from, keyed by extruder id as a string.
  691. // Empty on printers that don't report it (everything but the H2/X2 series).
  692. extruder_slots: Record<string, ExtruderSlot>;
  693. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  694. tray_now: number;
  695. // The trays this print has drawn from, in order: [global tray ID, layer of the
  696. // switch]. A tray outside the job's AMS mapping is a backup spool the printer
  697. // switched to (AMS Filament Backup). Reset at the start of each print.
  698. tray_change_log?: [number, number][];
  699. // Runout / filament-replacement guidance (#2587). Populated only while PAUSED.
  700. // Global tray IDs (ams_id*4+slot, 28-36 = H3C AMS 3H, 128-135 = AMS-HT, 254 = external; utils/trayIds), matching
  701. // the same numbering as tray_now so the AMS graphic can highlight them.
  702. // expected_tray = the slot the firmware now expects filament in (null = idle,
  703. // not paused, or unresolvable → "check the printer").
  704. // previous_tray = the slot that ran out (null = unknown).
  705. expected_tray: number | null;
  706. previous_tray: number | null;
  707. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  708. ams_status_main: number;
  709. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  710. ams_status_sub: number;
  711. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  712. mc_print_sub_stage: number;
  713. // Timestamp of last AMS data update (for RFID refresh detection)
  714. last_ams_update: number;
  715. // Number of printable objects in current print (for skip objects feature)
  716. printable_objects_count: number;
  717. // The next pause the slicer put into the running print (#2984). minutes is
  718. // null while the printer reports no time left yet.
  719. next_pause?: { layer: number; minutes: number | null } | null;
  720. // Fan speeds (0-100 percentage, null if not available for this model)
  721. cooling_fan_speed: number | null; // Part cooling fan
  722. big_fan1_speed: number | null; // Auxiliary fan
  723. big_fan2_speed: number | null; // Chamber/exhaust fan
  724. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  725. // Left auxiliary part cooling fan (optional P2S/X2D accessory, M106 P10).
  726. // null = not installed / not reported by this model.
  727. left_aux_fan_speed: number | null;
  728. // Chamber exhaust fan present (P2S/X2D External Exhaust Fan kit, airduct part 3).
  729. exhaust_fan_present: boolean;
  730. firmware_version: string | null; // Firmware version from MQTT
  731. // Developer LAN mode: true = enabled, false = disabled, null = unknown
  732. developer_mode: boolean | null;
  733. // AMS Filament Backup ("auto-switch" to a backup spool when one runs out).
  734. // true = ON, false = OFF, null = unknown / unsupported (A1 family).
  735. ams_filament_backup: boolean | null;
  736. // Queue: printer is awaiting user ack that the build plate was cleared after a
  737. // finished/failed print. Persisted across restarts (#961).
  738. awaiting_plate_clear: boolean;
  739. // AMS drying support
  740. supports_drying: boolean;
  741. // The AMS can dry, but only from the printer's own screen (P1 series, #2533).
  742. drying_screen_only?: boolean;
  743. // Active chamber heater (responds to M141). True only for H2C/H2D/H2DPro/H2S/X2D.
  744. supports_chamber_heater?: boolean;
  745. // BIQU Panda Breath bound to this printer (#1466), null without one.
  746. panda_breath?: PandaBreathState | null;
  747. }
  748. export type PandaBreathMode = 'auto mode' | 'power on' | 'filament drying';
  749. export interface PandaBreathState {
  750. device_id: string;
  751. online: boolean | null;
  752. chamber_temp: number | null;
  753. target_temp: number | null;
  754. work_on: boolean | null;
  755. mode: string | null;
  756. filament_drying_mode: string | null;
  757. drying_running: boolean | null;
  758. drying_remaining_min: number | null;
  759. }
  760. export interface PandaBreathCommand {
  761. work_on?: boolean;
  762. mode?: PandaBreathMode;
  763. target_temp?: number;
  764. }
  765. export interface PandaBreathStatus {
  766. enabled: boolean;
  767. connected: boolean;
  768. devices: (PandaBreathState & { bound: boolean; printer_id: number | null; printer_name: string | null })[];
  769. }
  770. export interface PrinterCreate {
  771. name: string;
  772. serial_number: string;
  773. ip_address: string;
  774. access_code: string;
  775. model?: string;
  776. location?: string | null;
  777. auto_archive?: boolean;
  778. // Maintenance Mode flag (#1476). Backend already gates MQTT, queue dispatch,
  779. // scheduler, metrics and the print picker on this; toggling via PATCH
  780. // /printers/{id} disconnects or reconnects MQTT accordingly.
  781. is_active?: boolean;
  782. external_camera_url?: string | null;
  783. external_camera_type?: string | null;
  784. external_camera_enabled?: boolean;
  785. external_camera_snapshot_url?: string | null;
  786. camera_rotation?: number;
  787. camera_light_auto?: boolean;
  788. plate_detection_enabled?: boolean;
  789. plate_detection_roi?: PlateDetectionROI;
  790. wear_cost_per_hour?: number | null;
  791. dispatch_priority?: number | null;
  792. wled_config?: WLEDConfig | null;
  793. }
  794. // Plate Detection
  795. export interface PlateDetectionROI {
  796. x: number; // X start % (0.0-1.0)
  797. y: number; // Y start % (0.0-1.0)
  798. w: number; // Width % (0.0-1.0)
  799. h: number; // Height % (0.0-1.0)
  800. }
  801. export interface PlateDetectionResult {
  802. is_empty: boolean;
  803. confidence: number;
  804. difference_percent: number;
  805. message: string;
  806. has_debug_image: boolean;
  807. debug_image_url?: string;
  808. needs_calibration: boolean;
  809. light_warning?: boolean;
  810. reference_count?: number;
  811. max_references?: number;
  812. roi?: PlateDetectionROI;
  813. }
  814. export interface PlateDetectionStatus {
  815. available: boolean;
  816. calibrated: boolean;
  817. reference_count: number;
  818. max_references: number;
  819. message: string;
  820. }
  821. export interface CalibrationResult {
  822. success: boolean;
  823. message: string;
  824. }
  825. export interface PlateReference {
  826. index: number;
  827. label: string;
  828. timestamp: string;
  829. has_image: boolean;
  830. thumbnail_url: string;
  831. }
  832. // Archive types
  833. export interface ArchiveDuplicate {
  834. id: number;
  835. print_name: string | null;
  836. created_at: string;
  837. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  838. }
  839. export interface ArchivePrinterMediaFile {
  840. name: string;
  841. path: string;
  842. size: number;
  843. mtime: string | null;
  844. kind: 'timelapse' | 'ipcam';
  845. }
  846. export interface ArchivePrinterMedia {
  847. archive_id: number;
  848. printer_id: number | null;
  849. local_timelapse: { name: string; size: number } | null;
  850. remote_files: ArchivePrinterMediaFile[];
  851. warnings: Array<'printer_missing' | 'timelapse_unavailable' | 'ipcam_unavailable' | 'printer_files_forbidden'>;
  852. }
  853. /** A timelapse editor re-encode, run in the background. */
  854. export interface TimelapseJob {
  855. status: 'running' | 'completed' | 'failed' | 'cancelled';
  856. /** Share done, 0 to 1; null before ffmpeg's first report. */
  857. progress: number | null;
  858. output_path: string | null;
  859. message: string | null;
  860. error: string | null;
  861. }
  862. /** How a post-print outcome verdict reached the archive (#1898). */
  863. export type VerdictSource = 'dialog' | 'link' | 'plate_clear' | 'printer_card' | 'api' | 'reaction';
  864. export interface Archive {
  865. id: number;
  866. printer_id: number | null;
  867. project_id: number | null;
  868. project_name: string | null;
  869. filename: string;
  870. file_path: string;
  871. file_size: number;
  872. content_hash: string | null;
  873. thumbnail_path: string | null;
  874. timelapse_path: string | null;
  875. source_3mf_path: string | null;
  876. f3d_path: string | null;
  877. duplicates: ArchiveDuplicate[] | null;
  878. duplicate_count: number;
  879. duplicate_sequence: number; // 0 = original, 1+ = nth duplicate
  880. original_archive_id: number | null; // ID of the first/original archive
  881. object_count: number | null;
  882. print_name: string | null;
  883. plate_id: number | null; // Selected plate of a multi-plate 3MF (#2603)
  884. print_time_seconds: number | null;
  885. actual_time_seconds: number | null; // Computed from started_at/completed_at
  886. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  887. time_estimate_seconds?: number | null; // The latest print's plate estimate, what time_accuracy compares with
  888. filament_used_grams: number | null;
  889. filament_type: string | null;
  890. filament_color: string | null;
  891. layer_height: number | null;
  892. total_layers: number | null;
  893. nozzle_diameter: number | null;
  894. bed_temperature: number | null;
  895. bed_type: string | null; // Build plate type from 3MF (e.g. "Cool Plate", "Textured PEI Plate")
  896. nozzle_temperature: number | null;
  897. sliced_for_model: string | null; // Printer model this file was sliced for
  898. status: string;
  899. started_at: string | null;
  900. completed_at: string | null;
  901. extra_data: Record<string, unknown> | null;
  902. makerworld_url: string | null;
  903. designer: string | null;
  904. external_url: string | null;
  905. is_favorite: boolean;
  906. tags: string | null;
  907. notes: string | null;
  908. cost: number | null;
  909. photos: string[] | null;
  910. failure_reason: string | null;
  911. // Post-print outcome confirmation (#1898)
  912. user_verdict: 'good' | 'reject' | null;
  913. // How the verdict arrived; 'reaction' is written by the Telegram reaction
  914. // handler (#3046) and is labelled here so it reads correctly once that lands.
  915. user_verdict_source: VerdictSource | null;
  916. user_verdict_at: string | null;
  917. confirm_requested: boolean;
  918. // The run whose outcome this shows, when it shows one run of the archive
  919. // (a plate printed on its own) rather than its latest (#1898).
  920. run_id?: number | null;
  921. // The latest print of the archive (among those the caller may see), whose
  922. // figures the per-print fields show (archive redesign).
  923. latest_run_id?: number | null;
  924. // How many videos its prints have; timelapse_path is the latest print's only.
  925. timelapse_count?: number;
  926. quantity: number;
  927. energy_kwh: number | null;
  928. energy_cost: number | null;
  929. wear_cost: number | null; // Printer wear (#694)
  930. created_at: string;
  931. // User tracking (Issue #206)
  932. created_by_id: number | null;
  933. created_by_username: string | null;
  934. // Per-archive run aggregates from PrintLogEntry (#1378)
  935. run_count: number;
  936. last_run_at: string | null;
  937. total_filament_actual_grams: number | null;
  938. successful_run_count: number;
  939. failed_run_count: number;
  940. }
  941. export interface ArchiveSlim {
  942. printer_id: number | null;
  943. print_name: string | null;
  944. print_time_seconds: number | null;
  945. actual_time_seconds: number | null;
  946. filament_used_grams: number | null;
  947. filament_type: string | null;
  948. filament_color: string | null;
  949. status: string;
  950. started_at: string | null;
  951. completed_at: string | null;
  952. cost: number | null;
  953. energy_kwh: number | null;
  954. energy_cost: number | null;
  955. wear_cost: number | null; // Printer wear (#694)
  956. quantity: number;
  957. created_at: string;
  958. }
  959. export interface PrintLogEntry {
  960. id: number;
  961. archive_id: number | null;
  962. print_name: string | null;
  963. plate_id?: number | null;
  964. printer_name: string | null;
  965. printer_id: number | null;
  966. status: string;
  967. started_at: string | null;
  968. completed_at: string | null;
  969. duration_seconds: number | null;
  970. filament_type: string | null;
  971. filament_color: string | null;
  972. filament_used_grams: number | null;
  973. cost: number | null;
  974. energy_kwh: number | null;
  975. energy_cost: number | null;
  976. wear_cost: number | null; // Printer wear (#694)
  977. failure_reason: string | null;
  978. user_verdict?: 'good' | 'reject' | null;
  979. user_verdict_source?: string | null;
  980. confirm_requested?: boolean | null;
  981. duration_unmeasured?: boolean | null;
  982. quantity?: number | null;
  983. // This print's own (archive redesign): note, finish photos, video.
  984. notes?: string | null;
  985. photos?: string[] | null;
  986. timelapse_path?: string | null;
  987. // The slicer's estimate for the plate it printed; in an archive's runs list.
  988. estimate_seconds?: number | null;
  989. estimate_grams?: number | null;
  990. thumbnail_path: string | null;
  991. created_by_id: number | null;
  992. created_by_username: string | null;
  993. created_at: string;
  994. }
  995. export interface PrintLogResponse {
  996. items: PrintLogEntry[];
  997. total: number;
  998. // The print log only: archives of its prints that were deleted.
  999. deleted_archive_ids?: number[];
  1000. }
  1001. export interface ArchiveStats {
  1002. total_prints: number;
  1003. successful_prints: number;
  1004. failed_prints: number;
  1005. cancelled_prints: number;
  1006. total_print_time_hours: number;
  1007. total_filament_grams: number;
  1008. total_cost: number;
  1009. prints_by_filament_type: Record<string, number>;
  1010. prints_by_printer: Record<string, number>;
  1011. // Name each printer id was last recorded under in the print log, so history
  1012. // belonging to a deleted printer keeps its label.
  1013. printer_names?: Record<string, string>;
  1014. average_time_accuracy: number | null;
  1015. time_accuracy_by_printer: Record<string, number> | null;
  1016. total_energy_kwh: number;
  1017. total_energy_cost: number;
  1018. total_wear_cost: number; // Printer wear (#694)
  1019. // True when a date-filtered total-consumption query is running on incomplete
  1020. // snapshot history (e.g. right after upgrade, before hourly snapshots have
  1021. // a baseline). UI should explain why the number may undercount.
  1022. energy_data_warming_up?: boolean;
  1023. }
  1024. export interface TagInfo {
  1025. name: string;
  1026. count: number;
  1027. }
  1028. export interface FailureAnalysis {
  1029. period_days: number;
  1030. total_prints: number;
  1031. failed_prints: number;
  1032. failure_rate: number;
  1033. // Quality dimension (#1898): completed prints the user rejected. Optional
  1034. // so a frontend build against an older backend degrades gracefully.
  1035. rejected_prints?: number;
  1036. yield_rate?: number;
  1037. rejects_by_reason?: Record<string, number>;
  1038. failures_by_reason: Record<string, number>;
  1039. failures_by_filament: Record<string, number>;
  1040. failures_by_printer: Record<string, number>;
  1041. failures_by_hour: Record<number, number>;
  1042. recent_failures: Array<{
  1043. id: number;
  1044. print_name: string;
  1045. failure_reason: string | null;
  1046. filament_type: string | null;
  1047. printer_id: number | null;
  1048. created_at: string | null;
  1049. }>;
  1050. trend: Array<{
  1051. week_start: string;
  1052. total_prints: number;
  1053. failed_prints: number;
  1054. failure_rate: number;
  1055. }>;
  1056. }
  1057. /**
  1058. * Send the browser's zone with calendar dates: the server reads a date as a
  1059. * day in it, else in its own TZ, which shifted every day for a browser away
  1060. * from the server (DB-C12). Only when a date is set.
  1061. */
  1062. function addDayZone(params: URLSearchParams): void {
  1063. if (!params.has('date_from') && !params.has('date_to')) return;
  1064. try {
  1065. const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  1066. if (zone) params.set('tz', zone);
  1067. } catch {
  1068. // No Intl zone: the server's TZ applies.
  1069. }
  1070. }
  1071. export interface BulkUploadResult {
  1072. uploaded: number;
  1073. failed: number;
  1074. /** `index` is the file's position in the request. */
  1075. results: Array<{ index: number; filename: string; id: number; status: string }>;
  1076. errors: Array<{ index: number; filename: string; error: string }>;
  1077. }
  1078. // Archive Comparison types
  1079. export interface ComparisonArchiveInfo {
  1080. id: number;
  1081. print_name: string;
  1082. status: string;
  1083. created_at: string | null;
  1084. printer_id: number | null;
  1085. project_name: string | null;
  1086. }
  1087. export interface ComparisonField {
  1088. field: string;
  1089. label: string;
  1090. unit: string | null;
  1091. values: (string | number | null)[];
  1092. raw_values: (string | number | null)[];
  1093. has_difference: boolean;
  1094. }
  1095. export interface SuccessCorrelationInsight {
  1096. field: string;
  1097. label: string;
  1098. insight: string;
  1099. success_avg?: number;
  1100. failed_avg?: number;
  1101. success_values?: string[];
  1102. failed_values?: string[];
  1103. }
  1104. export interface SuccessCorrelation {
  1105. has_both_outcomes: boolean;
  1106. message?: string;
  1107. successful_count?: number;
  1108. failed_count?: number;
  1109. insights?: SuccessCorrelationInsight[];
  1110. }
  1111. export interface ArchiveComparison {
  1112. archives: ComparisonArchiveInfo[];
  1113. comparison: ComparisonField[];
  1114. differences: ComparisonField[];
  1115. success_correlation: SuccessCorrelation;
  1116. }
  1117. // Project types
  1118. export interface ProjectStats {
  1119. total_archives: number;
  1120. total_items: number; // Sum of quantities (total items printed)
  1121. completed_prints: number; // Sum of quantities for completed prints (parts)
  1122. failed_prints: number;
  1123. queued_prints: number;
  1124. in_progress_prints: number;
  1125. total_print_time_hours: number;
  1126. total_filament_grams: number;
  1127. progress_percent: number | null; // Plates progress (total_archives / target_count)
  1128. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  1129. estimated_cost: number;
  1130. total_energy_kwh: number;
  1131. total_energy_cost: number;
  1132. total_wear_cost: number; // Printer wear (#694)
  1133. remaining_prints: number | null; // Remaining plates
  1134. remaining_parts: number | null; // Remaining parts
  1135. bom_total_items: number;
  1136. bom_completed_items: number;
  1137. bom_cost: number;
  1138. }
  1139. // A sub-project as listed on its parent's page. The figures cover the child's
  1140. // own subtree, so the listed rows add up to the parent's roll-up minus the
  1141. // parent's own prints (#1264).
  1142. export interface ProjectChildPreview {
  1143. id: number;
  1144. name: string;
  1145. color: string | null;
  1146. status: string;
  1147. progress_percent: number | null;
  1148. descendant_count: number;
  1149. total_archives: number;
  1150. completed_prints: number;
  1151. total_print_time_hours: number;
  1152. total_filament_grams: number;
  1153. total_cost: number; // Filament + energy + BOM, matching the parent's cost card
  1154. }
  1155. export interface Project {
  1156. id: number;
  1157. name: string;
  1158. description: string | null;
  1159. color: string | null;
  1160. status: string; // active, completed, archived
  1161. target_count: number | null; // Target number of plates/print jobs
  1162. target_parts_count: number | null; // Target number of parts/objects
  1163. target_sets: number | null; // Copies-per-file target (#1897)
  1164. notes: string | null;
  1165. attachments: ProjectAttachment[] | null;
  1166. tags: string | null;
  1167. due_date: string | null;
  1168. priority: string; // low, normal, high, urgent
  1169. budget: number | null;
  1170. is_template: boolean;
  1171. template_source_id: number | null;
  1172. parent_id: number | null;
  1173. parent_name: string | null;
  1174. children: ProjectChildPreview[];
  1175. descendant_count: number; // Sub-projects at any depth beneath this one (#1264)
  1176. created_at: string;
  1177. updated_at: string;
  1178. stats?: ProjectStats;
  1179. // This project's numbers combined with every sub-project's. Null when there
  1180. // are none, since it would only repeat `stats` (#1264).
  1181. rollup_stats?: ProjectStats | null;
  1182. url: string | null; // External link rendered next to project name on the card (#1155)
  1183. cover_image_filename: string | null; // Filename within project attachments dir (#1155)
  1184. }
  1185. export interface ProjectAttachment {
  1186. filename: string;
  1187. original_name: string;
  1188. size: number;
  1189. uploaded_at: string;
  1190. }
  1191. // Completed-run count for one library file inside a project (#1897)
  1192. export interface ProjectFileProgress {
  1193. file_id: number;
  1194. completed_count: number;
  1195. }
  1196. export interface ArchivePreview {
  1197. id: number;
  1198. print_name: string | null;
  1199. thumbnail_path: string | null;
  1200. status: string;
  1201. filament_type: string | null;
  1202. filament_color: string | null;
  1203. }
  1204. export interface ProjectListItem {
  1205. id: number;
  1206. name: string;
  1207. description: string | null;
  1208. color: string | null;
  1209. status: string;
  1210. target_count: number | null; // Target number of plates/print jobs
  1211. target_parts_count: number | null; // Target number of parts/objects
  1212. target_sets: number | null; // #1897 — the shared edit dialog seeds itself from this
  1213. budget: number | null;
  1214. tags: string | null; // #2536 — the shared edit dialog seeds itself from this
  1215. due_date: string | null; // #2536
  1216. priority: string; // #2536
  1217. created_at: string;
  1218. archive_count: number; // Number of print jobs (plates)
  1219. total_items: number; // Sum of quantities (total items printed, including failed)
  1220. completed_count: number; // Sum of quantities for completed prints only (parts)
  1221. failed_count: number; // Sum of quantities for failed prints
  1222. queue_count: number;
  1223. progress_percent: number | null; // Plates progress
  1224. parent_id: number | null; // #1264 — set when this is a sub-project
  1225. child_count: number; // #1264 — direct sub-projects only
  1226. archives: ArchivePreview[];
  1227. url: string | null; // #1155
  1228. cover_image_filename: string | null; // #1155
  1229. }
  1230. export interface ProjectCreate {
  1231. name: string;
  1232. description?: string;
  1233. color?: string;
  1234. target_count?: number;
  1235. target_parts_count?: number;
  1236. target_sets?: number;
  1237. notes?: string;
  1238. tags?: string;
  1239. due_date?: string;
  1240. priority?: string;
  1241. budget?: number | null;
  1242. parent_id?: number;
  1243. url?: string | null; // #1155
  1244. }
  1245. export interface ProjectUpdate {
  1246. name?: string;
  1247. description?: string;
  1248. color?: string;
  1249. status?: string;
  1250. target_count?: number;
  1251. target_parts_count?: number;
  1252. target_sets?: number | null; // #1897 — explicit null clears the copies-per-file target
  1253. notes?: string;
  1254. tags?: string | null; // #2536 — explicit null clears the tags
  1255. due_date?: string | null; // #2536 — explicit null clears the due date
  1256. priority?: string;
  1257. budget?: number | null;
  1258. parent_id?: number;
  1259. url?: string | null; // #1155 — explicit null clears the URL
  1260. }
  1261. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  1262. export interface BOMItem {
  1263. id: number;
  1264. project_id: number;
  1265. name: string;
  1266. quantity_needed: number;
  1267. quantity_acquired: number;
  1268. unit_price: number | null;
  1269. sourcing_url: string | null;
  1270. archive_id: number | null;
  1271. archive_name: string | null;
  1272. stl_filename: string | null;
  1273. remarks: string | null;
  1274. sort_order: number;
  1275. is_complete: boolean;
  1276. created_at: string;
  1277. updated_at: string;
  1278. }
  1279. export interface BOMItemCreate {
  1280. name: string;
  1281. quantity_needed?: number;
  1282. unit_price?: number;
  1283. sourcing_url?: string;
  1284. archive_id?: number;
  1285. stl_filename?: string;
  1286. remarks?: string;
  1287. }
  1288. export interface BOMItemUpdate {
  1289. name?: string;
  1290. quantity_needed?: number;
  1291. quantity_acquired?: number;
  1292. unit_price?: number;
  1293. sourcing_url?: string;
  1294. archive_id?: number;
  1295. stl_filename?: string;
  1296. remarks?: string;
  1297. }
  1298. // Project Export/Import Types
  1299. export interface BOMItemExport {
  1300. name: string;
  1301. quantity_needed: number;
  1302. quantity_acquired: number;
  1303. unit_price: number | null;
  1304. sourcing_url: string | null;
  1305. stl_filename: string | null;
  1306. remarks: string | null;
  1307. }
  1308. export interface LinkedFolderExport {
  1309. name: string;
  1310. }
  1311. export interface ProjectExport {
  1312. name: string;
  1313. description: string | null;
  1314. color: string | null;
  1315. status: string;
  1316. target_count: number | null;
  1317. target_parts_count: number | null;
  1318. target_sets: number | null; // #1897
  1319. notes: string | null;
  1320. tags: string | null;
  1321. due_date: string | null;
  1322. priority: string;
  1323. budget: number | null;
  1324. bom_items: BOMItemExport[];
  1325. linked_folders: LinkedFolderExport[];
  1326. }
  1327. export interface ProjectImport {
  1328. name: string;
  1329. description?: string;
  1330. color?: string;
  1331. status?: string;
  1332. target_count?: number;
  1333. target_parts_count?: number;
  1334. target_sets?: number; // #1897
  1335. notes?: string;
  1336. tags?: string;
  1337. due_date?: string;
  1338. priority?: string;
  1339. budget?: number | null;
  1340. bom_items?: BOMItemExport[];
  1341. linked_folders?: LinkedFolderExport[];
  1342. }
  1343. // Timeline Types
  1344. export interface TimelineEvent {
  1345. event_type: string;
  1346. timestamp: string;
  1347. title: string;
  1348. description: string | null;
  1349. metadata: Record<string, unknown> | null;
  1350. }
  1351. // API Key types
  1352. export interface APIKey {
  1353. id: number;
  1354. name: string;
  1355. key_prefix: string;
  1356. user_id: number | null; // Owner; null on legacy keys created before per-user ownership (#1182)
  1357. can_queue: boolean;
  1358. can_control_printer: boolean;
  1359. can_read_status: boolean;
  1360. can_manage_library: boolean;
  1361. can_manage_inventory: boolean;
  1362. can_manage_maintenance: boolean;
  1363. can_manage_archives: boolean;
  1364. can_manage_projects: boolean;
  1365. can_access_cloud: boolean;
  1366. can_update_energy_cost: boolean;
  1367. can_send_notifications: boolean;
  1368. printer_ids: number[] | null;
  1369. enabled: boolean;
  1370. last_used: string | null;
  1371. created_at: string;
  1372. expires_at: string | null;
  1373. }
  1374. export interface APIKeyCreate {
  1375. name: string;
  1376. can_queue?: boolean;
  1377. can_control_printer?: boolean;
  1378. can_read_status?: boolean;
  1379. can_manage_library?: boolean;
  1380. can_manage_inventory?: boolean;
  1381. can_manage_maintenance?: boolean;
  1382. can_manage_archives?: boolean;
  1383. can_manage_projects?: boolean;
  1384. can_access_cloud?: boolean;
  1385. can_update_energy_cost?: boolean;
  1386. can_send_notifications?: boolean;
  1387. printer_ids?: number[] | null;
  1388. expires_at?: string | null;
  1389. }
  1390. export interface APIKeyCreateResponse extends APIKey {
  1391. key: string; // Full key, only shown on creation
  1392. }
  1393. /**
  1394. * Tri-state calibration option (BambuStudio parity): "off" never runs it,
  1395. * "on" forces it every print, "auto" lets the printer skip it if it was done
  1396. * recently. Used by bed_levelling, flow_cali, and nozzle_offset_cali.
  1397. */
  1398. export type CalibrationMode = 'off' | 'on' | 'auto';
  1399. // Settings types
  1400. export type ModelDispatchOrder = 'fewest_hours' | 'most_hours' | 'least_recently_used' | 'priority';
  1401. export interface AppSettings {
  1402. auto_archive: boolean;
  1403. save_thumbnails: boolean;
  1404. capture_finish_photo: boolean;
  1405. finish_photo_restore_plate: boolean;
  1406. default_filament_cost: number;
  1407. currency: string;
  1408. energy_cost_per_kwh: number;
  1409. energy_tracking_mode: 'print' | 'total';
  1410. // Where the electricity price comes from (#1251). With 'homeassistant',
  1411. // energy_cost_per_kwh holds the sensor's last reading and is read-only.
  1412. energy_price_source: 'fixed' | 'homeassistant';
  1413. energy_price_ha_entity: string;
  1414. check_updates: boolean;
  1415. check_printer_firmware: boolean;
  1416. include_beta_updates: boolean;
  1417. // Announcements from the Bambuddy maintainers (a signed file on GitHub).
  1418. announcements_enabled?: boolean;
  1419. announcements_all_users?: boolean;
  1420. // #1589: false hides the local username/password form on the login page;
  1421. // BAMBUDDY_LOCAL_LOGIN=true on the server flips the reported value back to
  1422. // true so the env-var recovery path is visible to the SPA.
  1423. local_login_enabled: boolean;
  1424. language: string;
  1425. notification_language: string;
  1426. // AMS threshold settings
  1427. ams_humidity_good: number; // <= this is green
  1428. ams_humidity_fair: number; // <= this is orange, > is red
  1429. ams_temp_good: number; // <= this is green/blue
  1430. ams_temp_fair: number; // <= this is orange, > is red
  1431. // Separate from the display band (#2905). null = unset, which the backend
  1432. // resolves to ams_temp_fair so existing installs are unaffected.
  1433. ams_temp_alarm: number | null;
  1434. ams_history_retention_days: number; // days to keep AMS sensor history
  1435. printer_sensor_history_retention_days?: number; // days to keep printer heater history
  1436. // Queue auto-drying settings
  1437. queue_drying_enabled: boolean; // Auto-dry AMS between queued prints
  1438. queue_drying_block: boolean; // Block queue until drying completes
  1439. ambient_drying_enabled: boolean; // Auto-dry idle printers based on humidity regardless of queue
  1440. ambient_drying_sustained_minutes: number; // Minutes humidity must stay above threshold before ambient auto-dry starts (0 = instant)
  1441. print_drying_enabled: boolean; // Continue drying while a print is running on capable hardware
  1442. drying_presets: string; // JSON blob of drying presets per filament type
  1443. ams_humidity_thresholds: string; // JSON blob of per-filament humidity thresholds (#1605)
  1444. gcode_snippets: string; // JSON: per-model G-code injection snippets
  1445. // Scheduled local backup
  1446. local_backup_enabled: boolean;
  1447. local_backup_schedule: string;
  1448. local_backup_time: string;
  1449. local_backup_retention: number;
  1450. local_backup_path: string;
  1451. // Print modal settings
  1452. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  1453. // Date/time format settings
  1454. date_format: 'system' | 'us' | 'eu' | 'iso';
  1455. time_format: 'system' | '12h' | '24h';
  1456. // Filament tracking
  1457. disable_filament_warnings: boolean; // Disable filament warnings (print insufficiency and assignment mismatch)
  1458. prefer_lowest_filament: boolean; // When multiple spools match, prefer lowest remaining filament
  1459. 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
  1460. 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
  1461. spoolman_url: string;
  1462. // Default printer
  1463. default_printer_id: number | null;
  1464. pipeline_max_copies: number;
  1465. // Dark mode theme settings
  1466. dark_style: 'classic' | 'glow' | 'vibrant';
  1467. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  1468. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1469. // Light mode theme settings
  1470. light_style: 'classic' | 'glow' | 'vibrant';
  1471. light_background: 'neutral' | 'warm' | 'cool';
  1472. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  1473. // FTP retry settings
  1474. ftp_retry_enabled: boolean;
  1475. ftp_retry_count: number;
  1476. ftp_retry_delay: number;
  1477. ftp_timeout: number;
  1478. // MQTT relay settings
  1479. mqtt_enabled: boolean;
  1480. mqtt_broker: string;
  1481. mqtt_port: number;
  1482. mqtt_username: string;
  1483. mqtt_password: string;
  1484. mqtt_topic_prefix: string;
  1485. mqtt_use_tls: boolean;
  1486. // BIQU Panda Breath heaters on the same broker (#1466)
  1487. panda_breath_enabled: boolean;
  1488. // External URL for notifications
  1489. external_url: string;
  1490. // Directory holding docker-compose.yml, shown in the update instructions (#2664)
  1491. docker_compose_dir: string;
  1492. // Home Assistant integration
  1493. ha_enabled: boolean;
  1494. ha_url: string;
  1495. ha_token: string;
  1496. ha_url_from_env: boolean;
  1497. ha_token_from_env: boolean;
  1498. ha_env_managed: boolean;
  1499. // File Manager / Library settings
  1500. library_disk_warning_gb: number;
  1501. // Camera view settings
  1502. camera_view_mode: 'window' | 'embedded';
  1503. // Chamber light while the camera is in use (#1655)
  1504. camera_light_mode: 'off' | 'all' | 'selected';
  1505. camera_light_delay: number; // seconds a snapshot waits after the light came on
  1506. // Preferred slicer (server-side API / sidecar)
  1507. preferred_slicer: 'bambu_studio' | 'orcaslicer';
  1508. // Desktop "Open in Slicer" override (#1329). Null inherits from
  1509. // preferred_slicer so existing installs behave identically.
  1510. open_in_slicer: 'bambu_studio' | 'orcaslicer' | null;
  1511. // Where slicing runs, independent of which slicer binary the sidecar drives.
  1512. // Only 'sidecar' is implemented today; see lib/sliceEngines.ts.
  1513. slice_engine: 'sidecar' | 'browser';
  1514. // Use the slicer-API sidecar for slicing (in-app modal) vs desktop URI scheme
  1515. use_slicer_api: boolean;
  1516. // Per-install sidecar URLs. Empty string falls back to the env defaults.
  1517. orcaslicer_api_url: string;
  1518. bambu_studio_api_url: string;
  1519. // Minutes of silence from the sidecar before a slice is abandoned. Bounds
  1520. // stalls, not total slicing time — a model that keeps reporting progress
  1521. // runs to completion however long it takes.
  1522. slicer_stall_timeout_minutes: number;
  1523. // Prometheus metrics
  1524. prometheus_enabled: boolean;
  1525. prometheus_token: string;
  1526. // Bed cooled threshold
  1527. bed_cooled_threshold: number;
  1528. // Minutes before a slicer pause to send the pause heads-up (#2984)
  1529. pause_warning_minutes: number;
  1530. // Inventory low stock threshold
  1531. low_stock_threshold: number;
  1532. // Session policy (#1706) — admin-set ceiling, hours, [1, 720]
  1533. session_max_hours: number;
  1534. // User email notifications toggle
  1535. user_notifications_enabled: boolean;
  1536. // Default print options
  1537. default_bed_levelling: CalibrationMode;
  1538. default_flow_cali: CalibrationMode;
  1539. default_vibration_cali: boolean;
  1540. default_layer_inspect: boolean;
  1541. default_timelapse: boolean;
  1542. default_nozzle_offset_cali: CalibrationMode;
  1543. // Default for the per-job "ask for outcome afterwards" toggle (#1898)
  1544. default_confirm_outcome: boolean;
  1545. // Also ask for prints Bambuddy archived but did not dispatch (#1898)
  1546. confirm_outcome_external_prints: boolean;
  1547. // Count unanswered outcome prompts as "good" when the plate is released (#1898)
  1548. confirm_default_good_on_plate_clear: boolean;
  1549. // Staggered batch start defaults
  1550. stagger_group_size: number;
  1551. stagger_interval_minutes: number;
  1552. // Finance budget reset window
  1553. billing_enabled: boolean;
  1554. printer_kill_switch_enabled: boolean;
  1555. finance_budget_reset_day: number;
  1556. finance_budget_reset_timezone: string;
  1557. // Plate-clear confirmation
  1558. require_plate_clear: boolean;
  1559. // Shortest job first scheduling
  1560. queue_shortest_first: boolean;
  1561. // Which printer an any-model job takes when several can run it (#2915).
  1562. model_dispatch_order: ModelDispatchOrder;
  1563. // How many printers the queue may upload to at once (#2555). 1 restores the
  1564. // old strictly-serial behaviour, where every printer waited out every other
  1565. // printer's transfer.
  1566. queue_max_concurrent_uploads: number;
  1567. // Preheat / heat-soak before queued prints (#1468). Master toggle is the
  1568. // default for new queue items; per-item PrintQueueItem.preheat_override can
  1569. // flip the decision per print. Chamber target derives from the loaded AMS
  1570. // filament types via preheat_filament_targets (JSON map of type → °C, max
  1571. // across loaded slots); the per-item override field bypasses derivation.
  1572. preheat_enabled: boolean;
  1573. preheat_filament_targets: string;
  1574. preheat_max_wait_seconds: number;
  1575. preheat_soak_seconds: number;
  1576. queue_keep_bed_warm: boolean;
  1577. queue_keep_warm_bed_temp: number;
  1578. queue_keep_warm_max_minutes: number;
  1579. // User-configurable presets for the printer-card popovers (JSON arrays of 3 ints).
  1580. // Empty string = use built-in defaults.
  1581. nozzle_temp_presets: string;
  1582. bed_temp_presets: string;
  1583. chamber_temp_presets: string;
  1584. fan_speed_presets: string;
  1585. // Default sidebar order (admin-set for all users)
  1586. default_sidebar_order: string;
  1587. // LDAP authentication
  1588. ldap_enabled: boolean;
  1589. ldap_server_url: string;
  1590. ldap_bind_dn: string;
  1591. ldap_bind_password: string;
  1592. ldap_search_base: string;
  1593. ldap_user_filter: string;
  1594. ldap_security: string;
  1595. ldap_group_mapping: string;
  1596. ldap_auto_provision: boolean;
  1597. ldap_default_group: string;
  1598. obico_enabled: boolean;
  1599. obico_ml_url: string;
  1600. bambuddy_internal_url: string;
  1601. obico_ml_token: string;
  1602. obico_sensitivity: 'low' | 'medium' | 'high';
  1603. obico_action: 'notify' | 'pause' | 'pause_and_off';
  1604. obico_poll_interval: number;
  1605. obico_enabled_printers: string;
  1606. octoeverywhere_enabled: boolean;
  1607. octoeverywhere_api_key: string;
  1608. octoeverywhere_api_key_configured: boolean;
  1609. octoeverywhere_confidence: OctoEverywhereConfidence;
  1610. octoeverywhere_action: 'notify' | 'pause' | 'pause_and_off';
  1611. octoeverywhere_enabled_printers: string;
  1612. octoeverywhere_poll_interval: number;
  1613. // Inventory forecasting global lead time
  1614. forecast_global_lead_time_days: number;
  1615. location_sensor_poll_interval: number;
  1616. // JSON map of sensor category → {alertAbove, alertBelow, notifyOnAlert},
  1617. // seeding new storage-location sensor bindings. Empty = built-in defaults.
  1618. // Server-backed so two admins seed the same alert rules and a restore
  1619. // brings them back; see utils/locationSensorDefaults.ts.
  1620. location_sensor_alert_defaults: string;
  1621. }
  1622. export type AppSettingsUpdate = Partial<Omit<AppSettings, 'octoeverywhere_api_key_configured'>>;
  1623. // Settings as a page sees them: everything from GET /settings for a user who
  1624. // may read it, otherwise the subset /settings/ui-preferences and
  1625. // /settings/ui-flags serve, which reports G-code snippets only as set or not.
  1626. export type UiSettings = Partial<AppSettings> & { has_gcode_snippets?: boolean };
  1627. // MQTT relay status
  1628. export interface MQTTStatus {
  1629. enabled: boolean;
  1630. connected: boolean;
  1631. broker: string;
  1632. port: number;
  1633. topic_prefix: string;
  1634. }
  1635. // Cloud types
  1636. export interface CloudAuthStatus {
  1637. is_authenticated: boolean;
  1638. email: string | null;
  1639. region?: 'global' | 'china' | null;
  1640. /** A token is stored but Bambu no longer accepts it — tell the user why the login form is back. */
  1641. sign_in_expired?: boolean;
  1642. }
  1643. export interface CloudLoginResponse {
  1644. success: boolean;
  1645. needs_verification: boolean;
  1646. message: string;
  1647. verification_type?: 'email' | 'totp' | null;
  1648. tfa_key?: string | null;
  1649. /**
  1650. * Machine-readable cause of a failure. 'captcha' means Bambu's anti-abuse
  1651. * layer is challenging this network and no credential will be accepted until
  1652. * it clears — the UI must explain that in place rather than toast `message`.
  1653. */
  1654. reason?: 'captcha' | string | null;
  1655. }
  1656. // Orca Cloud types — paste-flow PKCE handshake against auth.orcaslicer.com.
  1657. // See backend/app/services/orca_cloud.py for the deep dive on why this
  1658. // flow is paste-based rather than callback-based.
  1659. export interface OrcaDeviceStartResponse {
  1660. user_code: string;
  1661. verification_uri: string;
  1662. verification_uri_complete: string;
  1663. interval: number;
  1664. expires_in: number;
  1665. }
  1666. export type OrcaDevicePollStatus =
  1667. | 'authorization_pending'
  1668. | 'slow_down'
  1669. | 'access_denied'
  1670. | 'expired_token'
  1671. | 'complete';
  1672. export interface OrcaDevicePollResponse {
  1673. status: OrcaDevicePollStatus;
  1674. connected: boolean;
  1675. email: string | null;
  1676. user_id: string | null;
  1677. }
  1678. export interface OrcaAuthStatusResponse {
  1679. connected: boolean;
  1680. email: string | null;
  1681. user_id: string | null;
  1682. }
  1683. // Orca profiles are shaped to match Bambu Cloud's SlicerSetting on the wire
  1684. // so the frontend can use the same visual components for both surfaces (cards,
  1685. // grouped sections, filter bar). Backend handles the source-specific
  1686. // transformation in routes/orca_cloud.py::_orca_to_setting.
  1687. export interface OrcaProfileMeta {
  1688. setting_id: string;
  1689. name: string;
  1690. type: string;
  1691. version: string | null;
  1692. user_id: string | null;
  1693. updated_time: string | null;
  1694. is_custom: boolean;
  1695. }
  1696. export interface OrcaProfileListResponse {
  1697. filament: OrcaProfileMeta[];
  1698. printer: OrcaProfileMeta[];
  1699. process: OrcaProfileMeta[];
  1700. }
  1701. export interface OrcaProfileDetail {
  1702. setting_id: string;
  1703. name: string;
  1704. type: string;
  1705. version: string | null;
  1706. base_id: string | null;
  1707. update_time: string | null;
  1708. setting: Record<string, unknown>;
  1709. }
  1710. // MakerWorld integration. Full metadata/instance shapes come back as
  1711. // Record<string, unknown> — MakerWorld's API adds fields over time, so we
  1712. // pass them through verbatim rather than maintaining a brittle mirror.
  1713. export interface MakerworldStatus {
  1714. has_cloud_token: boolean;
  1715. can_download: boolean;
  1716. /** A token is stored but Bambu rejected it — downloads will fail until the user signs in again. */
  1717. sign_in_expired?: boolean;
  1718. }
  1719. export interface MakerworldResolvedModel {
  1720. model_id: number;
  1721. profile_id: number | null;
  1722. design: Record<string, unknown>;
  1723. instances: Array<Record<string, unknown>>;
  1724. already_imported_library_ids: number[];
  1725. }
  1726. export interface MakerworldImportResponse {
  1727. library_file_id: number;
  1728. filename: string;
  1729. folder_id: number | null;
  1730. profile_id: number | null;
  1731. was_existing: boolean;
  1732. }
  1733. export interface MakerworldRecentImport {
  1734. library_file_id: number;
  1735. filename: string;
  1736. folder_id: number | null;
  1737. thumbnail_path: string | null;
  1738. source_url: string | null;
  1739. created_at: string;
  1740. }
  1741. // Manyfold integration (#1471): a self-hosted model library, browsed and
  1742. // searched, with single files imported into the library.
  1743. export interface ManyfoldConfig {
  1744. url: string;
  1745. client_id: string;
  1746. /** The secret itself is never returned. */
  1747. has_client_secret: boolean;
  1748. configured: boolean;
  1749. }
  1750. export interface ManyfoldConfigInput {
  1751. url: string;
  1752. client_id: string;
  1753. /** Empty or left out keeps the stored secret. */
  1754. client_secret?: string;
  1755. }
  1756. export interface ManyfoldStatus {
  1757. configured: boolean;
  1758. url: string;
  1759. }
  1760. export interface ManyfoldModelSummary {
  1761. id: string;
  1762. name: string;
  1763. }
  1764. export interface ManyfoldModelList {
  1765. total: number;
  1766. page: number;
  1767. has_next: boolean;
  1768. has_previous: boolean;
  1769. models: ManyfoldModelSummary[];
  1770. }
  1771. export interface ManyfoldFile {
  1772. id: string;
  1773. name: string;
  1774. mime: string;
  1775. importable: boolean;
  1776. /** Set while the file imported earlier is still in the library. */
  1777. library_file: { id: number; filename: string; folder_id: number | null } | null;
  1778. }
  1779. export interface ManyfoldModel {
  1780. id: string;
  1781. name: string;
  1782. caption: string | null;
  1783. description: string | null;
  1784. license: string | null;
  1785. tags: string[];
  1786. url: string;
  1787. has_preview: boolean;
  1788. files: ManyfoldFile[];
  1789. }
  1790. export interface ManyfoldImportResponse {
  1791. library_file_id: number;
  1792. filename: string;
  1793. folder_id: number | null;
  1794. was_existing: boolean;
  1795. }
  1796. export interface SlicerSetting {
  1797. setting_id: string;
  1798. name: string;
  1799. type: string;
  1800. version: string | null;
  1801. user_id: string | null;
  1802. updated_time: string | null;
  1803. is_custom: boolean;
  1804. // The id Bambu Studio puts in an AMS slot for the preset; not derivable
  1805. // from setting_id for every preset (#3387). Absent from older backends.
  1806. filament_id?: string | null;
  1807. }
  1808. export interface SpoolCatalogEntry {
  1809. id: number;
  1810. name: string;
  1811. weight: number;
  1812. is_default: boolean;
  1813. }
  1814. export interface StorageLocation {
  1815. id: number;
  1816. name: string;
  1817. identifier: string | null;
  1818. spool_count: number;
  1819. created_at: string;
  1820. updated_at: string;
  1821. }
  1822. export interface ColorCatalogEntry {
  1823. id: number;
  1824. manufacturer: string;
  1825. color_name: string;
  1826. hex_color: string;
  1827. material: string | null;
  1828. is_default: boolean;
  1829. // #1154: optional multi-colour gradient stops + visual effect.
  1830. extra_colors?: string | null;
  1831. effect_type?: string | null;
  1832. }
  1833. export interface SlicerSettingsResponse {
  1834. filament: SlicerSetting[];
  1835. printer: SlicerSetting[];
  1836. process: SlicerSetting[];
  1837. }
  1838. export interface SlicerSettingDetail {
  1839. message?: string | null;
  1840. code?: string | null;
  1841. error?: string | null;
  1842. public: boolean;
  1843. version?: string | null;
  1844. type: string;
  1845. name: string;
  1846. update_time?: string | null;
  1847. nickname?: string | null;
  1848. base_id?: string | null;
  1849. setting: Record<string, unknown>;
  1850. filament_id?: string | null;
  1851. setting_id?: string | null;
  1852. }
  1853. export interface SlicerSettingCreate {
  1854. type: string; // 'filament', 'print', or 'printer'
  1855. name: string;
  1856. base_id: string;
  1857. setting: Record<string, unknown>;
  1858. }
  1859. export interface SlicerSettingUpdate {
  1860. name?: string;
  1861. setting?: Record<string, unknown>;
  1862. }
  1863. export interface SlicerSettingDeleteResponse {
  1864. success: boolean;
  1865. message: string;
  1866. }
  1867. // Built-in filament fallback (static table from backend)
  1868. export interface BuiltinFilament {
  1869. filament_id: string;
  1870. name: string;
  1871. }
  1872. // Slice request/response — POST /library/files/{id}/slice and /archives/{id}/slice
  1873. //
  1874. // Two preset shapes are accepted per slot:
  1875. // - Legacy bare integer ids (`*_preset_id`) — pre-cloud-tier clients.
  1876. // - Source-aware refs (`*_preset: PresetRef`) — new SliceModal that picks
  1877. // across cloud / local / standard tiers. Source-aware refs win when both
  1878. // are present in the same payload.
  1879. export type PresetSource = 'orca_cloud' | 'cloud' | 'local' | 'standard';
  1880. export interface PresetRef {
  1881. source: PresetSource;
  1882. id: string;
  1883. }
  1884. /**
  1885. * Why a preset's effective values are unavailable.
  1886. *
  1887. * `sidecar_outdated` is the one that matters in practice: an install pulls its
  1888. * sidecar as `SIDECAR_TAG:-latest` regardless of which Bambuddy channel it is
  1889. * on, so a user can perfectly well be running a current Bambuddy against a
  1890. * sidecar that predates this endpoint. That has a one-line fix, and saying so
  1891. * beats a generic "could not read the values".
  1892. */
  1893. export type SlicerPresetValuesReason =
  1894. | 'ok'
  1895. | 'sidecar_outdated'
  1896. | 'sidecar_unavailable'
  1897. | 'not_configured'
  1898. | 'preset_unresolved';
  1899. export interface SlicerPresetValues {
  1900. /** False when the sidecar could not supply values; `values` is then empty. */
  1901. resolved: boolean;
  1902. /** Flattened key -> value map, in the string forms a process preset stores. */
  1903. values: Record<string, string | string[]>;
  1904. reason: SlicerPresetValuesReason;
  1905. }
  1906. export interface SliceRequest {
  1907. printer_preset_id?: number;
  1908. process_preset_id?: number;
  1909. filament_preset_id?: number;
  1910. printer_preset?: PresetRef;
  1911. process_preset?: PresetRef;
  1912. filament_preset?: PresetRef;
  1913. // Multi-color: one PresetRef per plate slot, in plate order. Always
  1914. // preferred over the singular `filament_preset` when both are sent; the
  1915. // backend validator promotes a singular into a one-element list when this
  1916. // is omitted, so legacy single-color clients keep working unchanged.
  1917. filament_presets?: PresetRef[];
  1918. // Per-slot filament colour as `#RRGGBB` / `#RRGGBBAA`, same plate order as
  1919. // `filament_presets` (#2977). Neither slicer stores a colour on a filament
  1920. // *preset* -- it is a per-project property -- so without this every sliced
  1921. // file records the CLI's built-in #00AE42 and the print dialog reports a
  1922. // colour mismatch against whatever is loaded in the AMS. An empty string in
  1923. // any position hands that slot back to the backend's fallback chain (the
  1924. // preset's own default_filament_colour, then the source plate's colour).
  1925. filament_colours?: string[];
  1926. plate?: number;
  1927. export_3mf?: boolean;
  1928. // Build-plate override (#1337). When omitted, the slicer uses the process
  1929. // preset's curr_bed_type as-is. A name from BambuStudio / OrcaSlicer's
  1930. // enum: "Cool Plate", "Engineering Plate", "High Temp Plate" (Smooth PEI),
  1931. // "Textured PEI Plate", "Supertack Plate", or OrcaSlicer's "Textured Cool
  1932. // Plate" (refused when Bambu Studio slices); the backend refuses others (#3359).
  1933. bed_type?: string | null;
  1934. // "Slice as designed" (#2611). 3MF only: slice using the file's embedded
  1935. // project_settings.config (the designer's own wall count, infill, etc.)
  1936. // instead of the picked profile triplet. The preset refs above are still
  1937. // required by the backend validator but go unused on this path.
  1938. use_embedded_settings?: boolean;
  1939. // Process settings the user edited in the slice modal's settings panel,
  1940. // already serialised into the string forms a process preset stores ("1" for
  1941. // a bool, "20%" for a percent, a list for the per-extruder vectors). Patched
  1942. // onto the resolved process JSON after the designer's carried tweaks, so an
  1943. // explicit choice here wins. Omitted when the panel is untouched.
  1944. process_overrides?: Record<string, string | string[]>;
  1945. // Design settings carried from the source 3MF (#2622) — a list of keys the
  1946. // file flags as changed from the system preset, not values.
  1947. design_overrides?: string[];
  1948. // Layout passes the slicer runs before slicing (#2548), both off by
  1949. // default because they move or rotate the objects the user laid out.
  1950. // Unlike the fields above these are CLI actions rather than profile
  1951. // values, so they apply on the embedded-settings path too.
  1952. auto_orient?: boolean;
  1953. auto_arrange?: boolean;
  1954. }
  1955. // GET /api/v1/slicer/presets — unified listing across cloud / local / standard.
  1956. export type SlicerCloudStatus = 'ok' | 'not_authenticated' | 'expired' | 'unreachable';
  1957. export interface UnifiedPreset {
  1958. id: string;
  1959. name: string;
  1960. source: PresetSource;
  1961. // Populated for the filament slot only — used by the SliceModal multi-color
  1962. // pre-pick to score presets against each plate slot's required (type,
  1963. // colour). Optional because the bundled / standard tier rarely carries a
  1964. // colour (colour is a runtime spool attribute on Bambu) and older API
  1965. // responses pre-date these fields entirely.
  1966. filament_type?: string | null;
  1967. filament_colour?: string | null;
  1968. // Printer-preset names a process / filament preset declares itself
  1969. // compatible with. Populated for the local tier (the slicer's own
  1970. // `compatible_printers`); null for cloud / standard. The SliceModal filters
  1971. // the process / filament dropdowns by the selected printer using this when
  1972. // present (#1325).
  1973. compatible_printers?: string[] | null;
  1974. // Printer presets only: the preset it was saved from, for the local and
  1975. // OrcaSlicer Cloud tiers (#3250).
  1976. inherits?: string | null;
  1977. }
  1978. export interface UnifiedPresetsBySlot {
  1979. printer: UnifiedPreset[];
  1980. process: UnifiedPreset[];
  1981. filament: UnifiedPreset[];
  1982. }
  1983. // What is loaded in each connected printer, for the SliceModal's
  1984. // "only connected printers" / "only loaded spools" filters (#3172).
  1985. export interface LoadedSpoolPreset {
  1986. preset_id: string;
  1987. preset_name: string;
  1988. preset_source: string;
  1989. tray_info_idx?: string | null;
  1990. }
  1991. export interface LoadedSpoolTray {
  1992. ams_id: number;
  1993. tray_id: number;
  1994. tray_type: string | null;
  1995. tray_sub_brands: string | null;
  1996. tray_color: string | null;
  1997. tray_info_idx: string | null;
  1998. exists: boolean | null;
  1999. state: number | null;
  2000. saved_preset: LoadedSpoolPreset | null;
  2001. }
  2002. export interface LoadedSpoolUnit {
  2003. id: number;
  2004. is_ams_ht: boolean;
  2005. trays: LoadedSpoolTray[];
  2006. }
  2007. export interface LoadedSpoolPrinter {
  2008. id: number;
  2009. name: string;
  2010. model: string | null;
  2011. ams: LoadedSpoolUnit[];
  2012. // Holders with a spool in them; external_holders counts all of them (two
  2013. // on a dual-nozzle printer, labelled left and right).
  2014. external: LoadedSpoolTray[];
  2015. external_holders: number;
  2016. }
  2017. export interface LoadedSpoolsResponse {
  2018. printers: LoadedSpoolPrinter[];
  2019. }
  2020. export interface UnifiedPresetsResponse {
  2021. // Priority order: local > orca_cloud > cloud > standard. No cross-tier
  2022. // dedup (apart from stock_aliases below) — every tier surfaces its full
  2023. // list so the user can pick from any source. The order drives auto-pick + visual group rendering only.
  2024. orca_cloud: UnifiedPresetsBySlot;
  2025. cloud: UnifiedPresetsBySlot;
  2026. local: UnifiedPresetsBySlot;
  2027. standard: UnifiedPresetsBySlot;
  2028. cloud_status: SlicerCloudStatus;
  2029. orca_cloud_status: SlicerCloudStatus;
  2030. // Standard presets that Bambu Cloud's stock list also has are left out of
  2031. // the standard tier (#3386); each "standard:<id>" maps to its cloud twin.
  2032. stock_aliases?: Record<string, PresetRef>;
  2033. }
  2034. // Slicer Pipelines (#1425) — named bundles of preset slots the SliceModal
  2035. // can apply in one click. PR A surfaces only the bundle; target_* and
  2036. // fanout_strategy round-trip from the backend but the UI doesn't yet expose
  2037. // them (they come alive in PR B / PR C).
  2038. export interface SlicerPipeline {
  2039. id: number;
  2040. name: string;
  2041. description: string | null;
  2042. printer_preset: PresetRef;
  2043. process_preset: PresetRef;
  2044. filament_presets: PresetRef[];
  2045. bed_type: string | null;
  2046. target_kind: 'specific_printer' | 'printer_class';
  2047. target_printer_id: number | null;
  2048. target_model_class: string | null;
  2049. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2050. created_by: number | null;
  2051. created_at: string;
  2052. updated_at: string;
  2053. }
  2054. export interface SlicerPipelineCreateRequest {
  2055. name: string;
  2056. description?: string | null;
  2057. printer_preset: PresetRef;
  2058. process_preset: PresetRef;
  2059. filament_presets: PresetRef[];
  2060. bed_type?: string | null;
  2061. }
  2062. export type SlicerPipelineUpdateRequest = Partial<SlicerPipelineCreateRequest> & {
  2063. target_kind?: 'specific_printer' | 'printer_class';
  2064. // ``target_printer_id: 0`` means "clear the target" — the backend maps that
  2065. // to null. Use null in TypeScript for the same intent.
  2066. target_printer_id?: number | null;
  2067. target_model_class?: string | null;
  2068. fanout_strategy?: 'max_parallel' | 'fill_one_first' | 'round_robin';
  2069. };
  2070. export interface SlicerPipelinesListResponse {
  2071. pipelines: SlicerPipeline[];
  2072. }
  2073. // Slicer Pipeline runs (#1425 PR B + PR C)
  2074. export type PipelineEligibilityKind =
  2075. | 'printer_not_set'
  2076. | 'printer_not_found'
  2077. | 'printer_disabled'
  2078. | 'printer_offline'
  2079. | 'filament_type_mismatch'
  2080. | 'filament_color_mismatch'
  2081. | 'ams_slot_missing'
  2082. | 'filament_unverified'
  2083. | 'no_class_matches'
  2084. | 'class_not_set';
  2085. export interface PipelineEligibilityIssue {
  2086. kind: PipelineEligibilityKind;
  2087. slot_index: number | null;
  2088. expected: string | null;
  2089. actual: string | null;
  2090. }
  2091. export interface PipelinePerPrinterReport {
  2092. printer_id: number;
  2093. printer_name: string;
  2094. ok: boolean;
  2095. issues: PipelineEligibilityIssue[];
  2096. }
  2097. export interface PipelineEligibilityReport {
  2098. ok: boolean;
  2099. target_kind: 'specific_printer' | 'printer_class';
  2100. target_printer_id: number | null;
  2101. target_printer_name: string | null;
  2102. target_model_class: string | null;
  2103. issues: PipelineEligibilityIssue[];
  2104. printer_reports: PipelinePerPrinterReport[];
  2105. }
  2106. export interface PipelineJob {
  2107. id: number;
  2108. pipeline_run_id: number;
  2109. copy_index: number;
  2110. assigned_printer_id: number | null;
  2111. assigned_printer_name: string | null;
  2112. queue_entry_id: number | null;
  2113. status:
  2114. | 'pending'
  2115. | 'awaiting_printer'
  2116. | 'queued'
  2117. | 'printing'
  2118. | 'completed'
  2119. | 'failed'
  2120. | 'cancelled'
  2121. | 'unknown';
  2122. error_message: string | null;
  2123. dispatched_at: string | null;
  2124. completed_at: string | null;
  2125. }
  2126. export interface PipelineRun {
  2127. id: number;
  2128. pipeline_id: number | null;
  2129. pipeline_name: string | null;
  2130. source_library_file_id: number | null;
  2131. source_archive_id: number | null;
  2132. source_filename: string | null;
  2133. parent_run_id: number | null;
  2134. copies: number;
  2135. copies_completed: number;
  2136. copies_failed: number;
  2137. copies_cancelled: number;
  2138. copies_in_progress: number;
  2139. status:
  2140. | 'queued'
  2141. | 'slicing'
  2142. | 'dispatching'
  2143. | 'in_progress'
  2144. | 'completed'
  2145. | 'failed'
  2146. | 'partial_failure'
  2147. | 'cancelled';
  2148. slice_job_id: number | null;
  2149. sliced_library_file_id: number | null;
  2150. eligibility_overridden: boolean;
  2151. error_message: string | null;
  2152. created_by: number | null;
  2153. created_at: string;
  2154. started_at: string | null;
  2155. completed_at: string | null;
  2156. jobs: PipelineJob[];
  2157. target_kind: 'specific_printer' | 'printer_class' | null;
  2158. target_printer_id: number | null;
  2159. target_model_class: string | null;
  2160. fanout_strategy: 'max_parallel' | 'fill_one_first' | 'round_robin' | null;
  2161. }
  2162. export interface PipelineRunListResponse {
  2163. runs: PipelineRun[];
  2164. total: number;
  2165. }
  2166. export interface SliceResponse {
  2167. library_file_id: number;
  2168. name: string;
  2169. print_time_seconds: number;
  2170. filament_used_g: number;
  2171. filament_used_mm: number;
  2172. used_embedded_settings: boolean;
  2173. /** Why the result could not be written to the external folder the source
  2174. * lives in, and so went to managed storage instead. Null on every normal
  2175. * slice. Surfaced to the user — a file filed somewhere they aren't looking
  2176. * with no signal is what made #2810 invisible from the UI. */
  2177. external_write_fallback?: string | null;
  2178. }
  2179. export interface SliceArchiveResponse {
  2180. archive_id: number;
  2181. name: string;
  2182. print_time_seconds: number;
  2183. filament_used_g: number;
  2184. filament_used_mm: number;
  2185. used_embedded_settings: boolean;
  2186. }
  2187. // Background slice-job lifecycle. POST /slice returns 202 + this shape;
  2188. // the frontend polls /slice-jobs/{id} until status is terminal.
  2189. export type SliceJobStatus = 'pending' | 'running' | 'completed' | 'failed';
  2190. export interface SliceJobEnqueueResponse {
  2191. job_id: number;
  2192. status: SliceJobStatus;
  2193. status_url: string;
  2194. }
  2195. export interface SliceJobProgress {
  2196. /** Stage label emitted by the slicer ("Generating G-code", "Slicing finished"). */
  2197. stage: string;
  2198. total_percent: number;
  2199. plate_percent: number;
  2200. /** 1-indexed plate position; 0 means "all plates" / final completion. */
  2201. plate_index: number;
  2202. plate_count: number;
  2203. updated_at: number;
  2204. /** When the backend is in the cross-class slice-all loop (#1493), each
  2205. * per-plate sub-slice's progress is augmented with the loop position
  2206. * so the toast can show "Plate 2 of 5 — Generating G-code 47%". The
  2207. * fields are absent on a single-plate slice. */
  2208. multi_plate_index?: number;
  2209. multi_plate_count?: number;
  2210. }
  2211. export interface SliceJobState {
  2212. job_id: number;
  2213. status: SliceJobStatus;
  2214. kind: 'library_file' | 'archive';
  2215. source_id: number;
  2216. source_name: string;
  2217. created_at: string;
  2218. started_at: string | null;
  2219. completed_at: string | null;
  2220. /** Live progress fed by the sidecar's --pipe channel; null until the
  2221. * slicer emits its first frame (early "Initializing" phase) or when
  2222. * the sidecar doesn't support progress. */
  2223. progress: SliceJobProgress | null;
  2224. result?: SliceResponse | SliceArchiveResponse;
  2225. error_status?: number;
  2226. error_detail?: string;
  2227. }
  2228. // Local preset types (OrcaSlicer imports)
  2229. export interface LocalPreset {
  2230. id: number;
  2231. name: string;
  2232. preset_type: string;
  2233. source: string;
  2234. filament_type: string | null;
  2235. filament_vendor: string | null;
  2236. nozzle_temp_min: number | null;
  2237. nozzle_temp_max: number | null;
  2238. pressure_advance: string | null;
  2239. default_filament_colour: string | null;
  2240. filament_cost: string | null;
  2241. filament_density: string | null;
  2242. compatible_printers: string | null;
  2243. inherits: string | null;
  2244. version: string | null;
  2245. created_at: string;
  2246. updated_at: string;
  2247. }
  2248. export interface LocalPresetDetail extends LocalPreset {
  2249. setting: Record<string, unknown>;
  2250. }
  2251. export interface LocalPresetsResponse {
  2252. filament: LocalPreset[];
  2253. printer: LocalPreset[];
  2254. process: LocalPreset[];
  2255. }
  2256. export interface ImportResponse {
  2257. success: boolean;
  2258. imported: number;
  2259. skipped: number;
  2260. errors: string[];
  2261. }
  2262. export interface FieldOption {
  2263. value: string;
  2264. label: string;
  2265. }
  2266. export interface FieldDefinition {
  2267. key: string;
  2268. label: string;
  2269. type: 'text' | 'number' | 'boolean' | 'select';
  2270. category: string;
  2271. description?: string;
  2272. options?: FieldOption[];
  2273. unit?: string;
  2274. min?: number;
  2275. max?: number;
  2276. step?: number;
  2277. }
  2278. export interface FieldDefinitionsResponse {
  2279. version: string;
  2280. description: string;
  2281. fields: FieldDefinition[];
  2282. }
  2283. export interface CloudDevice {
  2284. dev_id: string;
  2285. name: string;
  2286. dev_model_name: string | null;
  2287. dev_product_name: string | null;
  2288. online: boolean;
  2289. }
  2290. // Smart Plug types
  2291. export type SmartPlugTempSource = 'nozzle' | 'bed';
  2292. export interface SmartPlug {
  2293. id: number;
  2294. name: string;
  2295. plug_type: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2296. ip_address: string | null; // Required for Tasmota
  2297. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug", "script.turn_on_printer")
  2298. // Home Assistant energy sensor entities (optional)
  2299. ha_power_entity: string | null;
  2300. ha_energy_today_entity: string | null;
  2301. ha_energy_total_entity: string | null;
  2302. // MQTT fields (required when plug_type="mqtt")
  2303. // Legacy field - kept for backward compatibility
  2304. mqtt_topic: string | null; // Deprecated, use mqtt_power_topic
  2305. mqtt_multiplier: number; // Deprecated, use mqtt_power_multiplier
  2306. // Power monitoring
  2307. mqtt_power_topic: string | null; // Topic for power data
  2308. mqtt_power_path: string | null; // e.g., "power_l1" or "data.power"
  2309. mqtt_power_multiplier: number; // Unit conversion for power
  2310. // Energy monitoring
  2311. mqtt_energy_topic: string | null; // Topic for energy data
  2312. mqtt_energy_path: string | null; // e.g., "energy_l1"
  2313. mqtt_energy_multiplier: number; // Unit conversion for energy
  2314. mqtt_energy_total_path: string | null; // Lifetime counter on the energy topic (#3582)
  2315. mqtt_energy_total_multiplier: number;
  2316. // State monitoring
  2317. mqtt_state_topic: string | null; // Topic for state data
  2318. mqtt_state_path: string | null; // e.g., "state_l1" for ON/OFF
  2319. mqtt_state_on_value: string | null; // What value means "ON" (e.g., "ON", "true", "1")
  2320. // REST/Webhook fields (required when plug_type="rest")
  2321. rest_on_url: string | null;
  2322. rest_on_body: string | null;
  2323. rest_off_url: string | null;
  2324. rest_off_body: string | null;
  2325. rest_method: string | null;
  2326. rest_headers: string | null;
  2327. rest_status_url: string | null;
  2328. rest_status_path: string | null;
  2329. rest_status_on_value: string | null;
  2330. rest_power_url: string | null;
  2331. rest_power_path: string | null;
  2332. rest_power_multiplier: number;
  2333. rest_energy_url: string | null;
  2334. rest_energy_path: string | null;
  2335. rest_energy_multiplier: number;
  2336. // Lifetime counter, separate from the daily one (#2539). A Shelly reports only
  2337. // this; Today and Yesterday are derived from its hourly snapshots.
  2338. rest_energy_total_path: string | null;
  2339. rest_energy_total_multiplier: number;
  2340. printer_id: number | null;
  2341. // #2629: only a plug that really feeds the printer may mark it offline when
  2342. // switched off. Accessory plugs follow the print cycle without powering it.
  2343. controls_printer_power: boolean;
  2344. enabled: boolean;
  2345. auto_on: boolean;
  2346. auto_off: boolean;
  2347. auto_off_persistent: boolean;
  2348. off_delay_mode: 'time' | 'temperature';
  2349. off_delay_minutes: number;
  2350. off_temp_threshold: number;
  2351. // #3464: what temperature mode waits for, and the bed's own threshold.
  2352. off_temp_source: SmartPlugTempSource;
  2353. off_bed_temp_threshold: number;
  2354. // #1349: auto-off after AMS drying completes.
  2355. auto_off_after_drying: boolean;
  2356. off_delay_after_drying_minutes: number;
  2357. username: string | null;
  2358. password: string | null;
  2359. // Power alerts
  2360. power_alert_enabled: boolean;
  2361. power_alert_high: number | null;
  2362. power_alert_low: number | null;
  2363. power_alert_last_triggered: string | null;
  2364. // Schedule
  2365. schedule_enabled: boolean;
  2366. schedule_on_time: string | null;
  2367. schedule_off_time: string | null;
  2368. // Visibility options
  2369. show_in_switchbar: boolean;
  2370. show_on_printer_card: boolean; // For scripts: show on printer card
  2371. // Status
  2372. last_state: string | null;
  2373. last_checked: string | null;
  2374. auto_off_executed: boolean; // True when auto-off was triggered after print
  2375. created_at: string;
  2376. updated_at: string;
  2377. }
  2378. export interface SmartPlugCreate {
  2379. name: string;
  2380. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2381. ip_address?: string | null; // Required for Tasmota
  2382. ha_entity_id?: string | null; // Required for Home Assistant
  2383. // Home Assistant energy sensor entities (optional)
  2384. ha_power_entity?: string | null;
  2385. ha_energy_today_entity?: string | null;
  2386. ha_energy_total_entity?: string | null;
  2387. // MQTT fields (required when plug_type="mqtt")
  2388. // Legacy fields - kept for backward compatibility
  2389. mqtt_topic?: string | null;
  2390. mqtt_multiplier?: number;
  2391. // Power monitoring
  2392. mqtt_power_topic?: string | null;
  2393. mqtt_power_path?: string | null;
  2394. mqtt_power_multiplier?: number;
  2395. // Energy monitoring
  2396. mqtt_energy_topic?: string | null;
  2397. mqtt_energy_path?: string | null;
  2398. mqtt_energy_multiplier?: number;
  2399. mqtt_energy_total_path?: string | null;
  2400. mqtt_energy_total_multiplier?: number;
  2401. // State monitoring
  2402. mqtt_state_topic?: string | null;
  2403. mqtt_state_path?: string | null;
  2404. mqtt_state_on_value?: string | null;
  2405. // REST fields
  2406. rest_on_url?: string | null;
  2407. rest_on_body?: string | null;
  2408. rest_off_url?: string | null;
  2409. rest_off_body?: string | null;
  2410. rest_method?: string | null;
  2411. rest_headers?: string | null;
  2412. rest_status_url?: string | null;
  2413. rest_status_path?: string | null;
  2414. rest_status_on_value?: string | null;
  2415. rest_power_url?: string | null;
  2416. rest_power_path?: string | null;
  2417. rest_power_multiplier?: number;
  2418. rest_energy_url?: string | null;
  2419. rest_energy_path?: string | null;
  2420. rest_energy_multiplier?: number;
  2421. rest_energy_total_path?: string | null;
  2422. rest_energy_total_multiplier?: number;
  2423. printer_id?: number | null;
  2424. // #2629
  2425. controls_printer_power?: boolean;
  2426. enabled?: boolean;
  2427. auto_on?: boolean;
  2428. auto_off?: boolean;
  2429. auto_off_persistent?: boolean;
  2430. off_delay_mode?: 'time' | 'temperature';
  2431. off_delay_minutes?: number;
  2432. off_temp_threshold?: number;
  2433. // #3464
  2434. off_temp_source?: SmartPlugTempSource;
  2435. off_bed_temp_threshold?: number;
  2436. // #1349
  2437. auto_off_after_drying?: boolean;
  2438. off_delay_after_drying_minutes?: number;
  2439. username?: string | null;
  2440. password?: string | null;
  2441. // Power alerts
  2442. power_alert_enabled?: boolean;
  2443. power_alert_high?: number | null;
  2444. power_alert_low?: number | null;
  2445. // Schedule
  2446. schedule_enabled?: boolean;
  2447. schedule_on_time?: string | null;
  2448. schedule_off_time?: string | null;
  2449. // Visibility options
  2450. show_in_switchbar?: boolean;
  2451. show_on_printer_card?: boolean;
  2452. }
  2453. export interface SmartPlugUpdate {
  2454. name?: string;
  2455. plug_type?: 'tasmota' | 'homeassistant' | 'mqtt' | 'rest';
  2456. ip_address?: string | null;
  2457. ha_entity_id?: string | null;
  2458. // Home Assistant energy sensor entities (optional)
  2459. ha_power_entity?: string | null;
  2460. ha_energy_today_entity?: string | null;
  2461. ha_energy_total_entity?: string | null;
  2462. // MQTT fields (legacy)
  2463. mqtt_topic?: string | null;
  2464. mqtt_multiplier?: number;
  2465. // MQTT power fields
  2466. mqtt_power_topic?: string | null;
  2467. mqtt_power_path?: string | null;
  2468. mqtt_power_multiplier?: number;
  2469. // MQTT energy fields
  2470. mqtt_energy_topic?: string | null;
  2471. mqtt_energy_path?: string | null;
  2472. mqtt_energy_multiplier?: number;
  2473. mqtt_energy_total_path?: string | null;
  2474. mqtt_energy_total_multiplier?: number;
  2475. // MQTT state fields
  2476. mqtt_state_topic?: string | null;
  2477. mqtt_state_path?: string | null;
  2478. mqtt_state_on_value?: string | null;
  2479. // REST fields
  2480. rest_on_url?: string | null;
  2481. rest_on_body?: string | null;
  2482. rest_off_url?: string | null;
  2483. rest_off_body?: string | null;
  2484. rest_method?: string | null;
  2485. rest_headers?: string | null;
  2486. rest_status_url?: string | null;
  2487. rest_status_path?: string | null;
  2488. rest_status_on_value?: string | null;
  2489. rest_power_url?: string | null;
  2490. rest_power_path?: string | null;
  2491. rest_power_multiplier?: number;
  2492. rest_energy_url?: string | null;
  2493. rest_energy_path?: string | null;
  2494. rest_energy_multiplier?: number;
  2495. rest_energy_total_path?: string | null;
  2496. rest_energy_total_multiplier?: number;
  2497. printer_id?: number | null;
  2498. // #2629
  2499. controls_printer_power?: boolean;
  2500. enabled?: boolean;
  2501. auto_on?: boolean;
  2502. auto_off?: boolean;
  2503. auto_off_persistent?: boolean;
  2504. off_delay_mode?: 'time' | 'temperature';
  2505. off_delay_minutes?: number;
  2506. off_temp_threshold?: number;
  2507. // #3464
  2508. off_temp_source?: SmartPlugTempSource;
  2509. off_bed_temp_threshold?: number;
  2510. // #1349
  2511. auto_off_after_drying?: boolean;
  2512. off_delay_after_drying_minutes?: number;
  2513. username?: string | null;
  2514. password?: string | null;
  2515. // Power alerts
  2516. power_alert_enabled?: boolean;
  2517. power_alert_high?: number | null;
  2518. power_alert_low?: number | null;
  2519. // Schedule
  2520. schedule_enabled?: boolean;
  2521. schedule_on_time?: string | null;
  2522. schedule_off_time?: string | null;
  2523. // Visibility options
  2524. show_in_switchbar?: boolean;
  2525. show_on_printer_card?: boolean;
  2526. }
  2527. // Home Assistant entity for smart plug selection
  2528. export interface HAEntity {
  2529. entity_id: string;
  2530. friendly_name: string;
  2531. state: string | null;
  2532. domain: string; // "switch", "light", "input_boolean", "script"
  2533. }
  2534. // Home Assistant sensor entity for energy monitoring
  2535. export interface HASensorEntity {
  2536. entity_id: string;
  2537. friendly_name: string;
  2538. state: string | null;
  2539. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  2540. }
  2541. export interface HATestConnectionResult {
  2542. success: boolean;
  2543. message: string | null;
  2544. error: string | null;
  2545. }
  2546. // A Home Assistant entity bound to a printer for display on its card (#1148, #448).
  2547. // Read-only: unlike a SmartPlug there is nothing here to switch.
  2548. export interface PrinterHASensor {
  2549. id: number;
  2550. printer_id: number;
  2551. name: string;
  2552. entity_id: string;
  2553. kind: 'binary' | 'numeric';
  2554. device_class: string | null; // HA's own class: "door", "temperature", ...
  2555. unit: string | null; // numeric sensors only
  2556. // What counts as needing attention. Binary sensors use alert_state, numeric
  2557. // ones the thresholds; all null means the sensor is display-only.
  2558. alert_state: 'on' | 'off' | null;
  2559. alert_above: number | null;
  2560. alert_below: number | null;
  2561. block_print: boolean; // hold the printer's queue while alerting
  2562. notify_on_alert: boolean;
  2563. show_on_printer_card: boolean;
  2564. sort_order: number;
  2565. last_state: string | null;
  2566. last_changed: string | null;
  2567. last_checked: string | null;
  2568. created_at: string;
  2569. updated_at: string;
  2570. }
  2571. export interface PrinterHASensorReading {
  2572. id: number;
  2573. name: string;
  2574. entity_id: string;
  2575. kind: 'binary' | 'numeric';
  2576. device_class: string | null;
  2577. unit: string | null;
  2578. state: string | null; // null when unreadable or not yet polled
  2579. value: number | null; // numeric sensors only
  2580. alerting: boolean;
  2581. block_print: boolean;
  2582. reachable: boolean;
  2583. last_changed: string | null;
  2584. }
  2585. export interface PrinterHASensorCreate {
  2586. printer_id: number;
  2587. name: string;
  2588. entity_id: string;
  2589. kind: 'binary' | 'numeric';
  2590. device_class?: string | null;
  2591. unit?: string | null;
  2592. alert_state?: 'on' | 'off' | null;
  2593. alert_above?: number | null;
  2594. alert_below?: number | null;
  2595. block_print?: boolean;
  2596. notify_on_alert?: boolean;
  2597. show_on_printer_card?: boolean;
  2598. sort_order?: number;
  2599. }
  2600. export type PrinterHASensorUpdate = Partial<Omit<PrinterHASensorCreate, 'printer_id'>>;
  2601. export interface LocationHASensor {
  2602. id: number;
  2603. location_id: number;
  2604. name: string;
  2605. entity_id: string;
  2606. kind: 'binary' | 'numeric';
  2607. device_class: string | null;
  2608. unit: string | null;
  2609. alert_state: 'on' | 'off' | null;
  2610. alert_above: number | null;
  2611. alert_below: number | null;
  2612. notify_on_alert: boolean;
  2613. show_on_card: boolean;
  2614. sort_order: number;
  2615. last_state: string | null;
  2616. last_changed: string | null;
  2617. last_checked: string | null;
  2618. created_at: string;
  2619. updated_at: string;
  2620. }
  2621. export interface LocationHASensorReading {
  2622. id: number;
  2623. name: string;
  2624. entity_id: string;
  2625. kind: 'binary' | 'numeric';
  2626. device_class: string | null;
  2627. unit: string | null;
  2628. state: string | null;
  2629. value: number | null;
  2630. alerting: boolean;
  2631. reachable: boolean;
  2632. alert_state: string | null;
  2633. alert_above: number | null;
  2634. alert_below: number | null;
  2635. last_changed: string | null;
  2636. show_on_card: boolean;
  2637. }
  2638. export interface LocationHASensorCreate {
  2639. location_id: number;
  2640. name: string;
  2641. entity_id: string;
  2642. kind: 'binary' | 'numeric';
  2643. device_class?: string | null;
  2644. unit?: string | null;
  2645. alert_state?: 'on' | 'off' | null;
  2646. alert_above?: number | null;
  2647. alert_below?: number | null;
  2648. notify_on_alert?: boolean;
  2649. show_on_card?: boolean;
  2650. sort_order?: number;
  2651. }
  2652. export type LocationHASensorUpdate = Partial<Omit<LocationHASensorCreate, 'location_id'>>;
  2653. // An entity offered by the binding picker.
  2654. export interface HADisplayEntity {
  2655. entity_id: string;
  2656. friendly_name: string;
  2657. state: string | null;
  2658. domain: string; // "binary_sensor" | "sensor"
  2659. device_class: string | null;
  2660. unit_of_measurement: string | null;
  2661. }
  2662. export interface SmartPlugEnergy {
  2663. power: number | null; // Current watts
  2664. voltage: number | null; // Volts
  2665. current: number | null; // Amps
  2666. today: number | null; // kWh used today
  2667. yesterday: number | null; // kWh used yesterday
  2668. total: number | null; // Total kWh
  2669. factor: number | null; // Power factor (0-1)
  2670. apparent_power: number | null; // VA
  2671. reactive_power: number | null; // VAr
  2672. }
  2673. export interface SmartPlugStatus {
  2674. state: string | null;
  2675. reachable: boolean;
  2676. device_name: string | null;
  2677. energy: SmartPlugEnergy | null;
  2678. }
  2679. export interface SmartPlugTestResult {
  2680. success: boolean;
  2681. state: string | null;
  2682. device_name: string | null;
  2683. }
  2684. // Tasmota Discovery types
  2685. export interface TasmotaScanStatus {
  2686. running: boolean;
  2687. scanned: number;
  2688. total: number;
  2689. }
  2690. export interface DiscoveredTasmotaDevice {
  2691. ip_address: string;
  2692. name: string;
  2693. module: number | null;
  2694. state: string | null;
  2695. discovered_at: string | null;
  2696. }
  2697. // Print Queue types
  2698. export interface PrintQueueItem {
  2699. id: number;
  2700. printer_id: number | null; // null = unassigned
  2701. target_model: string | null; // Target printer model for model-based assignment
  2702. target_location: string | null; // Target location filter for model-based assignment
  2703. required_filament_types: string[] | null; // Required filament types for model-based assignment
  2704. waiting_reason: string | null; // Why this job hasn't started yet (empty once it can)
  2705. // Cross-model alternatives (#671), in priority order. Empty for ordinary
  2706. // items. Present until dispatch resolves one, after which library_file_id and
  2707. // target_model name the candidate that actually ran.
  2708. variants?: Array<{
  2709. library_file_id: number;
  2710. filename: string;
  2711. target_model: string;
  2712. position: number;
  2713. }>;
  2714. // Either archive_id OR library_file_id must be set (archive created at print start)
  2715. archive_id: number | null;
  2716. library_file_id: number | null;
  2717. cost_center_id: number | null;
  2718. estimated_cost: number | null;
  2719. position: number;
  2720. scheduled_time: string | null;
  2721. require_previous_success: boolean;
  2722. auto_off_after: boolean;
  2723. manual_start: boolean; // Requires manual trigger to start (staged)
  2724. // Set by the dispatch scheduler when the assigned spool can't satisfy
  2725. // any required slot's grams (#1496). Surfaced on the queue row as a
  2726. // "filament short" badge; cleared on a successful ▶ click (live recheck).
  2727. filament_short: boolean;
  2728. // Persistent "Print Anyway" acknowledgement — once true the scheduler
  2729. // skips the deficit check for this item (#1698-followup). Set by the
  2730. // start route when skip_filament_check=true, or at queue creation if
  2731. // PrintModal's deficit warning was acknowledged.
  2732. skip_filament_check: boolean;
  2733. // True when the source archive carries the slicer's own live-resolved
  2734. // AMS-slot pick (extra_data.slicer_ams_mapping) — a reprint reuses that
  2735. // exact physical spool instead of re-deriving one from type/color.
  2736. archive_has_slicer_ams_mapping: boolean;
  2737. // A virtual printer's job not printed yet: the slicer's AMS pick it keeps
  2738. // for its archive, when made against this row's printer.
  2739. slicer_ams_mapping?: number[] | null;
  2740. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  2741. filament_overrides: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null; // Filament overrides for model-based assignment
  2742. plate_id: number | null; // Plate ID for multi-plate 3MF files
  2743. // Print options
  2744. bed_levelling: CalibrationMode;
  2745. flow_cali: CalibrationMode;
  2746. vibration_cali: boolean;
  2747. layer_inspect: boolean;
  2748. timelapse: boolean;
  2749. use_ams: boolean;
  2750. nozzle_offset_cali: CalibrationMode;
  2751. // Ask for a post-print outcome verdict when this job completes (#1898)
  2752. confirm_outcome: boolean;
  2753. preheat_override: 'inherit' | 'on' | 'off';
  2754. preheat_chamber_target_override: number | null;
  2755. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  2756. started_at: string | null;
  2757. completed_at: string | null;
  2758. error_message: string | null;
  2759. created_at: string;
  2760. archive_name?: string | null;
  2761. archive_thumbnail?: string | null;
  2762. // True when the linked archive has been soft-deleted; archive_name /
  2763. // archive_thumbnail / downstream metadata are left null in that case so
  2764. // the UI doesn't 404-storm the now-missing endpoints (#1348 follow-up).
  2765. archive_deleted?: boolean;
  2766. library_file_name?: string | null;
  2767. library_file_thumbnail?: string | null;
  2768. printer_name?: string | null;
  2769. print_time_seconds?: number | null; // Estimated print time from archive or library file
  2770. filament_used_grams?: number | null; // Estimated print weight from archive or library file
  2771. filament_type?: string | null; // e.g. "PLA", "PETG"
  2772. filament_color?: string | null; // Hex RGBA from the slicer
  2773. bed_type?: string | null; // Build plate type for this print (per-plate accurate, #1281)
  2774. // User tracking (Issue #206)
  2775. created_by_id?: number | null;
  2776. created_by_username?: string | null;
  2777. // Batch grouping
  2778. batch_id?: number | null;
  2779. batch_name?: string | null;
  2780. // Shortest-job-first scheduling
  2781. been_jumped?: boolean;
  2782. // Auto-print G-code injection
  2783. gcode_injection?: boolean;
  2784. cleanup_library_after_dispatch?: boolean;
  2785. /** Which rack position each filament group prints from, on a nozzle-rack
  2786. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2787. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2788. nozzle_rack_choice?: Record<number, number> | null;
  2789. /** Slots sent with a spool of another colour than the file asks for
  2790. * (#3279). Worked out when the job is sent; null when every slot got its
  2791. * colour or nothing could be compared. */
  2792. color_substitutions?: ColorSubstitution[] | null;
  2793. }
  2794. /** One slot printed in another colour than the file asked for (#3279). */
  2795. export interface ColorSubstitution {
  2796. slot_id: number;
  2797. type: string;
  2798. /** `#RRGGBB` the file asks for, after overrides. */
  2799. wanted: string;
  2800. /** `#RRGGBB` of the spool the slot was sent with. */
  2801. got: string;
  2802. tray: number;
  2803. }
  2804. export interface PrintBatchPlateTarget {
  2805. plate_id: number | null;
  2806. plate_name?: string | null;
  2807. quantity_target: number;
  2808. sort_order?: number;
  2809. }
  2810. export interface PrintBatchPlateProgress {
  2811. plate_id: number | null;
  2812. plate_name: string | null;
  2813. quantity_target: number;
  2814. dispatched: number;
  2815. remaining: number;
  2816. pending_count: number;
  2817. printing_count: number;
  2818. completed_count: number;
  2819. failed_count: number;
  2820. cancelled_count: number;
  2821. skipped_count: number;
  2822. /** Measured from finished runs; null until one has produced a cost. */
  2823. actual_cost: number | null;
  2824. estimated_remaining_cost: number | null;
  2825. filament_used_grams: number | null;
  2826. print_time_seconds: number;
  2827. /** False when this plate owes runs but has no queue item left to clone
  2828. * their configuration from, so queueing it could only fail (#2960). */
  2829. can_dispatch: boolean;
  2830. }
  2831. export interface PrintBatch {
  2832. id: number;
  2833. name: string;
  2834. archive_id: number | null;
  2835. library_file_id: number | null;
  2836. quantity: number;
  2837. status: string;
  2838. created_at: string;
  2839. completed_at: string | null;
  2840. created_by_id: number | null;
  2841. created_by_username: string | null;
  2842. project_id: number | null;
  2843. due_date: string | null;
  2844. notes: string | null;
  2845. /** Set when an integration (e.g. a shop connector) created the batch. */
  2846. external_source: string | null;
  2847. external_ref: string | null;
  2848. pending_count: number;
  2849. printing_count: number;
  2850. completed_count: number;
  2851. failed_count: number;
  2852. cancelled_count: number;
  2853. skipped_count: number;
  2854. /** False for batches created before per-plate targets existed (#342):
  2855. * they report progress but owe nothing and cannot be dispatched from. */
  2856. has_targets: boolean;
  2857. target_count: number;
  2858. remaining_count: number;
  2859. /** Of remaining_count, how many runs can actually be queued (#2960). */
  2860. dispatchable_count: number;
  2861. actual_cost: number | null;
  2862. estimated_remaining_cost: number | null;
  2863. filament_used_grams: number | null;
  2864. print_time_seconds: number;
  2865. plates: PrintBatchPlateProgress[];
  2866. }
  2867. export interface PrintQueueItemCreate {
  2868. printer_id?: number | null; // null = unassigned
  2869. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2870. target_location?: string | null; // Target location filter (only used with target_model)
  2871. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2872. archive_id?: number | null;
  2873. library_file_id?: number | null;
  2874. scheduled_time?: string | null;
  2875. require_previous_success?: boolean;
  2876. auto_off_after?: boolean;
  2877. manual_start?: boolean; // Requires manual trigger to start (staged)
  2878. insert_at_top?: boolean; // Insert ahead of other pending items (one queue order across all printers, #3200)
  2879. insert_position?: number | null; // 1-indexed insertion position for priority queueing
  2880. // PrintModal "Print Anyway" on the deficit warning — persisted so the
  2881. // scheduler doesn't immediately re-flag this item (#1698-followup).
  2882. skip_filament_check?: boolean;
  2883. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  2884. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2885. // Print options
  2886. bed_levelling?: CalibrationMode;
  2887. flow_cali?: CalibrationMode;
  2888. vibration_cali?: boolean;
  2889. layer_inspect?: boolean;
  2890. timelapse?: boolean;
  2891. use_ams?: boolean;
  2892. nozzle_offset_cali?: CalibrationMode;
  2893. // Ask for a post-print outcome verdict when this job completes (#1898)
  2894. confirm_outcome?: boolean;
  2895. preheat_override?: 'inherit' | 'on' | 'off';
  2896. preheat_chamber_target_override?: number | null;
  2897. // Auto-print G-code injection
  2898. gcode_injection?: boolean;
  2899. // Batch: create multiple copies (creates a batch if > 1)
  2900. quantity?: number;
  2901. // Existing batch to add this item into (multi-plate auto-batch flow).
  2902. batch_id?: number | null;
  2903. // Project to associate the resulting archive with
  2904. project_id?: number;
  2905. cost_center_id?: number | null;
  2906. estimated_cost?: number | null;
  2907. // Delete transient uploaded library file after scheduler creates the archive
  2908. cleanup_library_after_dispatch?: boolean;
  2909. // Cross-model alternatives (#671): several sliced files, one job, whichever
  2910. // printer frees up first. Mutually exclusive with printer_id (a named printer
  2911. // defeats the point) and with archive_id/library_file_id (these ARE the files).
  2912. // Order is priority — index 0 wins when several printers are idle at once.
  2913. variants?: QueueVariantCreate[];
  2914. /** Which rack position each filament group prints from, on a nozzle-rack
  2915. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2916. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2917. nozzle_rack_choice?: Record<number, number> | null;
  2918. }
  2919. /** One candidate file for a cross-model queue item (#671). */
  2920. export interface QueueVariantCreate {
  2921. library_file_id: number;
  2922. /** Read from the file's own sliced_for_model unless it declares none. */
  2923. target_model?: string | null;
  2924. plate_id?: number | null;
  2925. ams_mapping?: number[] | null;
  2926. nozzle_mapping?: number[] | null;
  2927. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2928. }
  2929. export interface PrintBatchCreate {
  2930. name: string;
  2931. archive_id?: number | null;
  2932. library_file_id?: number | null;
  2933. /** When set, the listed pending items are assigned to the new batch
  2934. * (manual "Group as batch"). When omitted/empty, an empty batch is
  2935. * returned so the client can pass batch_id on subsequent addToQueue calls. */
  2936. item_ids?: number[];
  2937. /** Per-plate targets. Omitting them creates a plain grouping batch. */
  2938. plates?: PrintBatchPlateTarget[];
  2939. project_id?: number | null;
  2940. due_date?: string | null;
  2941. notes?: string | null;
  2942. }
  2943. export interface PrintBatchUpdate {
  2944. name?: string;
  2945. status?: 'active' | 'cancelled';
  2946. /** Replaces the full target set — a plate omitted here is removed. */
  2947. plates?: PrintBatchPlateTarget[];
  2948. project_id?: number | null;
  2949. due_date?: string | null;
  2950. notes?: string | null;
  2951. }
  2952. export interface PrintBatchDispatchRequest {
  2953. plate_id?: number | null;
  2954. only_plate?: boolean;
  2955. /** Cap on items created across all plates; omit to queue everything owed. */
  2956. limit?: number;
  2957. }
  2958. export interface PrintQueueItemUpdate {
  2959. printer_id?: number | null; // null = unassign
  2960. // A deliberate filament substitution in the mapping (#2799); see PrintModal.
  2961. skip_filament_check?: boolean;
  2962. target_model?: string | null; // Target printer model (mutually exclusive with printer_id)
  2963. target_location?: string | null; // Target location filter (only used with target_model)
  2964. filament_overrides?: Array<{ slot_id: number; type: string; color: string; color_name?: string; tray_info_idx?: string; force_color_match?: boolean }> | null;
  2965. position?: number;
  2966. scheduled_time?: string | null;
  2967. require_previous_success?: boolean;
  2968. auto_off_after?: boolean;
  2969. manual_start?: boolean;
  2970. ams_mapping?: number[];
  2971. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  2972. // Print options
  2973. bed_levelling?: CalibrationMode;
  2974. flow_cali?: CalibrationMode;
  2975. vibration_cali?: boolean;
  2976. layer_inspect?: boolean;
  2977. timelapse?: boolean;
  2978. use_ams?: boolean;
  2979. nozzle_offset_cali?: CalibrationMode;
  2980. // Ask for a post-print outcome verdict when this job completes (#1898)
  2981. confirm_outcome?: boolean;
  2982. preheat_override?: 'inherit' | 'on' | 'off';
  2983. preheat_chamber_target_override?: number | null;
  2984. // Auto-print G-code injection
  2985. gcode_injection?: boolean;
  2986. cost_center_id?: number | null;
  2987. estimated_cost?: number | null;
  2988. /** Which rack position each filament group prints from, on a nozzle-rack
  2989. * machine (#1784): `{ [group_id]: 1-based position }`. Re-checked against
  2990. * the live rack at dispatch; omit to have the dispatcher assign them. */
  2991. nozzle_rack_choice?: Record<number, number> | null;
  2992. }
  2993. export interface PrintQueueBulkUpdate {
  2994. item_ids: number[];
  2995. printer_id?: number | null;
  2996. scheduled_time?: string | null;
  2997. require_previous_success?: boolean;
  2998. auto_off_after?: boolean;
  2999. manual_start?: boolean;
  3000. // Print options
  3001. bed_levelling?: CalibrationMode;
  3002. flow_cali?: CalibrationMode;
  3003. vibration_cali?: boolean;
  3004. layer_inspect?: boolean;
  3005. timelapse?: boolean;
  3006. use_ams?: boolean;
  3007. nozzle_offset_cali?: CalibrationMode;
  3008. // Ask for a post-print outcome verdict when this job completes (#1898)
  3009. confirm_outcome?: boolean;
  3010. preheat_override?: 'inherit' | 'on' | 'off';
  3011. preheat_chamber_target_override?: number | null;
  3012. // Auto-print G-code injection
  3013. gcode_injection?: boolean;
  3014. cost_center_id?: number | null;
  3015. estimated_cost?: number | null;
  3016. }
  3017. export interface PrintQueueBulkUpdateResponse {
  3018. updated_count: number;
  3019. skipped_count: number;
  3020. message: string;
  3021. }
  3022. // MQTT Logging types
  3023. export interface MQTTLogEntry {
  3024. timestamp: string;
  3025. topic: string;
  3026. direction: 'in' | 'out';
  3027. payload: Record<string, unknown>;
  3028. }
  3029. export interface MQTTLogsResponse {
  3030. logging_enabled: boolean;
  3031. logs: MQTTLogEntry[];
  3032. }
  3033. // K-Profile types
  3034. export interface KProfile {
  3035. slot_id: number;
  3036. extruder_id: number;
  3037. nozzle_id: string;
  3038. nozzle_diameter: string;
  3039. filament_id: string;
  3040. name: string;
  3041. k_value: string;
  3042. n_coef: string;
  3043. ams_id: number;
  3044. tray_id: number;
  3045. setting_id: string | null;
  3046. }
  3047. export interface KProfileCreate {
  3048. slot_id?: number; // Storage slot, 0 for new profiles
  3049. extruder_id?: number;
  3050. nozzle_id: string;
  3051. nozzle_diameter: string;
  3052. filament_id: string;
  3053. name: string;
  3054. k_value: string;
  3055. n_coef?: string;
  3056. ams_id?: number;
  3057. tray_id?: number;
  3058. setting_id?: string | null;
  3059. }
  3060. export interface KProfileDelete {
  3061. slot_id: number; // cali_idx - calibration index to delete
  3062. extruder_id: number;
  3063. nozzle_id: string; // e.g., "HH00-0.4"
  3064. nozzle_diameter: string; // e.g., "0.4"
  3065. filament_id: string; // Bambu filament identifier
  3066. setting_id?: string | null; // Setting ID (for X1C series)
  3067. }
  3068. export interface KProfilesResponse {
  3069. profiles: KProfile[];
  3070. nozzle_diameter: string;
  3071. }
  3072. export interface KProfileNote {
  3073. setting_id: string;
  3074. note: string;
  3075. }
  3076. export interface KProfileNotesResponse {
  3077. notes: Record<string, string>; // setting_id -> note
  3078. }
  3079. // Slot Preset Mapping
  3080. export interface SlotPresetMapping {
  3081. ams_id: number;
  3082. tray_id: number;
  3083. preset_id: string;
  3084. preset_name: string;
  3085. // Filament id the slot was configured with alongside this preset; null for
  3086. // rows that predate it or whose writer did not know it (#3216).
  3087. tray_info_idx?: string | null;
  3088. }
  3089. // Filament types
  3090. export interface Filament {
  3091. id: number;
  3092. name: string;
  3093. type: string; // PLA, PETG, ABS, etc.
  3094. brand: string | null;
  3095. color: string | null;
  3096. color_hex: string | null;
  3097. cost_per_kg: number;
  3098. spool_weight_g: number;
  3099. currency: string;
  3100. density: number | null;
  3101. print_temp_min: number | null;
  3102. print_temp_max: number | null;
  3103. bed_temp_min: number | null;
  3104. bed_temp_max: number | null;
  3105. created_at: string;
  3106. updated_at: string;
  3107. }
  3108. // Notification Provider types
  3109. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook' | 'homeassistant' | 'bark' | 'gotify' | 'notify';
  3110. // How a Telegram provider collects the outcome verdict (#3046)
  3111. export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
  3112. // Events that can carry a camera snapshot; a provider can skip it per event (#2877).
  3113. export type NotificationPhotoEvent =
  3114. | 'print_start'
  3115. | 'print_complete'
  3116. | 'print_failed'
  3117. | 'print_stopped'
  3118. | 'print_progress'
  3119. | 'first_layer_complete'
  3120. | 'printer_error'
  3121. | 'ai_failure_detection'
  3122. | 'plate_not_empty'
  3123. | 'print_confirm_request';
  3124. export interface NotificationProvider {
  3125. id: number;
  3126. name: string;
  3127. provider_type: ProviderType;
  3128. enabled: boolean;
  3129. config: Record<string, unknown>;
  3130. attach_photo: boolean;
  3131. photo_skip_events: NotificationPhotoEvent[];
  3132. // Print lifecycle events
  3133. on_print_start: boolean;
  3134. on_print_complete: boolean;
  3135. on_print_failed: boolean;
  3136. on_print_stopped: boolean;
  3137. on_print_progress: boolean;
  3138. on_print_missing_spool_assignment: boolean;
  3139. on_billing_charge_failed: boolean;
  3140. // Printer status events
  3141. on_printer_offline: boolean;
  3142. on_printer_error: boolean;
  3143. on_ai_failure_detection: boolean;
  3144. on_filament_low: boolean;
  3145. on_maintenance_due: boolean;
  3146. // AMS environmental alarms (regular AMS)
  3147. on_ams_humidity_high: boolean;
  3148. on_ams_temperature_high: boolean;
  3149. on_ams_drying_suspended: boolean;
  3150. // AMS-HT environmental alarms
  3151. on_ams_ht_humidity_high: boolean;
  3152. on_ams_ht_temperature_high: boolean;
  3153. // Build plate detection
  3154. on_plate_not_empty: boolean;
  3155. on_plate_clear_required: boolean;
  3156. // Post-print outcome confirmation (#1898)
  3157. on_print_confirm_request: boolean;
  3158. telegram_verdict_mode: TelegramVerdictMode;
  3159. // Bed cooled
  3160. on_bed_cooled: boolean;
  3161. on_ha_sensor_alert: boolean;
  3162. on_location_ha_sensor_alert: boolean;
  3163. // First layer complete
  3164. on_first_layer_complete: boolean;
  3165. on_print_pause_upcoming: boolean;
  3166. on_app_message: boolean;
  3167. // Inventory stock alerts
  3168. on_stock_reorder_alert: boolean;
  3169. on_stock_break_alert: boolean;
  3170. // Print queue events
  3171. on_queue_job_added: boolean;
  3172. on_queue_job_assigned: boolean;
  3173. on_queue_job_started: boolean;
  3174. on_queue_job_waiting: boolean;
  3175. on_queue_job_skipped: boolean;
  3176. on_queue_job_failed: boolean;
  3177. on_queue_completed: boolean;
  3178. // Quiet hours
  3179. quiet_hours_enabled: boolean;
  3180. quiet_hours_start: string | null;
  3181. quiet_hours_end: string | null;
  3182. // Daily digest
  3183. daily_digest_enabled: boolean;
  3184. daily_digest_time: string | null;
  3185. // Printer filter
  3186. printer_id: number | null;
  3187. // Status tracking
  3188. last_success: string | null;
  3189. last_error: string | null;
  3190. last_error_at: string | null;
  3191. // Timestamps
  3192. created_at: string;
  3193. updated_at: string;
  3194. }
  3195. export interface NotificationProviderCreate {
  3196. name: string;
  3197. provider_type: ProviderType;
  3198. enabled?: boolean;
  3199. config: Record<string, unknown>;
  3200. attach_photo?: boolean;
  3201. photo_skip_events?: NotificationPhotoEvent[];
  3202. // Print lifecycle events
  3203. on_print_start?: boolean;
  3204. on_print_complete?: boolean;
  3205. on_print_failed?: boolean;
  3206. on_print_stopped?: boolean;
  3207. on_print_progress?: boolean;
  3208. on_print_missing_spool_assignment?: boolean;
  3209. on_billing_charge_failed?: boolean;
  3210. // Printer status events
  3211. on_printer_offline?: boolean;
  3212. on_printer_error?: boolean;
  3213. on_ai_failure_detection?: boolean;
  3214. on_filament_low?: boolean;
  3215. on_maintenance_due?: boolean;
  3216. // AMS environmental alarms (regular AMS)
  3217. on_ams_humidity_high?: boolean;
  3218. on_ams_temperature_high?: boolean;
  3219. on_ams_drying_suspended?: boolean;
  3220. // AMS-HT environmental alarms
  3221. on_ams_ht_humidity_high?: boolean;
  3222. on_ams_ht_temperature_high?: boolean;
  3223. // Build plate detection
  3224. on_plate_not_empty?: boolean;
  3225. on_plate_clear_required?: boolean;
  3226. // Post-print outcome confirmation (#1898)
  3227. on_print_confirm_request?: boolean;
  3228. telegram_verdict_mode?: TelegramVerdictMode;
  3229. // Bed cooled
  3230. on_bed_cooled?: boolean;
  3231. on_ha_sensor_alert?: boolean;
  3232. on_location_ha_sensor_alert?: boolean;
  3233. // First layer complete
  3234. on_first_layer_complete?: boolean;
  3235. on_print_pause_upcoming?: boolean;
  3236. on_app_message?: boolean;
  3237. // Inventory stock alerts
  3238. on_stock_reorder_alert?: boolean;
  3239. on_stock_break_alert?: boolean;
  3240. // Print queue events
  3241. on_queue_job_added?: boolean;
  3242. on_queue_job_assigned?: boolean;
  3243. on_queue_job_started?: boolean;
  3244. on_queue_job_waiting?: boolean;
  3245. on_queue_job_skipped?: boolean;
  3246. on_queue_job_failed?: boolean;
  3247. on_queue_completed?: boolean;
  3248. // Quiet hours
  3249. quiet_hours_enabled?: boolean;
  3250. quiet_hours_start?: string | null;
  3251. quiet_hours_end?: string | null;
  3252. // Daily digest
  3253. daily_digest_enabled?: boolean;
  3254. daily_digest_time?: string | null;
  3255. // Printer filter
  3256. printer_id?: number | null;
  3257. }
  3258. export interface NotificationProviderUpdate {
  3259. name?: string;
  3260. provider_type?: ProviderType;
  3261. enabled?: boolean;
  3262. config?: Record<string, unknown>;
  3263. attach_photo?: boolean;
  3264. photo_skip_events?: NotificationPhotoEvent[];
  3265. // Print lifecycle events
  3266. on_print_start?: boolean;
  3267. on_print_complete?: boolean;
  3268. on_print_failed?: boolean;
  3269. on_print_stopped?: boolean;
  3270. on_print_progress?: boolean;
  3271. on_print_missing_spool_assignment?: boolean;
  3272. on_billing_charge_failed?: boolean;
  3273. // Printer status events
  3274. on_printer_offline?: boolean;
  3275. on_printer_error?: boolean;
  3276. on_ai_failure_detection?: boolean;
  3277. on_filament_low?: boolean;
  3278. on_maintenance_due?: boolean;
  3279. // AMS environmental alarms (regular AMS)
  3280. on_ams_humidity_high?: boolean;
  3281. on_ams_temperature_high?: boolean;
  3282. on_ams_drying_suspended?: boolean;
  3283. // AMS-HT environmental alarms
  3284. on_ams_ht_humidity_high?: boolean;
  3285. on_ams_ht_temperature_high?: boolean;
  3286. // Build plate detection
  3287. on_plate_not_empty?: boolean;
  3288. on_plate_clear_required?: boolean;
  3289. // Post-print outcome confirmation (#1898)
  3290. on_print_confirm_request?: boolean;
  3291. telegram_verdict_mode?: TelegramVerdictMode;
  3292. // Bed cooled
  3293. on_bed_cooled?: boolean;
  3294. on_ha_sensor_alert?: boolean;
  3295. on_location_ha_sensor_alert?: boolean;
  3296. // First layer complete
  3297. on_first_layer_complete?: boolean;
  3298. on_print_pause_upcoming?: boolean;
  3299. on_app_message?: boolean;
  3300. // Inventory stock alerts
  3301. on_stock_reorder_alert?: boolean;
  3302. on_stock_break_alert?: boolean;
  3303. // Print queue events
  3304. on_queue_job_added?: boolean;
  3305. on_queue_job_assigned?: boolean;
  3306. on_queue_job_started?: boolean;
  3307. on_queue_job_waiting?: boolean;
  3308. on_queue_job_skipped?: boolean;
  3309. on_queue_job_failed?: boolean;
  3310. on_queue_completed?: boolean;
  3311. // Quiet hours
  3312. quiet_hours_enabled?: boolean;
  3313. quiet_hours_start?: string | null;
  3314. quiet_hours_end?: string | null;
  3315. // Daily digest
  3316. daily_digest_enabled?: boolean;
  3317. daily_digest_time?: string | null;
  3318. // Printer filter
  3319. printer_id?: number | null;
  3320. }
  3321. // GitHub Backup types
  3322. export type ScheduleType = 'hourly' | 'daily' | 'weekly';
  3323. export type GitProviderType = 'github' | 'gitea' | 'forgejo' | 'gitlab';
  3324. /** How many cloud accounts a backup would collect presets from. Counts only —
  3325. * with auth enabled the accounts belong to individual users, so the backup
  3326. * administrator sees how many, never whose. */
  3327. export interface CloudAccountCounts {
  3328. bambu: number;
  3329. orca: number;
  3330. }
  3331. export interface GitHubBackupConfig {
  3332. id: number;
  3333. repository_url: string;
  3334. has_token: boolean;
  3335. branch: string;
  3336. provider: GitProviderType;
  3337. allow_insecure_http: boolean;
  3338. schedule_enabled: boolean;
  3339. schedule_type: ScheduleType;
  3340. backup_kprofiles: boolean;
  3341. backup_cloud_profiles: boolean;
  3342. backup_settings: boolean;
  3343. backup_spools: boolean;
  3344. backup_archives: boolean;
  3345. enabled: boolean;
  3346. last_backup_at: string | null;
  3347. last_backup_status: string | null;
  3348. last_backup_message: string | null;
  3349. last_backup_commit_sha: string | null;
  3350. next_scheduled_run: string | null;
  3351. created_at: string;
  3352. updated_at: string;
  3353. }
  3354. export interface GitHubBackupConfigCreate {
  3355. repository_url: string;
  3356. access_token: string;
  3357. branch?: string;
  3358. provider?: GitProviderType;
  3359. allow_insecure_http?: boolean;
  3360. schedule_enabled?: boolean;
  3361. schedule_type?: ScheduleType;
  3362. backup_kprofiles?: boolean;
  3363. backup_cloud_profiles?: boolean;
  3364. backup_settings?: boolean;
  3365. backup_spools?: boolean;
  3366. backup_archives?: boolean;
  3367. enabled?: boolean;
  3368. }
  3369. export interface GitHubBackupLog {
  3370. id: number;
  3371. config_id: number;
  3372. started_at: string;
  3373. completed_at: string | null;
  3374. status: string;
  3375. trigger: string;
  3376. commit_sha: string | null;
  3377. files_changed: number;
  3378. error_message: string | null;
  3379. }
  3380. export interface GitHubBackupStatus {
  3381. configured: boolean;
  3382. enabled: boolean;
  3383. is_running: boolean;
  3384. restore_running: boolean;
  3385. progress: string | null;
  3386. last_backup_at: string | null;
  3387. last_backup_status: string | null;
  3388. next_scheduled_run: string | null;
  3389. }
  3390. // Restore from a Git backup (#2656). Cloud profiles are absent deliberately —
  3391. // the backup collector never writes them, so there is nothing to restore.
  3392. export type RestoreCategory = 'kprofiles' | 'settings' | 'spools' | 'archives';
  3393. export interface GitHubCommitInfo {
  3394. sha: string;
  3395. message: string;
  3396. author: string;
  3397. date: string;
  3398. }
  3399. export interface GitHubCommitListResponse {
  3400. success: boolean;
  3401. message: string;
  3402. branch: string;
  3403. commits: GitHubCommitInfo[];
  3404. }
  3405. /**
  3406. * Values the server interpolates into a translated note or preview detail.
  3407. * Kept to strings and numbers on purpose — anything richer would have to be
  3408. * formatted server-side and could not be translated.
  3409. */
  3410. export type GitHubRestoreParams = Record<string, string | number>;
  3411. export interface GitHubRestorePreviewCategory {
  3412. category: RestoreCategory;
  3413. available: boolean;
  3414. item_count: number;
  3415. /** English rendering. Used as i18next's defaultValue, never shown on its own. */
  3416. detail: string | null;
  3417. /** Key under backup.restoreFromGit.details, or null when there is no caveat. */
  3418. detail_code: string | null;
  3419. detail_params: GitHubRestoreParams;
  3420. }
  3421. export interface GitHubRestorePreview {
  3422. success: boolean;
  3423. message: string;
  3424. ref: string;
  3425. commit: GitHubCommitInfo | null;
  3426. metadata_version: string | null;
  3427. categories: GitHubRestorePreviewCategory[];
  3428. }
  3429. export interface GitHubRestoreRequest {
  3430. ref?: string;
  3431. categories: RestoreCategory[];
  3432. overwrite_existing?: boolean;
  3433. }
  3434. /**
  3435. * One tally note, as a translation code plus its parameters (#2656).
  3436. *
  3437. * Same contract as {@link LocalBackupPathCheck} one card down: the server picks
  3438. * the code and supplies typed params, and the client renders
  3439. * ``t(`backup.restoreFromGit.notes.${code}`, { ...params, defaultValue: message })``.
  3440. * A code the client does not know yet falls back to the English `message`
  3441. * rather than showing the raw key.
  3442. */
  3443. export interface GitHubRestoreNote {
  3444. code: string;
  3445. params: GitHubRestoreParams;
  3446. message: string;
  3447. }
  3448. export interface GitHubRestoreCategoryResult {
  3449. restored: number;
  3450. skipped: number;
  3451. failed: number;
  3452. notes: GitHubRestoreNote[];
  3453. }
  3454. export interface GitHubRestoreResponse {
  3455. success: boolean;
  3456. message: string;
  3457. log_id: number | null;
  3458. ref: string | null;
  3459. results: Record<string, GitHubRestoreCategoryResult>;
  3460. }
  3461. export interface LocalBackupStatus {
  3462. enabled: boolean;
  3463. schedule: string;
  3464. time: string;
  3465. retention: number;
  3466. path: string;
  3467. default_path: string;
  3468. is_running: boolean;
  3469. last_backup_at: string | null;
  3470. last_status: string | null;
  3471. last_message: string | null;
  3472. next_run: string | null;
  3473. timezone: string;
  3474. }
  3475. export interface LocalBackupFile {
  3476. filename: string;
  3477. size: number;
  3478. created_at: string;
  3479. }
  3480. /** Result of writing a probe file into the configured backup directory (#2544). */
  3481. export interface LocalBackupPathCheck {
  3482. writable: boolean;
  3483. path: string;
  3484. /** 'ok' | 'sandboxed' | 'read_only' | 'permission_denied' | 'no_space' | 'not_a_directory' | 'missing' | 'error' */
  3485. code: string;
  3486. /** Raw OS error, shown as-is under the translated explanation. */
  3487. detail: string | null;
  3488. /** Copy-pasteable fix (systemd drop-in, compose snippet) — not translated. */
  3489. remedy: string | null;
  3490. message: string;
  3491. /** 'container_ephemeral' — writable, but the backups die with the container. */
  3492. warning: string | null;
  3493. }
  3494. export interface ObicoDetectionEvent {
  3495. printer_id: number;
  3496. task_name: string;
  3497. timestamp: string;
  3498. current_p: number;
  3499. score: number;
  3500. class: 'safe' | 'warning' | 'failure';
  3501. detections: number;
  3502. }
  3503. export interface ObicoStatus {
  3504. is_running: boolean;
  3505. last_error: string | null;
  3506. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3507. thresholds: { low: number; high: number; pause?: number };
  3508. history: ObicoDetectionEvent[];
  3509. enabled: boolean;
  3510. ml_url: string;
  3511. sensitivity: 'low' | 'medium' | 'high';
  3512. action: 'notify' | 'pause' | 'pause_and_off';
  3513. poll_interval: number;
  3514. external_url_configured: boolean;
  3515. }
  3516. // Lightweight subset served under printers:read for the printer-card badge (#1546)
  3517. export interface ObicoPrinterStatus {
  3518. enabled: boolean;
  3519. // null = all printers are monitored
  3520. monitored_printers: number[] | null;
  3521. per_printer: Record<string, { class: string; frame_count: number; score: number }>;
  3522. // null = no error, or the viewer lacks settings:read (error strings can embed config URLs)
  3523. last_error: string | null;
  3524. }
  3525. export interface ObicoTestConnection {
  3526. ok: boolean;
  3527. status_code: number | null;
  3528. body: string | null;
  3529. error: string | null;
  3530. // Whether the ML API accepted the token. null = not determined (the health
  3531. // check failed first, or the token probe itself errored).
  3532. auth_ok: boolean | null;
  3533. }
  3534. // How sure Gadget must be before suggesting a warning or pause (API levels 1-5).
  3535. export type OctoEverywhereConfidence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';
  3536. export interface OctoEverywhereDetection {
  3537. class: 'safe' | 'warning' | 'failure' | 'error' | 'unknown';
  3538. print_quality: number | null;
  3539. frame_count: number;
  3540. error?: string | null;
  3541. error_code: string | null;
  3542. }
  3543. export interface OctoEverywhereDetectionEvent {
  3544. timestamp: string;
  3545. printer_id: number;
  3546. class: OctoEverywhereDetection['class'];
  3547. print_quality: number | null;
  3548. }
  3549. export interface OctoEverywhereStatus {
  3550. enabled: boolean;
  3551. api_key_configured: boolean;
  3552. confidence: OctoEverywhereConfidence;
  3553. action: 'notify' | 'pause' | 'pause_and_off';
  3554. poll_interval: number;
  3555. is_running: boolean;
  3556. last_error: string | null;
  3557. last_error_code: string | null;
  3558. per_printer: Record<string, OctoEverywhereDetection>;
  3559. history: OctoEverywhereDetectionEvent[];
  3560. notifications: { configured: boolean; uncovered_printers: number[] };
  3561. }
  3562. export interface OctoEverywherePrinterStatus {
  3563. enabled: boolean;
  3564. // null = all printers are monitored
  3565. monitored_printers: number[] | null;
  3566. per_printer: Record<string, OctoEverywhereDetection>;
  3567. last_error: string | null;
  3568. last_error_code: string | null;
  3569. }
  3570. export interface OctoEverywhereTestConnection {
  3571. ok: boolean;
  3572. status_code: number | null;
  3573. error: string | null;
  3574. error_code: string | null;
  3575. }
  3576. export interface GitHubTestConnectionResponse {
  3577. success: boolean;
  3578. message: string;
  3579. repo_name: string | null;
  3580. permissions: Record<string, boolean> | null;
  3581. // true = confirmed private, false = confirmed public/internal,
  3582. // null = could not determine. Backend rejects save unless true.
  3583. is_private: boolean | null;
  3584. }
  3585. export interface GitHubBackupTriggerResponse {
  3586. success: boolean;
  3587. message: string;
  3588. log_id: number | null;
  3589. commit_sha: string | null;
  3590. files_changed: number;
  3591. }
  3592. export interface NotificationTestRequest {
  3593. provider_type: ProviderType;
  3594. config: Record<string, unknown>;
  3595. attach_photo?: boolean;
  3596. /** The saved provider being edited: its stored secrets fill in the placeholders. */
  3597. provider_id?: number;
  3598. }
  3599. export interface NotificationTestResponse {
  3600. success: boolean;
  3601. message: string;
  3602. }
  3603. // Provider-specific config types for reference
  3604. export interface CallMeBotConfig {
  3605. phone: string;
  3606. apikey: string;
  3607. }
  3608. export interface NtfyConfig {
  3609. server?: string;
  3610. topic: string;
  3611. auth_token?: string | null;
  3612. }
  3613. export interface PushoverConfig {
  3614. user_key: string;
  3615. app_token: string;
  3616. priority?: number;
  3617. }
  3618. export interface NotifyConfig {
  3619. device_id: string;
  3620. token: string;
  3621. icon_url?: string;
  3622. group_type?: string;
  3623. live_activities?: boolean;
  3624. lock_screen_widgets?: boolean;
  3625. live_activity_privacy?: boolean;
  3626. live_activity_stage?: boolean;
  3627. live_activity_style?: 'bar' | 'segments' | 'none';
  3628. live_activity_metrics?: ('progress' | 'eta' | 'layers' | 'nozzle' | 'bed' | 'chamber')[];
  3629. live_activity_button_url?: string;
  3630. live_activity_symbol?: string;
  3631. live_activity_tint?: string;
  3632. time_sensitive?: boolean;
  3633. }
  3634. export interface TelegramConfig {
  3635. bot_token: string;
  3636. chat_id: string;
  3637. }
  3638. export interface EmailConfig {
  3639. smtp_server: string;
  3640. smtp_port?: number;
  3641. username: string;
  3642. password: string;
  3643. from_email: string;
  3644. to_email: string;
  3645. use_tls?: boolean;
  3646. }
  3647. // Notification Template types
  3648. export interface NotificationTemplate {
  3649. id: number;
  3650. event_type: string;
  3651. name: string;
  3652. title_template: string;
  3653. body_template: string;
  3654. is_default: boolean;
  3655. created_at: string;
  3656. updated_at: string;
  3657. }
  3658. export interface NotificationTemplateUpdate {
  3659. title_template?: string;
  3660. body_template?: string;
  3661. }
  3662. export interface EventVariablesResponse {
  3663. event_type: string;
  3664. event_name: string;
  3665. variables: string[];
  3666. supports_photo: boolean;
  3667. }
  3668. export interface TemplatePreviewRequest {
  3669. event_type: string;
  3670. title_template: string;
  3671. body_template: string;
  3672. }
  3673. export interface TemplatePreviewResponse {
  3674. title: string;
  3675. body: string;
  3676. }
  3677. // Notification Log types
  3678. export interface NotificationLogEntry {
  3679. id: number;
  3680. provider_id: number;
  3681. provider_name: string | null;
  3682. provider_type: string | null;
  3683. event_type: string;
  3684. title: string;
  3685. message: string;
  3686. success: boolean;
  3687. error_message: string | null;
  3688. printer_id: number | null;
  3689. printer_name: string | null;
  3690. created_at: string;
  3691. }
  3692. export interface NotificationLogStats {
  3693. total: number;
  3694. success_count: number;
  3695. failure_count: number;
  3696. by_event_type: Record<string, number>;
  3697. by_provider: Record<string, number>;
  3698. }
  3699. // Spoolman types
  3700. export interface SpoolmanStatus {
  3701. enabled: boolean;
  3702. connected: boolean;
  3703. url: string | null;
  3704. native_tags?: boolean; // Spoolman 0.27+ links tags natively
  3705. }
  3706. export interface SpoolmanTagMigrationReport {
  3707. dry_run: boolean;
  3708. moved: number[];
  3709. already: number;
  3710. slot_ids: number;
  3711. conflicts: Array<{ spool_id: number; tag: string; holder: number }>; // holder -1: a filament holds the tag
  3712. }
  3713. export interface SkippedSpool {
  3714. location: string;
  3715. reason: string;
  3716. filament_type: string | null;
  3717. color: string | null;
  3718. }
  3719. export interface SpoolmanSyncResult {
  3720. success: boolean;
  3721. synced_count: number;
  3722. skipped_count: number;
  3723. skipped: SkippedSpool[];
  3724. errors: string[];
  3725. }
  3726. export interface UnlinkedSpool {
  3727. id: number;
  3728. filament_name: string | null;
  3729. filament_vendor: string | null;
  3730. filament_material: string | null;
  3731. filament_color_hex: string | null;
  3732. remaining_weight: number | null;
  3733. location: string | null;
  3734. }
  3735. export interface LinkedSpoolInfo {
  3736. id: number;
  3737. remaining_weight: number | null;
  3738. filament_weight: number | null;
  3739. }
  3740. export interface LinkedSpoolsMap {
  3741. linked: Record<string, LinkedSpoolInfo>; // tag (uppercase) -> spool info
  3742. }
  3743. export interface SpoolmanVendor {
  3744. id: number;
  3745. name: string;
  3746. }
  3747. export interface SpoolmanFilamentEntry {
  3748. id: number;
  3749. name: string;
  3750. material: string | null;
  3751. color_hex: string | null;
  3752. color_name: string | null;
  3753. weight: number | null;
  3754. spool_weight: number | null;
  3755. vendor: SpoolmanVendor | null;
  3756. }
  3757. // Inventory types
  3758. // Label printing (#809). Mirror of backend.app.services.label_renderer.TemplateName.
  3759. export type SpoolLabelTemplate =
  3760. | 'ams_holder_74x33'
  3761. | 'ams_holder_75x55'
  3762. | 'box_40x30'
  3763. | 'box_62x29'
  3764. | 'avery_5160'
  3765. | 'avery_l7160';
  3766. // Mirror of backend.app.services.label_renderer.LabelField, in print order (#2981).
  3767. export const SPOOL_LABEL_FIELDS = [
  3768. 'brand',
  3769. 'material',
  3770. 'hex',
  3771. 'name',
  3772. 'location',
  3773. 'material_number',
  3774. 'temps',
  3775. 'weight',
  3776. 'note',
  3777. 'added',
  3778. 'qr',
  3779. 'spool_id',
  3780. ] as const;
  3781. export type SpoolLabelField = (typeof SPOOL_LABEL_FIELDS)[number];
  3782. // Mirror of DEFAULT_LABEL_FIELDS: what a label carried before fields were selectable.
  3783. export const DEFAULT_SPOOL_LABEL_FIELDS: SpoolLabelField[] = [
  3784. 'brand',
  3785. 'material',
  3786. 'hex',
  3787. 'name',
  3788. 'location',
  3789. 'qr',
  3790. 'spool_id',
  3791. ];
  3792. // A sheet of identical labels in a grid, in millimetres (#3296). Mirror of
  3793. // backend.app.schemas.label_template.SheetLayoutSpec.
  3794. export type LabelPageSize = 'a4' | 'letter';
  3795. export interface LabelSheetLayout {
  3796. page: LabelPageSize;
  3797. label_w_mm: number;
  3798. label_h_mm: number;
  3799. cols: number;
  3800. rows: number;
  3801. top_mm: number;
  3802. left_mm: number;
  3803. col_gap_mm: number;
  3804. row_gap_mm: number;
  3805. }
  3806. // A custom sheet saved under a name, shared by everyone on the install.
  3807. export interface SavedLabelTemplate {
  3808. id: number;
  3809. name: string;
  3810. layout: LabelSheetLayout;
  3811. created_at: string;
  3812. updated_at: string;
  3813. }
  3814. // A built-in template, or "custom" with the sheet itself in ``layout``.
  3815. export type SpoolLabelRequestTemplate = SpoolLabelTemplate | 'custom';
  3816. export interface PrintSpoolLabelsRequest {
  3817. spool_ids: number[];
  3818. template: SpoolLabelRequestTemplate;
  3819. layout?: LabelSheetLayout;
  3820. monochrome: boolean;
  3821. starting_position: number;
  3822. fields?: SpoolLabelField[];
  3823. format?: 'pdf' | 'png';
  3824. dpi?: 203 | 300 | 600;
  3825. }
  3826. export interface PreviewSpoolLabelRequest {
  3827. spool_id: number;
  3828. template: SpoolLabelRequestTemplate;
  3829. layout?: LabelSheetLayout;
  3830. monochrome: boolean;
  3831. fields: SpoolLabelField[];
  3832. }
  3833. export interface InventorySpool {
  3834. id: number;
  3835. material: string;
  3836. subtype: string | null;
  3837. color_name: string | null;
  3838. // True when color_name was synthesised from subtype because Spoolman has no
  3839. // stored value (Spoolman-backed inventory only). The edit form uses this to
  3840. // leave the input blank, so the user doesn't round-trip the synth value
  3841. // back to Spoolman as if it were a real user-set color_name (#1319).
  3842. color_name_is_synthesized?: boolean;
  3843. rgba: string | null;
  3844. // Multi-colour gradient stops (#1154): comma-separated 6/8-char hex.
  3845. extra_colors: string | null;
  3846. // Visual effect overlay: sparkle | wood | marble | glow | matte.
  3847. effect_type: string | null;
  3848. brand: string | null;
  3849. label_weight: number;
  3850. core_weight: number;
  3851. // Spoolman-backed inventory only: true when the spool has no tare of its
  3852. // own and core_weight is the filament type's. Absent for local spools (#2908).
  3853. core_weight_is_inherited?: boolean;
  3854. core_weight_catalog_id: number | null;
  3855. weight_used: number;
  3856. // Anchor for the resettable "Total Consumed" display (#1390). The
  3857. // counter shown on the Inventory page is `weight_used - weight_used_baseline`;
  3858. // remaining is still `label_weight - weight_used`, so "Reset usage to 0"
  3859. // zeroes the counter without disturbing remaining. Optional for back-compat
  3860. // with rows from a pre-migration DB snapshot — default to 0.
  3861. weight_used_baseline?: number;
  3862. slicer_filament: string | null;
  3863. slicer_filament_name: string | null;
  3864. nozzle_temp_min: number | null;
  3865. nozzle_temp_max: number | null;
  3866. note: string | null;
  3867. added_full: boolean | null;
  3868. last_used: string | null;
  3869. // Spoolman mode: when the spool was first printed with (#3407).
  3870. first_used?: string | null;
  3871. // Last drying (#2863): stamped when an AMS drying run of at least half its
  3872. // length ends, or set by hand. Temperature and hours are null when unknown.
  3873. last_dried_at?: string | null;
  3874. last_dried_temp?: number | null;
  3875. last_dried_hours?: number | null;
  3876. encode_time: string | null;
  3877. tag_uid: string | null;
  3878. tray_uuid: string | null;
  3879. data_origin: string | null;
  3880. tag_type: string | null;
  3881. archived_at: string | null;
  3882. created_at: string;
  3883. updated_at: string;
  3884. cost_per_kg: number | null;
  3885. // Spoolman mode: what prints are charged per kg, the spool's own price or
  3886. // else its filament's. Display only; the form edits cost_per_kg.
  3887. effective_cost_per_kg?: number | null;
  3888. last_scale_weight: number | null;
  3889. last_weighed_at: string | null;
  3890. // User-defined category + per-spool low-stock threshold override (#729).
  3891. category: string | null;
  3892. low_stock_threshold_pct: number | null;
  3893. // Internal material / article number (#2870) — the purchasing identifier
  3894. // shared by all spools of the same product.
  3895. material_number: string | null;
  3896. k_profiles?: SpoolKProfile[];
  3897. storage_location?: string | null;
  3898. location_id?: number | null;
  3899. // Supplier assignments (#2988). Absent in Spoolman mode — Spoolman's
  3900. // vendor is the manufacturer, not the seller, so there is no mapping.
  3901. suppliers?: SpoolSupplierLink[];
  3902. }
  3903. // ── Suppliers (#2988) ──────────────────────────────────────────────────────
  3904. /** Where filament is bought — distinct from brand (who made it). */
  3905. export interface Supplier {
  3906. id: number;
  3907. name: string;
  3908. website: string | null;
  3909. customer_number: string | null;
  3910. note: string | null;
  3911. /** Spools referencing this supplier; a referenced supplier cannot be deleted. */
  3912. spool_count: number;
  3913. created_at: string;
  3914. updated_at: string;
  3915. }
  3916. export interface SupplierInput {
  3917. name: string;
  3918. website?: string | null;
  3919. customer_number?: string | null;
  3920. note?: string | null;
  3921. }
  3922. /** One spool-to-supplier assignment as written by the spool dialog. */
  3923. export interface SpoolSupplierLinkInput {
  3924. supplier_id: number;
  3925. /** The supplier's own article number — NOT the internal material number. */
  3926. supplier_article_number?: string | null;
  3927. /** Quoted price for comparison — never the cost basis (spool.cost_per_kg). */
  3928. quoted_price_per_kg?: number | null;
  3929. /** Marks where this concrete spool was actually bought. */
  3930. is_purchase_source?: boolean;
  3931. }
  3932. export interface SpoolSupplierLink {
  3933. id: number;
  3934. supplier_id: number;
  3935. supplier_name: string;
  3936. supplier_article_number: string | null;
  3937. quoted_price_per_kg: number | null;
  3938. is_purchase_source: boolean;
  3939. }
  3940. /** Per-supplier inventory aggregate (#2988), purchase-source spools only. */
  3941. export interface SupplierStats {
  3942. supplier_id: number;
  3943. supplier_name: string;
  3944. spool_count: number;
  3945. remaining_g: number;
  3946. consumed_g: number;
  3947. cost: number;
  3948. }
  3949. /** Per-material-number inventory aggregate (#2870). */
  3950. export interface MaterialNumberStats {
  3951. material_number: string;
  3952. spool_count: number;
  3953. remaining_g: number;
  3954. consumed_g: number;
  3955. cost: number;
  3956. }
  3957. export interface SpoolmanBulkCreateResult {
  3958. created: InventorySpool[];
  3959. requested_count: number;
  3960. failed_count: number;
  3961. }
  3962. // ── CSV import/export (#1576) ──────────────────────────────────────────────
  3963. /** One row's outcome from the import preview / real import. */
  3964. export interface CsvImportRow {
  3965. row_number: number;
  3966. status: 'valid' | 'error' | 'skipped';
  3967. /** The id the spool is created with (#3520); null gets the next free one. */
  3968. keeps_id?: number | null;
  3969. reason: string | null;
  3970. material: string | null;
  3971. brand: string | null;
  3972. color_name: string | null;
  3973. rgba: string | null;
  3974. /** rgba/extra_colors/effect_type were filled from the Color Catalog. */
  3975. resolved_color: boolean;
  3976. /** The catalog match came from a different material's variant (no exact
  3977. * material match). Shown as a warning in the preview. */
  3978. cross_material_color: boolean;
  3979. /** An active spool with the same material+brand+color already exists.
  3980. * Informational only — the import still creates the row. */
  3981. duplicate_of_existing: boolean;
  3982. }
  3983. /** Dry-run preview: per-row classification, no rows written. */
  3984. export interface CsvImportPreview {
  3985. columns: string[];
  3986. total: number;
  3987. valid_count: number;
  3988. error_count: number;
  3989. skipped_count: number;
  3990. rows: CsvImportRow[];
  3991. warnings: string[];
  3992. }
  3993. /** Summary returned after a real (non-dry-run) import. */
  3994. export interface CsvImportResult {
  3995. created: number;
  3996. skipped: number;
  3997. errors: number;
  3998. error_rows: CsvImportRow[];
  3999. }
  4000. export interface SpoolUsageRecord {
  4001. id: number;
  4002. // null: the spool was deleted, its usage kept
  4003. spool_id: number | null;
  4004. // Spoolman mode: the Spoolman spool charged (#3407); spool_id is null then.
  4005. spoolman_spool_id?: number | null;
  4006. printer_id: number | null;
  4007. print_name: string | null;
  4008. weight_used: number;
  4009. percent_used: number;
  4010. status: string;
  4011. cost: number | null;
  4012. created_at: string;
  4013. }
  4014. export interface SpoolKProfile {
  4015. id: number;
  4016. spool_id: number;
  4017. printer_id: number;
  4018. extruder: number;
  4019. nozzle_diameter: string;
  4020. nozzle_type: string | null;
  4021. k_value: number;
  4022. name: string | null;
  4023. cali_idx: number | null;
  4024. setting_id: string | null;
  4025. created_at: string;
  4026. }
  4027. export interface SpoolKProfileInput {
  4028. printer_id: number;
  4029. extruder?: number;
  4030. nozzle_diameter?: string;
  4031. nozzle_type?: string | null;
  4032. k_value: number;
  4033. name?: string | null;
  4034. cali_idx?: number | null;
  4035. setting_id?: string | null;
  4036. }
  4037. /**
  4038. * One per-printer-model override of a spool's slicer filament preset.
  4039. *
  4040. * A cloud or Orca preset is bound to a printer model ("@BBL X1C"), so the
  4041. * spool's single `slicer_filament` is wrong as soon as the spool is used on a
  4042. * second model. `nozzle_diameter` is "" for the model's own default and a bare
  4043. * decimal ("0.2") for a per-hotend exception; the backend resolves
  4044. * exact (model, diameter) -> (model, "") -> the spool's own preset.
  4045. */
  4046. export interface SlotSpoolDefaults {
  4047. slicer_filament: string | null;
  4048. slicer_filament_name: string | null;
  4049. cali_idx: number | null;
  4050. k_value: number | null;
  4051. profile_name: string | null;
  4052. extruder: number | null;
  4053. nozzle_diameter: string;
  4054. }
  4055. export interface SpoolFilamentPresetInput {
  4056. printer_model: string;
  4057. nozzle_diameter: string;
  4058. slicer_filament: string | null;
  4059. slicer_filament_name: string | null;
  4060. }
  4061. export interface SpoolFilamentPreset extends SpoolFilamentPresetInput {
  4062. id: number;
  4063. spool_id: number;
  4064. created_at: string;
  4065. }
  4066. /**
  4067. * What a new spool of one product starts with (#1326): the slicer preset, the
  4068. * per-model preset overrides and the K profiles. `color_name` "" is the
  4069. * default for every colour of the product; one with a colour wins over it per
  4070. * preset and per hotend. Shared by both inventory modes.
  4071. */
  4072. export interface ProfileDefaultKey {
  4073. brand: string;
  4074. material: string;
  4075. subtype: string;
  4076. color_name: string;
  4077. }
  4078. export interface ProfileDefaultInput extends ProfileDefaultKey {
  4079. slicer_filament: string | null;
  4080. slicer_filament_name: string | null;
  4081. presets: SpoolFilamentPresetInput[];
  4082. k_profiles: SpoolKProfileInput[];
  4083. }
  4084. export interface ProfileDefault extends ProfileDefaultInput {
  4085. id: number;
  4086. updated_at: string;
  4087. }
  4088. /** Both levels of a product's default merged, as a create applies them. */
  4089. export interface ResolvedProfileDefault {
  4090. slicer_filament: string | null;
  4091. slicer_filament_name: string | null;
  4092. presets: SpoolFilamentPresetInput[];
  4093. k_profiles: SpoolKProfileInput[];
  4094. default_ids: number[];
  4095. }
  4096. /** One inventory-bound AMS slot, as returned by `/printers/{id}/inventory-remain`. */
  4097. export interface SlotMaterial {
  4098. ams_id: number;
  4099. tray_id: number;
  4100. global_tray_id: number;
  4101. /** Opaque grouping key from the backend. Two slots back each other up under
  4102. * AMS Filament Backup only when both `material_key` and `extruder` match.
  4103. * Never parse it — the format belongs to the backend's identity rule. */
  4104. material_key: string;
  4105. remaining_g: number;
  4106. /** 0 = right / single nozzle, 1 = left. */
  4107. extruder: number;
  4108. /** How the bound spool should be *named* — display only, never matched on.
  4109. * The printer has no brand field and reports no sub-brand for a
  4110. * third-party spool, so this is the only place a slot's real identity
  4111. * exists. Null when the binding resolves to a spool we cannot describe. */
  4112. spool?: SlotSpoolIdentity | null;
  4113. /** Per-kg rate a print off this spool is charged at; null when unpriced,
  4114. * which is charged at the default rate. Optional for an older backend. */
  4115. cost_per_kg?: number | null;
  4116. }
  4117. /** Display identity of an inventory-bound slot. See `SlotMaterial.spool`. */
  4118. export interface SlotSpoolIdentity {
  4119. brand: string | null;
  4120. material: string | null;
  4121. subtype: string | null;
  4122. color_name: string | null;
  4123. rgba: string | null;
  4124. /** Comma-separated hex stops for a multi-colour spool, and the effect
  4125. * overlay — the two things a tray record cannot carry, so a slot swatch
  4126. * can be drawn the way the inventory row draws it (#3159).
  4127. *
  4128. * Optional rather than required: the backend sends both keys on every
  4129. * binding, but a frontend running against an older one gets neither, and
  4130. * every reader here already falls back to a solid swatch. */
  4131. extra_colors?: string | null;
  4132. effect_type?: string | null;
  4133. }
  4134. export interface InventoryRemainResponse {
  4135. /** Currently-loaded, inventory-bound slots only — drives the prefer-lowest sort. */
  4136. inventory_remain_g: Record<string, number>;
  4137. /** Every inventory binding on the printer, with identity + extruder side. */
  4138. slot_materials: SlotMaterial[];
  4139. }
  4140. export interface SpoolAssignment {
  4141. id: number;
  4142. spool_id: number;
  4143. printer_id: number;
  4144. printer_name: string | null;
  4145. ams_id: number;
  4146. tray_id: number;
  4147. fingerprint_color: string | null;
  4148. fingerprint_type: string | null;
  4149. spool?: InventorySpool | null;
  4150. configured: boolean;
  4151. pending_config?: boolean; // Slot was empty at assign time; will configure on insert
  4152. created_at: string;
  4153. ams_label?: string | null; // User-defined friendly name for the AMS unit
  4154. printer_model?: string | null; // names a rack printer's external inputs "Ext-n" (utils/trayIds)
  4155. }
  4156. export interface FilamentSkuSettings {
  4157. id: number;
  4158. material: string;
  4159. subtype: string | null;
  4160. brand: string | null;
  4161. color_name: string | null;
  4162. lead_time_days: number;
  4163. safety_margin_value: number;
  4164. safety_margin_unit: 'days' | 'g';
  4165. alerts_snoozed: boolean;
  4166. }
  4167. export interface ShoppingListItem {
  4168. id: number;
  4169. material: string;
  4170. subtype: string | null;
  4171. brand: string | null;
  4172. color_name: string | null;
  4173. quantity_spools: number;
  4174. note: string | null;
  4175. status: 'pending' | 'purchased' | 'received';
  4176. purchased_at: string | null;
  4177. added_at: string;
  4178. }
  4179. export interface ShoppingListItemCreate {
  4180. material: string;
  4181. subtype: string | null;
  4182. brand: string | null;
  4183. color_name: string | null;
  4184. quantity_spools: number;
  4185. note?: string | null;
  4186. }
  4187. // Update types
  4188. export interface VersionInfo {
  4189. version: string;
  4190. repo: string;
  4191. }
  4192. export interface UpdateCheckResult {
  4193. update_available: boolean;
  4194. current_version: string;
  4195. latest_version: string | null;
  4196. release_name?: string;
  4197. release_notes?: string;
  4198. release_url?: string;
  4199. published_at?: string;
  4200. error?: string;
  4201. message?: string;
  4202. is_docker?: boolean;
  4203. is_ha_addon?: boolean;
  4204. is_windows_installer?: boolean;
  4205. update_method?: 'docker' | 'git' | 'ha_addon' | 'windows_installer';
  4206. installer_download_url?: string | null;
  4207. // Best-effort guess at the compose directory (#2664). Prefill only — the
  4208. // value the user saved lives on AppSettings.docker_compose_dir, so clearing
  4209. // that field falls back to this guess instead of resurrecting the old value.
  4210. compose_dir_detected?: string | null;
  4211. }
  4212. export interface UpdateStatus {
  4213. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  4214. progress: number;
  4215. message: string;
  4216. error: string | null;
  4217. }
  4218. // Maintenance types
  4219. export interface MaintenanceType {
  4220. id: number;
  4221. name: string;
  4222. description: string | null;
  4223. default_interval_hours: number;
  4224. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  4225. icon: string | null;
  4226. wiki_url: string | null; // Documentation link
  4227. is_system: boolean;
  4228. created_at: string;
  4229. }
  4230. export interface MaintenanceTypeCreate {
  4231. name: string;
  4232. description?: string | null;
  4233. default_interval_hours?: number;
  4234. interval_type?: 'hours' | 'days';
  4235. icon?: string | null;
  4236. wiki_url?: string | null;
  4237. }
  4238. export interface MaintenanceStatus {
  4239. id: number;
  4240. printer_id: number;
  4241. printer_name: string;
  4242. printer_model: string | null;
  4243. maintenance_type_id: number;
  4244. maintenance_type_name: string;
  4245. maintenance_type_icon: string | null;
  4246. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  4247. enabled: boolean;
  4248. interval_hours: number; // For hours type: print hours; for days type: number of days
  4249. interval_type: 'hours' | 'days';
  4250. current_hours: number;
  4251. hours_since_maintenance: number;
  4252. hours_until_due: number;
  4253. days_since_maintenance: number | null; // For days type
  4254. days_until_due: number | null; // For days type
  4255. is_due: boolean;
  4256. is_warning: boolean;
  4257. last_performed_at: string | null;
  4258. }
  4259. export interface PrinterMaintenanceOverview {
  4260. printer_id: number;
  4261. printer_name: string;
  4262. printer_model: string | null;
  4263. total_print_hours: number;
  4264. maintenance_items: MaintenanceStatus[];
  4265. due_count: number;
  4266. warning_count: number;
  4267. }
  4268. // External Links (sidebar)
  4269. export interface ExternalLink {
  4270. id: number;
  4271. name: string;
  4272. url: string;
  4273. icon: string;
  4274. open_in_new_tab: boolean;
  4275. custom_icon: string | null;
  4276. sort_order: number;
  4277. created_at: string;
  4278. updated_at: string;
  4279. /** Count reported by the app the link points to, while it keeps reporting. */
  4280. badge_count?: number | null;
  4281. }
  4282. export interface ExternalLinkCreate {
  4283. name: string;
  4284. url: string;
  4285. icon: string;
  4286. open_in_new_tab?: boolean;
  4287. }
  4288. export interface ExternalLinkUpdate {
  4289. name?: string;
  4290. url?: string;
  4291. icon?: string;
  4292. open_in_new_tab?: boolean;
  4293. }
  4294. // Finance types
  4295. export interface CostCenterSummary {
  4296. id: number;
  4297. name: string;
  4298. is_private: boolean;
  4299. owner_user_id: number | null;
  4300. is_active: boolean;
  4301. total_balance: number;
  4302. total_budget: number | null;
  4303. monthly_budget: number | null;
  4304. budget_mode: 'none' | 'total' | 'monthly';
  4305. budget_limit: number | null;
  4306. budget_used: number | null;
  4307. budget_available: number | null;
  4308. can_print: boolean;
  4309. }
  4310. export interface CostCenterCreateRequest {
  4311. name: string;
  4312. total_budget?: number | null;
  4313. monthly_budget?: number | null;
  4314. is_active?: boolean;
  4315. }
  4316. export interface CostCenterBudgetUpdateRequest {
  4317. total_budget?: number | null;
  4318. monthly_budget?: number | null;
  4319. }
  4320. export interface CostCenterUpdateRequest {
  4321. name?: string;
  4322. is_active?: boolean;
  4323. }
  4324. export interface CostCenterMemberRequest {
  4325. user_id: number;
  4326. can_print?: boolean;
  4327. }
  4328. export interface CostCenterMemberResponse {
  4329. id: number;
  4330. cost_center_id: number;
  4331. user_id: number;
  4332. can_print: boolean;
  4333. created_at: string;
  4334. }
  4335. export interface CostCenterDetail extends CostCenterSummary {
  4336. members: CostCenterMemberResponse[];
  4337. }
  4338. export interface WalletBalance {
  4339. user_id: number;
  4340. balance: number;
  4341. currency: string;
  4342. updated_at: string | null;
  4343. }
  4344. export type WalletTransactionType = 'print_charge' | 'deposit' | 'withdraw' | 'manual_adjustment';
  4345. export interface WalletTransaction {
  4346. id: number;
  4347. user_id: number | null; // null once the user is deleted
  4348. cost_center_id: number | null;
  4349. transaction_type: WalletTransactionType;
  4350. amount: number;
  4351. balance_after: number | null;
  4352. description: string | null;
  4353. created_by_user_id: number | null;
  4354. print_run_id: string | null;
  4355. print_archive_id: number | null;
  4356. print_queue_id: number | null;
  4357. created_at: string;
  4358. }
  4359. export interface WalletTransactionListResponse {
  4360. items: WalletTransaction[];
  4361. total: number;
  4362. limit: number;
  4363. offset: number;
  4364. }
  4365. export interface WalletAdjustmentRequest {
  4366. amount: number;
  4367. description?: string;
  4368. cost_center_id?: number | null;
  4369. }
  4370. export interface WalletAdjustmentResponse {
  4371. transaction: WalletTransaction;
  4372. balance: WalletBalance;
  4373. }
  4374. export interface TransactionEditRequest {
  4375. user_id?: number | null;
  4376. cost_center_id?: number | null;
  4377. amount?: number | null;
  4378. description?: string | null;
  4379. }
  4380. export interface ManualPrintRequest {
  4381. user_id: number;
  4382. cost_center_id: number;
  4383. amount: number;
  4384. description?: string | null;
  4385. created_at?: string | null;
  4386. }
  4387. // Permission type - all available permissions
  4388. export type Permission =
  4389. | 'printers:read' | 'printers:create' | 'printers:update' | 'printers:delete' | 'printers:control' | 'printers:files' | 'printers:ams_rfid' | 'printers:clear_plate'
  4390. | 'archives:read' | 'archives:read_own' | 'archives:read_all' | 'archives:create'
  4391. | 'archives:update_own' | 'archives:update_all' | 'archives:delete_own' | 'archives:delete_all'
  4392. | 'archives:reprint_own' | 'archives:reprint_all' | 'archives:purge'
  4393. | 'queue:read' | 'queue:read_own' | 'queue:read_all' | 'queue:create'
  4394. | 'queue:update_own' | 'queue:update_all' | 'queue:delete_own' | 'queue:delete_all'
  4395. | 'queue:reorder' | 'queue:start_unreviewed'
  4396. | 'library:read' | 'library:read_own' | 'library:read_all' | 'library:upload'
  4397. | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all'
  4398. | 'library:purge'
  4399. | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete'
  4400. | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete'
  4401. | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments'
  4402. | 'inventory:forecast_read' | 'inventory:forecast_write'
  4403. | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control'
  4404. | 'camera:view'
  4405. | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete'
  4406. | 'kprofiles:read' | 'kprofiles:create' | 'kprofiles:update' | 'kprofiles:delete'
  4407. | 'notifications:read' | 'notifications:create' | 'notifications:update' | 'notifications:delete' | 'notifications:user_email'
  4408. | 'notification_templates:read' | 'notification_templates:update'
  4409. | 'external_links:read' | 'external_links:create' | 'external_links:update' | 'external_links:delete'
  4410. | 'discovery:scan'
  4411. | 'firmware:read' | 'firmware:update'
  4412. | 'ams_history:read'
  4413. | 'cost_centers:read_own' | 'cost_centers:read_all' | 'cost_centers:modify' | 'cost_centers:create'
  4414. | 'stats:read' | 'stats:filter_by_user'
  4415. | 'system:read'
  4416. | 'settings:read' | 'settings:update' | 'settings:backup' | 'settings:restore'
  4417. | 'github:backup' | 'github:restore'
  4418. | 'cloud:auth' | 'orca_cloud:auth'
  4419. | 'makerworld:view' | 'makerworld:import'
  4420. | 'manyfold:view' | 'manyfold:import'
  4421. | 'api_keys:read' | 'api_keys:create' | 'api_keys:update' | 'api_keys:delete'
  4422. | 'users:read' | 'users:read_slim' | 'users:create' | 'users:update' | 'users:delete'
  4423. | 'groups:read' | 'groups:create' | 'groups:update' | 'groups:delete'
  4424. | 'pipelines:read' | 'pipelines:write' | 'pipelines:run'
  4425. | 'websocket:connect';
  4426. // Group types
  4427. export interface GroupBrief {
  4428. id: number;
  4429. name: string;
  4430. }
  4431. export interface Group {
  4432. id: number;
  4433. name: string;
  4434. description: string | null;
  4435. permissions: Permission[];
  4436. is_system: boolean;
  4437. /** Members only see the printers in printer_ids plus every printer in locations (#1727) */
  4438. restrict_printers: boolean;
  4439. printer_ids: number[];
  4440. /** Matched against Printer.location, so printers added there later are included */
  4441. locations: string[];
  4442. user_count: number;
  4443. created_at: string;
  4444. updated_at: string;
  4445. }
  4446. export interface GroupDetail extends Group {
  4447. users: Array<{ id: number; username: string; is_active: boolean }>;
  4448. }
  4449. export interface GroupCreate {
  4450. name: string;
  4451. description?: string;
  4452. permissions: Permission[];
  4453. restrict_printers?: boolean;
  4454. printer_ids?: number[];
  4455. locations?: string[];
  4456. }
  4457. export interface GroupUpdate {
  4458. name?: string;
  4459. description?: string;
  4460. permissions?: Permission[];
  4461. restrict_printers?: boolean;
  4462. printer_ids?: number[];
  4463. locations?: string[];
  4464. }
  4465. export interface PermissionInfo {
  4466. value: Permission;
  4467. label: string;
  4468. }
  4469. export interface PermissionCategory {
  4470. name: string;
  4471. permissions: PermissionInfo[];
  4472. }
  4473. export interface PermissionsListResponse {
  4474. categories: PermissionCategory[];
  4475. all_permissions: Permission[];
  4476. }
  4477. // User email notification preferences
  4478. export interface UserEmailPreferences {
  4479. notify_print_start: boolean;
  4480. notify_print_complete: boolean;
  4481. notify_print_failed: boolean;
  4482. notify_print_stopped: boolean;
  4483. }
  4484. // Auth types
  4485. export interface LoginRequest {
  4486. username: string;
  4487. password: string;
  4488. }
  4489. export interface LoginResponse {
  4490. access_token?: string;
  4491. token_type?: string;
  4492. user?: UserResponse;
  4493. /** Set when 2FA verification is required before a full token is issued. */
  4494. requires_2fa?: boolean;
  4495. pre_auth_token?: string;
  4496. two_fa_methods?: string[];
  4497. }
  4498. export interface UserResponse {
  4499. id: number;
  4500. username: string;
  4501. email?: string;
  4502. role: string; // Deprecated, kept for backward compatibility
  4503. is_active: boolean;
  4504. is_admin: boolean; // Computed from role and group membership
  4505. auth_source: string; // "local" or "ldap"
  4506. groups: GroupBrief[];
  4507. permissions: Permission[]; // All permissions from groups
  4508. created_at: string;
  4509. }
  4510. /**
  4511. * Just enough to label an owner id (#1894). Backed by GET /users/slim, which
  4512. * is readable with `users:read_slim` as well as the admin-level `users:read`
  4513. * -- use it anywhere a screen only needs to turn a `created_by_id` into a
  4514. * name, so operators are not forced into the full listing to get one.
  4515. */
  4516. export interface UserSlim {
  4517. id: number;
  4518. username: string;
  4519. }
  4520. export interface UserCreate {
  4521. username: string;
  4522. password?: string; // Optional when advanced auth is enabled
  4523. email?: string;
  4524. role: string;
  4525. group_ids?: number[];
  4526. }
  4527. export interface UserUpdate {
  4528. username?: string;
  4529. password?: string;
  4530. email?: string;
  4531. role?: string;
  4532. is_active?: boolean;
  4533. group_ids?: number[];
  4534. }
  4535. export interface SetupRequest {
  4536. auth_enabled: boolean;
  4537. admin_username?: string;
  4538. admin_password?: string;
  4539. }
  4540. export interface ForgotPasswordRequest {
  4541. email: string;
  4542. }
  4543. export interface ForgotPasswordResponse {
  4544. message: string;
  4545. }
  4546. export interface ResetPasswordRequest {
  4547. user_id: number;
  4548. }
  4549. export interface ResetPasswordResponse {
  4550. message: string;
  4551. }
  4552. export interface SMTPSettings {
  4553. smtp_host: string;
  4554. smtp_port: number;
  4555. smtp_username?: string;
  4556. smtp_password?: string;
  4557. smtp_security: 'starttls' | 'ssl' | 'none';
  4558. smtp_auth_enabled: boolean;
  4559. smtp_from_email: string;
  4560. smtp_from_name: string;
  4561. }
  4562. // 2FA / MFA interfaces
  4563. export interface TwoFAStatus {
  4564. totp_enabled: boolean;
  4565. email_otp_enabled: boolean;
  4566. backup_codes_remaining: number;
  4567. }
  4568. export interface TOTPSetupResponse {
  4569. secret: string;
  4570. qr_code_b64: string;
  4571. issuer: string;
  4572. }
  4573. export interface TOTPEnableResponse {
  4574. message: string;
  4575. backup_codes: string[];
  4576. }
  4577. export interface BackupCodesResponse {
  4578. backup_codes: string[];
  4579. message: string;
  4580. }
  4581. export interface TwoFAVerifyRequest {
  4582. pre_auth_token: string;
  4583. code: string;
  4584. method: 'totp' | 'email' | 'backup';
  4585. }
  4586. /**
  4587. * A URL that is known to be same-origin (a relative path starting with ``/``).
  4588. *
  4589. * Branded so that producers of same-origin URLs (e.g. ``api.oidcProviderIconUrl``)
  4590. * can be distinguished from arbitrary strings at the type level. The brand
  4591. * is compile-time only; at runtime these are plain strings.
  4592. *
  4593. * Purpose: CSP-safe image sources for ``<img src=...>``. The strict
  4594. * ``img-src 'self' data: blob:`` CSP rejects anything that isn't same-origin,
  4595. * so callers that demand a ``SameOriginUrl`` get a compile-time guarantee
  4596. * that no external URL slips through.
  4597. */
  4598. export type SameOriginUrl = string & { readonly __brand: 'SameOriginUrl' };
  4599. // OIDC interfaces
  4600. /** What the unauthenticated GET /auth/oidc/providers returns (#3107): only
  4601. * what the login page renders. The full provider, group sync config
  4602. * included, needs the admin-only /auth/oidc/providers/all. */
  4603. export interface OIDCProviderPublic {
  4604. id: number;
  4605. name: string;
  4606. has_icon: boolean;
  4607. is_autologin: boolean;
  4608. }
  4609. export interface OIDCProvider {
  4610. id: number;
  4611. name: string;
  4612. issuer_url: string;
  4613. client_id: string;
  4614. scopes: string;
  4615. is_enabled: boolean;
  4616. auto_create_users: boolean;
  4617. auto_link_existing_accounts: boolean;
  4618. email_claim: string;
  4619. require_email_verified: boolean;
  4620. // #3107 — group sync. Empty mapping = sync off (default).
  4621. group_claim?: string;
  4622. group_mapping?: Record<string, string>;
  4623. icon_url?: string | null;
  4624. default_group_id?: number | null;
  4625. // True when the backend has cached icon bytes for this provider.
  4626. // Login page / admin preview consume this via the proxy URL
  4627. // /api/v1/auth/oidc/providers/{id}/icon (#1333) so the SPA never
  4628. // hotlinks the external icon URL — that would require loosening
  4629. // the strict img-src CSP. Required, not optional: the backend always
  4630. // includes this field in the response (Pydantic default-False is
  4631. // populated unconditionally in the route handler).
  4632. has_icon: boolean;
  4633. // #1589: when true, the LoginPage redirects unauthenticated visitors
  4634. // straight to this provider on mount. At most one provider may carry this.
  4635. is_autologin: boolean;
  4636. // #2593: defined by BAMBUDDY_OIDC_* and rewritten from the environment on
  4637. // every boot. The API answers 409 to any write, so the settings UI must not
  4638. // offer edit/delete controls that cannot succeed. Optional so a response
  4639. // from an older backend still type-checks.
  4640. is_env_managed?: boolean;
  4641. }
  4642. export interface OIDCProviderCreate {
  4643. name: string;
  4644. issuer_url: string;
  4645. client_id: string;
  4646. client_secret: string;
  4647. scopes?: string;
  4648. is_enabled?: boolean;
  4649. auto_create_users?: boolean;
  4650. auto_link_existing_accounts?: boolean;
  4651. email_claim?: string;
  4652. require_email_verified?: boolean;
  4653. // #3107 — group sync. Omit both to leave them unchanged on update.
  4654. group_claim?: string;
  4655. group_mapping?: Record<string, string>;
  4656. icon_url?: string | null;
  4657. default_group_id?: number | null;
  4658. is_autologin?: boolean; // #1589
  4659. }
  4660. export interface OIDCLink {
  4661. id: number;
  4662. provider_id: number;
  4663. provider_name: string;
  4664. provider_email?: string | null;
  4665. created_at: string;
  4666. }
  4667. export interface TestSMTPRequest {
  4668. test_recipient: string;
  4669. // The form's settings, tested before they are saved. An empty password
  4670. // keeps the saved one.
  4671. smtp?: SMTPSettings;
  4672. }
  4673. export interface TestSMTPResponse {
  4674. success: boolean;
  4675. message: string;
  4676. }
  4677. export interface AdvancedAuthStatus {
  4678. advanced_auth_enabled: boolean;
  4679. smtp_configured: boolean;
  4680. // #1589: false hides the username/password form on the LoginPage; the env
  4681. // var BAMBUDDY_LOCAL_LOGIN=true on the server flips this back to true so
  4682. // the recovery path remains visible.
  4683. local_login_enabled: boolean;
  4684. // #1589: when set, LoginPage redirects to this provider's authorize URL
  4685. // on mount unless ?fallback=local is in the URL or the redirect times out.
  4686. autologin_provider_id: number | null;
  4687. }
  4688. export interface LDAPStatus {
  4689. ldap_enabled: boolean;
  4690. ldap_configured: boolean;
  4691. }
  4692. export interface EncryptionRowCounts {
  4693. oidc_providers: number;
  4694. user_totp: number;
  4695. }
  4696. export interface EncryptionStatus {
  4697. key_configured: boolean;
  4698. key_source: 'env' | 'file' | 'generated' | 'none';
  4699. legacy_plaintext_rows: EncryptionRowCounts;
  4700. encrypted_rows: EncryptionRowCounts;
  4701. decryption_broken: boolean;
  4702. // B2: count of rows skipped during the last legacy re-encryption migration.
  4703. // Surfaced via a yellow secondary banner in SecurityStatusCard.
  4704. migration_error_count: number;
  4705. }
  4706. export interface LDAPTestRequest {
  4707. ldap_server_url?: string;
  4708. ldap_bind_dn?: string;
  4709. ldap_bind_password?: string;
  4710. ldap_search_base?: string;
  4711. ldap_user_filter?: string;
  4712. ldap_security?: string;
  4713. }
  4714. export interface LDAPTestResponse {
  4715. success: boolean;
  4716. message: string;
  4717. }
  4718. export interface LDAPSearchResult {
  4719. username: string;
  4720. email: string | null;
  4721. display_name: string | null;
  4722. dn: string;
  4723. already_provisioned: boolean;
  4724. }
  4725. export interface SetupResponse {
  4726. auth_enabled: boolean;
  4727. admin_created?: boolean;
  4728. }
  4729. export interface AuthStatus {
  4730. auth_enabled: boolean;
  4731. requires_setup: boolean;
  4732. }
  4733. // API functions
  4734. export interface QueueHistoryFilters {
  4735. printerId?: number | null;
  4736. status?: string;
  4737. location?: string;
  4738. }
  4739. export interface QueueHistoryParams extends QueueHistoryFilters {
  4740. sortBy?: 'date' | 'name' | 'printer';
  4741. // Flips the default order: newest first by date, A to Z by name or printer.
  4742. reverse?: boolean;
  4743. limit?: number;
  4744. offset?: number;
  4745. }
  4746. export interface QueueHistoryPage {
  4747. // The page in display order, then any other runs of the batches on it.
  4748. items: PrintQueueItem[];
  4749. total: number;
  4750. locations: string[];
  4751. }
  4752. function queueHistorySearch(params: QueueHistoryParams): URLSearchParams {
  4753. const search = new URLSearchParams();
  4754. if (params.printerId) search.set('printer_id', String(params.printerId));
  4755. if (params.status) search.set('status', params.status);
  4756. if (params.location) search.set('location', params.location);
  4757. if (params.sortBy) search.set('sort_by', params.sortBy);
  4758. if (params.reverse) search.set('reverse', 'true');
  4759. if (params.limit !== undefined) search.set('limit', String(params.limit));
  4760. if (params.offset) search.set('offset', String(params.offset));
  4761. return search;
  4762. }
  4763. // Per-printer reads that a page showing every printer makes once per printer,
  4764. // coalesced into one bulk request per few milliseconds (see ./batch). Each
  4765. // keeps its single-printer request for a lone id.
  4766. const idsParam = (ids: number[]) => `ids=${ids.join(',')}`;
  4767. const printerStatusBatch = batched(
  4768. (id) => request<PrinterStatus>(`/printers/${id}/status`),
  4769. async (ids) => byField(await request<PrinterStatus[]>(`/bulk/printer-statuses?${idsParam(ids)}`), (s) => s.id),
  4770. );
  4771. const slotPresetsBatch = batched(
  4772. (id) => request<Record<number, SlotPresetMapping>>(`/printers/${id}/slot-presets`),
  4773. async (ids) => byId(await request<Record<string, Record<number, SlotPresetMapping>>>(`/bulk/slot-presets?${idsParam(ids)}`)),
  4774. );
  4775. const amsLabelsBatch = batched(
  4776. (id) => request<Record<number, string>>(`/printers/${id}/ams-labels`),
  4777. async (ids) => byId(await request<Record<string, Record<number, string>>>(`/bulk/ams-labels?${idsParam(ids)}`)),
  4778. );
  4779. type PrinterCardPlugs = { plug: SmartPlug | null; scripts: SmartPlug[] };
  4780. const cardPlugs = async (ids: number[]) =>
  4781. byId(await request<Record<string, PrinterCardPlugs>>(`/bulk/card-plugs?${idsParam(ids)}`));
  4782. const smartPlugBatch = batched(
  4783. (id) => request<SmartPlug | null>(`/smart-plugs/by-printer/${id}`),
  4784. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.plug])),
  4785. );
  4786. const scriptPlugsBatch = batched(
  4787. (id) => request<SmartPlug[]>(`/smart-plugs/by-printer/${id}/scripts`),
  4788. async (ids) => new Map([...(await cardPlugs(ids))].map(([id, plugs]) => [id, plugs.scripts])),
  4789. );
  4790. const haSensorReadingsBatch = batched(
  4791. (id) => request<PrinterHASensorReading[]>(`/ha-sensors/by-printer/${id}/readings`),
  4792. async (ids) => byId(await request<Record<string, PrinterHASensorReading[]>>(`/bulk/ha-sensor-readings?${idsParam(ids)}`)),
  4793. );
  4794. const firmwareUpdateBatch = batched(
  4795. (id) => request<FirmwareUpdateInfo>(`/firmware/updates/${id}`),
  4796. async (ids) =>
  4797. byField(await request<FirmwareUpdateInfo[]>(`/bulk/firmware-updates?${idsParam(ids)}`), (u) => u.printer_id),
  4798. );
  4799. // One batcher per status asked for: the bulk route takes a single status list.
  4800. const printerQueueBatches = new Map<string, (id: number) => Promise<PrintQueueItem[]>>();
  4801. const printerQueueBatch = (status: string) => {
  4802. let batch = printerQueueBatches.get(status);
  4803. if (!batch) {
  4804. batch = batched(
  4805. (id) => request<PrintQueueItem[]>(`/queue/?printer_id=${id}&status=${encodeURIComponent(status)}`),
  4806. async (ids) =>
  4807. byId(
  4808. await request<Record<string, PrintQueueItem[]>>(
  4809. `/bulk/printer-queues?${idsParam(ids)}&status=${encodeURIComponent(status)}`,
  4810. ),
  4811. ),
  4812. );
  4813. printerQueueBatches.set(status, batch);
  4814. }
  4815. return batch;
  4816. };
  4817. const foldersByArchiveBatch = batched(
  4818. (id) => request<LibraryFolder[]>(`/library/folders/by-archive/${id}`),
  4819. async (ids) => byId(await request<Record<string, LibraryFolder[]>>(`/bulk/archive-folders?${idsParam(ids)}`)),
  4820. );
  4821. export const api = {
  4822. // Overlay branding
  4823. getOverlayLogo: async (token: string | null, signal?: AbortSignal): Promise<Blob | null> => {
  4824. const endpoint = token ? `/overlay-branding/logo?token=${encodeURIComponent(token)}` : '/settings/overlay-logo';
  4825. const response = await fetch(`${API_BASE}${endpoint}`, {
  4826. signal, cache: 'no-store',
  4827. headers: !token && authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4828. });
  4829. if (response.status === 404) return null;
  4830. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4831. return response.blob();
  4832. },
  4833. uploadOverlayLogo: async (file: File): Promise<void> => {
  4834. const body = new FormData();
  4835. body.append('file', file);
  4836. const response = await fetch(`${API_BASE}/settings/overlay-logo`, {
  4837. method: 'POST', body,
  4838. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  4839. });
  4840. if (!response.ok) {
  4841. const error = await response.json().catch(() => ({}));
  4842. const detail = error?.detail;
  4843. const message = typeof detail === 'string' ? detail : detail?.message;
  4844. throw new Error(typeof message === 'string' && message ? message : `HTTP ${response.status}`);
  4845. }
  4846. },
  4847. deleteOverlayLogo: () => request<{ status: string }>('/settings/overlay-logo', { method: 'DELETE' }),
  4848. // Authentication
  4849. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  4850. setupAuth: (data: SetupRequest) =>
  4851. request<SetupResponse>('/auth/setup', {
  4852. method: 'POST',
  4853. body: JSON.stringify(data),
  4854. }),
  4855. login: (data: LoginRequest) =>
  4856. request<LoginResponse>('/auth/login', {
  4857. method: 'POST',
  4858. body: JSON.stringify(data),
  4859. }),
  4860. logout: () =>
  4861. request<{ message: string }>('/auth/logout', {
  4862. method: 'POST',
  4863. }),
  4864. getCurrentUser: () => request<UserResponse>('/auth/me'),
  4865. disableAuth: () =>
  4866. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  4867. method: 'POST',
  4868. }),
  4869. // Advanced Authentication
  4870. testSMTP: (data: TestSMTPRequest) =>
  4871. request<TestSMTPResponse>('/auth/smtp/test', {
  4872. method: 'POST',
  4873. body: JSON.stringify(data),
  4874. }),
  4875. getSMTPSettings: () => request<SMTPSettings | null>('/auth/smtp'),
  4876. saveSMTPSettings: (data: SMTPSettings) =>
  4877. request<{ message: string }>('/auth/smtp', {
  4878. method: 'POST',
  4879. body: JSON.stringify(data),
  4880. }),
  4881. enableAdvancedAuth: () =>
  4882. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/enable', {
  4883. method: 'POST',
  4884. }),
  4885. disableAdvancedAuth: () =>
  4886. request<{ message: string; advanced_auth_enabled: boolean }>('/auth/advanced-auth/disable', {
  4887. method: 'POST',
  4888. }),
  4889. getAdvancedAuthStatus: () => request<AdvancedAuthStatus>('/auth/advanced-auth/status'),
  4890. // LDAP Authentication
  4891. getLDAPStatus: () => request<LDAPStatus>('/auth/ldap/status'),
  4892. getEncryptionStatus: () => request<EncryptionStatus>('/auth/encryption-status'),
  4893. // form: the settings being edited, tested before they are saved. An empty
  4894. // bind password keeps the saved one.
  4895. testLDAP: (form?: LDAPTestRequest) =>
  4896. request<LDAPTestResponse>('/auth/ldap/test', {
  4897. method: 'POST',
  4898. ...(form ? { body: JSON.stringify(form) } : {}),
  4899. }),
  4900. searchLDAPDirectory: (q: string) =>
  4901. request<LDAPSearchResult[]>(`/auth/ldap/search?q=${encodeURIComponent(q)}`),
  4902. provisionLDAPUser: (username: string) =>
  4903. request<UserResponse>('/auth/ldap/provision', {
  4904. method: 'POST',
  4905. body: JSON.stringify({ username }),
  4906. }),
  4907. forgotPassword: (data: ForgotPasswordRequest) =>
  4908. request<ForgotPasswordResponse>('/auth/forgot-password', {
  4909. method: 'POST',
  4910. body: JSON.stringify(data),
  4911. }),
  4912. // H-6: Confirm password reset using the token from the emailed link
  4913. forgotPasswordConfirm: (token: string, newPassword: string) =>
  4914. request<ForgotPasswordResponse>('/auth/forgot-password/confirm', {
  4915. method: 'POST',
  4916. body: JSON.stringify({ token, new_password: newPassword }),
  4917. }),
  4918. resetUserPassword: (data: ResetPasswordRequest) =>
  4919. request<ResetPasswordResponse>('/auth/reset-password', {
  4920. method: 'POST',
  4921. body: JSON.stringify(data),
  4922. }),
  4923. // 2FA - status
  4924. get2FAStatus: () => request<TwoFAStatus>('/auth/2fa/status'),
  4925. // 2FA - TOTP
  4926. setupTOTP: () => request<TOTPSetupResponse>('/auth/2fa/totp/setup', { method: 'POST' }),
  4927. enableTOTP: (code: string) =>
  4928. request<TOTPEnableResponse>('/auth/2fa/totp/enable', {
  4929. method: 'POST',
  4930. body: JSON.stringify({ code }),
  4931. }),
  4932. disableTOTP: (code: string) =>
  4933. request<{ message: string }>('/auth/2fa/totp/disable', {
  4934. method: 'POST',
  4935. body: JSON.stringify({ code }),
  4936. }),
  4937. regenerateBackupCodes: (code: string) =>
  4938. request<BackupCodesResponse>('/auth/2fa/totp/regenerate-backup-codes', {
  4939. method: 'POST',
  4940. body: JSON.stringify({ code }),
  4941. }),
  4942. // 2FA - Email OTP
  4943. // Step 1: send a verification code to the user's email (proof of possession)
  4944. enableEmailOTP: () =>
  4945. request<{ message: string; setup_token: string }>('/auth/2fa/email/enable', { method: 'POST' }),
  4946. // Step 2: confirm with the code received by email
  4947. confirmEnableEmailOTP: (setup_token: string, code: string) =>
  4948. request<{ message: string }>('/auth/2fa/email/enable/confirm', {
  4949. method: 'POST',
  4950. body: JSON.stringify({ setup_token, code }),
  4951. }),
  4952. // Disable requires account password for re-auth
  4953. disableEmailOTP: (password: string) =>
  4954. request<{ message: string }>('/auth/2fa/email/disable', {
  4955. method: 'POST',
  4956. body: JSON.stringify({ password }),
  4957. }),
  4958. sendEmailOTP: (preAuthToken: string) =>
  4959. request<{ message: string; pre_auth_token?: string }>('/auth/2fa/email/send', {
  4960. method: 'POST',
  4961. body: JSON.stringify({ pre_auth_token: preAuthToken }),
  4962. }),
  4963. // 2FA - verify (completes login)
  4964. verify2FA: (data: TwoFAVerifyRequest) =>
  4965. request<LoginResponse>('/auth/2fa/verify', {
  4966. method: 'POST',
  4967. body: JSON.stringify(data),
  4968. }),
  4969. // 2FA - admin
  4970. // adminPassword: the calling admin's own password; null for an admin
  4971. // without one (LDAP / OIDC accounts usually), whom the route does not ask.
  4972. admin2FADisable: (userId: number, adminPassword: string | null) =>
  4973. request<{ message: string; had_2fa: boolean }>(`/auth/2fa/admin/${userId}`, {
  4974. method: 'DELETE',
  4975. body: JSON.stringify({ admin_password: adminPassword }),
  4976. }),
  4977. // OIDC providers (public list)
  4978. getOIDCProviders: () => request<OIDCProviderPublic[]>('/auth/oidc/providers'),
  4979. // OIDC providers (admin)
  4980. getOIDCProvidersAll: () => request<OIDCProvider[]>('/auth/oidc/providers/all'),
  4981. createOIDCProvider: (data: OIDCProviderCreate) =>
  4982. request<OIDCProvider>('/auth/oidc/providers', {
  4983. method: 'POST',
  4984. body: JSON.stringify(data),
  4985. }),
  4986. updateOIDCProvider: (id: number, data: Partial<OIDCProviderCreate>) =>
  4987. request<OIDCProvider>(`/auth/oidc/providers/${id}`, {
  4988. method: 'PUT',
  4989. body: JSON.stringify(data),
  4990. }),
  4991. deleteOIDCProvider: (id: number) =>
  4992. request<{ message: string }>(`/auth/oidc/providers/${id}`, { method: 'DELETE' }),
  4993. // OIDC provider icon proxy (#1333) — same-origin path so the strict
  4994. // img-src CSP stays in force. Returns a SameOriginUrl-branded string
  4995. // so a future caller can't accidentally substitute an attacker-
  4996. // controlled URL where this is consumed.
  4997. oidcProviderIconUrl: (id: number): SameOriginUrl =>
  4998. `/api/v1/auth/oidc/providers/${id}/icon` as SameOriginUrl,
  4999. deleteOIDCProviderIcon: (id: number) =>
  5000. request<void>(`/auth/oidc/providers/${id}/icon`, { method: 'DELETE' }),
  5001. refreshOIDCProviderIcon: (id: number) =>
  5002. request<OIDCProvider>(`/auth/oidc/providers/${id}/icon/refresh`, { method: 'POST' }),
  5003. // OIDC authorize URL
  5004. getOIDCAuthorizeUrl: (providerId: number) =>
  5005. request<{ auth_url: string }>(`/auth/oidc/authorize/${providerId}`),
  5006. // OIDC exchange token for JWT
  5007. exchangeOIDCToken: (oidcToken: string) =>
  5008. request<LoginResponse>('/auth/oidc/exchange', {
  5009. method: 'POST',
  5010. body: JSON.stringify({ oidc_token: oidcToken }),
  5011. }),
  5012. // OIDC links for current user
  5013. getOIDCLinks: () => request<OIDCLink[]>('/auth/oidc/links'),
  5014. deleteOIDCLink: (providerId: number) =>
  5015. request<{ message: string }>(`/auth/oidc/links/${providerId}`, { method: 'DELETE' }),
  5016. // Users
  5017. getUsers: () => request<UserResponse[]>('/users/'),
  5018. getUsersSlim: () => request<UserSlim[]>('/users/slim'),
  5019. createUser: (data: UserCreate) =>
  5020. request<UserResponse>('/users/', {
  5021. method: 'POST',
  5022. body: JSON.stringify(data),
  5023. }),
  5024. updateUser: (id: number, data: UserUpdate) =>
  5025. request<UserResponse>(`/users/${id}`, {
  5026. method: 'PATCH',
  5027. body: JSON.stringify(data),
  5028. }),
  5029. deleteUser: (id: number, deleteItems: boolean = false) =>
  5030. request<void>(`/users/${id}?delete_items=${deleteItems}`, {
  5031. method: 'DELETE',
  5032. }),
  5033. getUserItemsCount: (id: number) =>
  5034. request<{ archives: number; queue_items: number; library_files: number }>(`/users/${id}/items-count`),
  5035. changePassword: (currentPassword: string, newPassword: string) =>
  5036. request<{ message: string }>('/users/me/change-password', {
  5037. method: 'POST',
  5038. body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
  5039. }),
  5040. // User Email Notifications
  5041. getUserEmailPreferences: () =>
  5042. request<UserEmailPreferences>('/user-notifications/preferences'),
  5043. updateUserEmailPreferences: (data: UserEmailPreferences) =>
  5044. request<UserEmailPreferences>('/user-notifications/preferences', {
  5045. method: 'PUT',
  5046. body: JSON.stringify(data),
  5047. }),
  5048. // Groups
  5049. getPermissions: () => request<PermissionsListResponse>('/groups/permissions'),
  5050. getGroups: () => request<Group[]>('/groups/'),
  5051. getGroup: (id: number) => request<GroupDetail>(`/groups/${id}`),
  5052. createGroup: (data: GroupCreate) =>
  5053. request<Group>('/groups/', {
  5054. method: 'POST',
  5055. body: JSON.stringify(data),
  5056. }),
  5057. updateGroup: (id: number, data: GroupUpdate) =>
  5058. request<Group>(`/groups/${id}`, {
  5059. method: 'PATCH',
  5060. body: JSON.stringify(data),
  5061. }),
  5062. deleteGroup: (id: number) =>
  5063. request<void>(`/groups/${id}`, {
  5064. method: 'DELETE',
  5065. }),
  5066. // Printers
  5067. getPrinters: () => request<Printer[]>('/printers/'),
  5068. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  5069. createPrinter: (data: PrinterCreate) =>
  5070. request<Printer>('/printers/', {
  5071. method: 'POST',
  5072. body: JSON.stringify(data),
  5073. }),
  5074. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  5075. request<Printer>(`/printers/${id}`, {
  5076. method: 'PATCH',
  5077. body: JSON.stringify(data),
  5078. }),
  5079. getWledPresets: (id: number, baseUrl: string) =>
  5080. request<WLEDPreset[]>(`/printers/${id}/wled/presets`, {
  5081. method: 'POST',
  5082. body: JSON.stringify({ base_url: baseUrl }),
  5083. }),
  5084. testWledConnection: (id: number, baseUrl: string) =>
  5085. request<WLEDConnectionInfo>(`/printers/${id}/wled/test-connection`, {
  5086. method: 'POST',
  5087. body: JSON.stringify({ base_url: baseUrl }),
  5088. }),
  5089. testWledPreset: (id: number, baseUrl: string, presetId: number) =>
  5090. request<{ success: boolean }>(`/printers/${id}/wled/test-preset`, {
  5091. method: 'POST',
  5092. body: JSON.stringify({ base_url: baseUrl, preset_id: presetId }),
  5093. }),
  5094. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  5095. request<{ status: string; archives_deleted: boolean }>(
  5096. `/printers/${id}?delete_archives=${deleteArchives}`,
  5097. { method: 'DELETE' }
  5098. ),
  5099. getDeveloperModeWarnings: () =>
  5100. request<{ printer_id: number; name: string }[]>('/printers/developer-mode-warnings'),
  5101. getAvailableFilaments: (model: string, location?: string) => {
  5102. const params = new URLSearchParams({ model });
  5103. if (location) params.set('location', location);
  5104. return request<Array<{ type: string; color: string; tray_info_idx: string; tray_sub_brands: string; extruder_id: number | null }>>(`/printers/available-filaments?${params}`);
  5105. },
  5106. getPrinterLocations: () => request<PrinterLocation[]>('/printer-locations/'),
  5107. createPrinterLocation: (data: { name: string; icon?: string | null; color?: string | null }) =>
  5108. request<PrinterLocation>('/printer-locations/', { method: 'POST', body: JSON.stringify(data) }),
  5109. updatePrinterLocation: (data: PrinterLocationUpdate) =>
  5110. request<PrinterLocation>('/printer-locations/', { method: 'PATCH', body: JSON.stringify(data) }),
  5111. deletePrinterLocations: (names: string[]) =>
  5112. request<{ deleted: number; printers_ungrouped: number }>('/printer-locations/delete', {
  5113. method: 'POST',
  5114. body: JSON.stringify({ names }),
  5115. }),
  5116. assignPrinterLocation: (printerIds: number[], location: string | null) =>
  5117. request<{ moved: number }>('/printer-locations/assign', {
  5118. method: 'POST',
  5119. body: JSON.stringify({ printer_ids: printerIds, location }),
  5120. }),
  5121. getPrinterStatus: (id: number) => printerStatusBatch(id),
  5122. refreshPrinterStatus: (id: number) =>
  5123. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  5124. method: 'POST',
  5125. }),
  5126. connectPrinter: (id: number) =>
  5127. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  5128. method: 'POST',
  5129. }),
  5130. getUsbCameras: () => request<{ cameras: UsbCamera[] }>('/printers/usb-cameras'),
  5131. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  5132. // `coalesced` is true when the frame came from a capture that was already
  5133. // running (Obico polling, a snapshot) rather than a connection this test
  5134. // opened — a single-reader camera is shared rather than opened twice, so
  5135. // the result is real but says nothing about reaching the camera just now.
  5136. // `live_view` is true when the tested camera is the one a viewer is
  5137. // watching: the answer comes from the live frame, not a test of its own.
  5138. // In the body: the URL may carry the camera login, and a query string
  5139. // ends up in the server's access log.
  5140. request<{ success: boolean; error?: string; resolution?: string; coalesced?: boolean; live_view?: boolean }>(
  5141. `/printers/${printerId}/camera/external/test`,
  5142. { method: 'POST', body: JSON.stringify({ url, camera_type: cameraType }) }
  5143. ),
  5144. // Print Control
  5145. stopPrint: (printerId: number) =>
  5146. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  5147. method: 'POST',
  5148. }),
  5149. pausePrint: (printerId: number) =>
  5150. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  5151. method: 'POST',
  5152. }),
  5153. resumePrint: (printerId: number) =>
  5154. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  5155. method: 'POST',
  5156. }),
  5157. clearPlate: (printerId: number) =>
  5158. request<{ success: boolean; message: string }>(`/printers/${printerId}/clear-plate`, {
  5159. method: 'POST',
  5160. }),
  5161. // Get current print user (for reprint tracking - Issue #206)
  5162. getCurrentPrintUser: (printerId: number) =>
  5163. request<{ user_id?: number; username?: string }>(`/printers/${printerId}/current-print-user`),
  5164. // Print Speed Control
  5165. setPrintSpeed: (printerId: number, mode: number) =>
  5166. request<{ success: boolean; message: string }>(`/printers/${printerId}/print-speed?mode=${mode}`, {
  5167. method: 'POST',
  5168. }),
  5169. setNozzleTemperature: (printerId: number, target: number, nozzle: number = 0) =>
  5170. request<{ success: boolean; message: string }>(
  5171. `/printers/${printerId}/temperature/nozzle?target=${target}&nozzle=${nozzle}`,
  5172. { method: 'POST' }
  5173. ),
  5174. setBedTemperature: (printerId: number, target: number) =>
  5175. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/bed?target=${target}`, {
  5176. method: 'POST',
  5177. }),
  5178. setChamberTemperature: (printerId: number, target: number) =>
  5179. request<{ success: boolean; message: string }>(`/printers/${printerId}/temperature/chamber?target=${target}`, {
  5180. method: 'POST',
  5181. }),
  5182. sendPandaBreathCommand: (printerId: number, command: PandaBreathCommand) =>
  5183. request<{ success: boolean }>(`/printers/${printerId}/panda-breath`, {
  5184. method: 'POST',
  5185. body: JSON.stringify(command),
  5186. }),
  5187. setFanSpeed: (printerId: number, fan: 'part' | 'aux' | 'aux2' | 'chamber', speed: number) =>
  5188. request<{ success: boolean; message: string }>(`/printers/${printerId}/fan-speed?fan=${fan}&speed=${speed}`, {
  5189. method: 'POST',
  5190. }),
  5191. selectExtruder: (printerId: number, extruder: number) =>
  5192. request<{ success: boolean; message: string }>(`/printers/${printerId}/select-extruder?extruder=${extruder}`, {
  5193. method: 'POST',
  5194. }),
  5195. setAirductMode: (printerId: number, mode: 'cooling' | 'heating') =>
  5196. request<{ success: boolean; message: string }>(`/printers/${printerId}/airduct-mode?mode=${mode}`, {
  5197. method: 'POST',
  5198. }),
  5199. // Bed (Z-axis) jog
  5200. bedJog: (printerId: number, distance: number) =>
  5201. request<{ success: boolean; message: string }>(
  5202. `/printers/${printerId}/bed-jog?distance=${distance}`,
  5203. { method: 'POST' }
  5204. ),
  5205. xyJog: (printerId: number, x: number, y: number) =>
  5206. request<{ success: boolean; message: string }>(
  5207. `/printers/${printerId}/xy-jog?x=${x}&y=${y}`,
  5208. { method: 'POST' }
  5209. ),
  5210. extruderJog: (printerId: number, distance: number) =>
  5211. request<{ success: boolean; message: string }>(
  5212. `/printers/${printerId}/extruder-jog?distance=${distance}`,
  5213. { method: 'POST' }
  5214. ),
  5215. homeAxes: (printerId: number, axes: 'z' | 'xy' | 'all' = 'z') =>
  5216. request<{ success: boolean; message: string }>(
  5217. `/printers/${printerId}/home-axes?axes=${axes}`,
  5218. { method: 'POST' }
  5219. ),
  5220. // Chamber Light Control
  5221. setChamberLight: (printerId: number, on: boolean) =>
  5222. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  5223. method: 'POST',
  5224. }),
  5225. // AMS Drying Control
  5226. startDrying: (printerId: number, amsId: number, temp: number, duration: number, filament: string = '', rotateTray: boolean = false) =>
  5227. request<{ status: string; ams_id: number; temp: number; duration: number }>(
  5228. `/printers/${printerId}/drying/start?ams_id=${amsId}&temp=${temp}&duration=${duration}&filament=${encodeURIComponent(filament)}&rotate_tray=${rotateTray}`,
  5229. { method: 'POST' }
  5230. ),
  5231. stopDrying: (printerId: number, amsId: number) =>
  5232. request<{ status: string; ams_id: number }>(
  5233. `/printers/${printerId}/drying/stop?ams_id=${amsId}`,
  5234. { method: 'POST' }
  5235. ),
  5236. // Scheduled (delayed) drying runs (#2638)
  5237. createScheduledDrying: (data: {
  5238. printer_id: number;
  5239. ams_id: number;
  5240. temp: number;
  5241. duration_hours: number;
  5242. filament?: string;
  5243. rotate_tray?: boolean;
  5244. start_after: string | null;
  5245. }) =>
  5246. request<ScheduledDrying>('/scheduled-dryings', {
  5247. method: 'POST',
  5248. body: JSON.stringify(data),
  5249. }),
  5250. // Omit printerId for the whole fleet in one request; the printer cards share
  5251. // that single query rather than each polling for its own id.
  5252. listScheduledDryings: (printerId?: number) =>
  5253. request<ScheduledDrying[]>(
  5254. printerId === undefined ? '/scheduled-dryings' : `/scheduled-dryings?printer_id=${printerId}`
  5255. ),
  5256. cancelScheduledDrying: (id: number) =>
  5257. request<{ status: string; id: number }>(`/scheduled-dryings/${id}`, { method: 'DELETE' }),
  5258. // AMS Filament Backup (auto-switch to a backup spool when one runs out)
  5259. setAmsFilamentBackup: (printerId: number, enabled: boolean) =>
  5260. request<{ success: boolean; ams_filament_backup: boolean }>(
  5261. `/printers/${printerId}/ams-backup?enabled=${enabled}`,
  5262. { method: 'POST' }
  5263. ),
  5264. // Per-globalTrayId remaining grams for this printer's inventory-bound slots
  5265. // (#1766). Drives the client-side "Prefer Lowest Remaining Filament" sort
  5266. // when computing the AMS mapping; mirrors backend `_build_inventory_remain_overrides`
  5267. // so internal and Spoolman modes both work uniformly.
  5268. getInventoryRemain: (printerId: number) =>
  5269. request<InventoryRemainResponse>(
  5270. `/printers/${printerId}/inventory-remain`,
  5271. ),
  5272. // Skip Objects
  5273. getPrintableObjects: (printerId: number) =>
  5274. request<{
  5275. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  5276. total: number;
  5277. skipped_count: number;
  5278. is_printing: boolean;
  5279. bbox_all: [number, number, number, number] | null;
  5280. }>(`/printers/${printerId}/print/objects`),
  5281. skipObjects: (printerId: number, objectIds: number[]) =>
  5282. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  5283. `/printers/${printerId}/print/skip-objects`,
  5284. {
  5285. method: 'POST',
  5286. body: JSON.stringify(objectIds),
  5287. }
  5288. ),
  5289. // HMS Errors
  5290. clearHMSErrors: (printerId: number) =>
  5291. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/clear`, { method: 'POST' }),
  5292. executeHMSAction: (printerId: number, data: HMSActionBody) =>
  5293. request<{ success: boolean; message: string }>(`/printers/${printerId}/hms/execute-action`, {
  5294. method: 'POST',
  5295. body: JSON.stringify(data),
  5296. }),
  5297. // AMS Control
  5298. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  5299. request<{ success: boolean; message: string }>(
  5300. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  5301. { method: 'POST' }
  5302. ),
  5303. // Load filament from a tray. trayId: 0-15 for AMS (amsId*4+slotId), 28-36 for the H3C AMS 3H, 128-135 for an
  5304. // AMS-HT (its unit id), 254 for external spool.
  5305. // extruderId (0 = right, 1 = left) names the hotend to feed. Pass it only on a
  5306. // printer with a Filament Track Switch — there the AMS is bound to a switch
  5307. // inlet rather than a hotend, so the firmware cannot work the target out and
  5308. // drops the command. Omit it everywhere else, as BambuStudio does.
  5309. loadAmsTray: (printerId: number, trayId: number, extruderId?: number) =>
  5310. request<{ success: boolean; message: string }>(
  5311. `/printers/${printerId}/ams/load?tray_id=${trayId}` +
  5312. (extruderId !== undefined ? `&extruder_id=${extruderId}` : ''),
  5313. { method: 'POST' }
  5314. ),
  5315. // Unload filament. trayId names the slot to unload, which is what tells a
  5316. // dual-nozzle printer which of its two hotends to act on; omit it to unload
  5317. // whatever the printer's single tray_now field names.
  5318. unloadAms: (printerId: number, trayId?: number) =>
  5319. request<{ success: boolean; message: string }>(
  5320. `/printers/${printerId}/ams/unload` + (trayId !== undefined ? `?tray_id=${trayId}` : ''),
  5321. { method: 'POST' }
  5322. ),
  5323. // MQTT Debug Logging
  5324. enableMQTTLogging: (printerId: number) =>
  5325. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  5326. method: 'POST',
  5327. }),
  5328. disableMQTTLogging: (printerId: number) =>
  5329. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  5330. method: 'POST',
  5331. }),
  5332. getMQTTLogs: (printerId: number) =>
  5333. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  5334. clearMQTTLogs: (printerId: number) =>
  5335. request<{ status: string }>(`/printers/${printerId}/logging`, {
  5336. method: 'DELETE',
  5337. }),
  5338. // Printer File Manager
  5339. getPrinterFiles: (printerId: number, path = '/') =>
  5340. request<{
  5341. path: string;
  5342. files: Array<{
  5343. name: string;
  5344. is_directory: boolean;
  5345. size: number;
  5346. path: string;
  5347. mtime?: string;
  5348. }>;
  5349. warnings: Array<'printer_unavailable' | 'listing_timed_out'>;
  5350. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  5351. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  5352. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  5353. getPrinterFileGcodeUrl: (printerId: number, path: string) =>
  5354. `${API_BASE}/printers/${printerId}/files/gcode?path=${encodeURIComponent(path)}`,
  5355. getPrinterFilePlates: (printerId: number, path: string) =>
  5356. request<{
  5357. printer_id: number;
  5358. path: string;
  5359. filename: string;
  5360. plates: Array<{
  5361. index: number;
  5362. name: string | null;
  5363. objects: string[];
  5364. has_thumbnail: boolean;
  5365. thumbnail_url: string | null;
  5366. print_time_seconds: number | null;
  5367. filament_used_grams: number | null;
  5368. filaments: Array<{
  5369. slot_id: number;
  5370. type: string;
  5371. color: string;
  5372. used_grams: number;
  5373. used_meters: number;
  5374. }>;
  5375. }>;
  5376. is_multi_plate: boolean;
  5377. }>(`/printers/${printerId}/files/plates?path=${encodeURIComponent(path)}`),
  5378. getPrinterFilePlateThumbnail: (printerId: number, plateIndex: number, path: string) =>
  5379. withMediaToken(`${API_BASE}/printers/${printerId}/files/plate-thumbnail/${plateIndex}?path=${encodeURIComponent(path)}`),
  5380. downloadPrinterFilesAsZip: async (
  5381. printerId: number,
  5382. paths: string[],
  5383. sizes: Record<string, number>,
  5384. filename = 'printer-files.zip',
  5385. asZip = true,
  5386. signal?: AbortSignal,
  5387. onProgress?: (completed: number, total: number) => void,
  5388. ): Promise<{ requested: number; successful: number; failed: number }> => {
  5389. type JobStatus = {
  5390. job_id: string;
  5391. state: 'queued' | 'preparing' | 'ready' | 'failed' | 'cancelled';
  5392. requested: number;
  5393. successful: number;
  5394. failed: number;
  5395. token: string | null;
  5396. message: string | null;
  5397. };
  5398. let jobId: string | null = null;
  5399. try {
  5400. if (signal?.aborted) throw new DOMException('Download cancelled', 'AbortError');
  5401. let status = await request<JobStatus>(`/printers/${printerId}/files/download-job`, {
  5402. method: 'POST',
  5403. body: JSON.stringify({ paths, sizes, filename, as_zip: asZip }),
  5404. signal,
  5405. });
  5406. jobId = status.job_id;
  5407. let polls = 0;
  5408. while (status.state === 'queued' || status.state === 'preparing') {
  5409. onProgress?.(status.successful + status.failed, status.requested);
  5410. // Small selections finish in the first seconds, so poll quickly there.
  5411. // A large one runs for up to half an hour, where half-second polling is
  5412. // thousands of requests that each re-check the caller's credentials.
  5413. const delay = polls < 10 ? 500 : 2000;
  5414. polls += 1;
  5415. await new Promise<void>((resolve, reject) => {
  5416. if (signal?.aborted) {
  5417. reject(new DOMException('Download cancelled', 'AbortError'));
  5418. return;
  5419. }
  5420. const onAbort = () => {
  5421. window.clearTimeout(timer);
  5422. reject(new DOMException('Download cancelled', 'AbortError'));
  5423. };
  5424. const timer = window.setTimeout(() => {
  5425. signal?.removeEventListener('abort', onAbort);
  5426. resolve();
  5427. }, delay);
  5428. signal?.addEventListener('abort', onAbort, { once: true });
  5429. });
  5430. status = await request<JobStatus>(`/printers/${printerId}/files/download-jobs/${jobId}`, { signal });
  5431. }
  5432. onProgress?.(status.successful + status.failed, status.requested);
  5433. if (status.state !== 'ready' || !status.token) {
  5434. throw new Error(status.message || (status.state === 'cancelled'
  5435. ? 'Download cancelled'
  5436. : 'Printer download preparation failed'));
  5437. }
  5438. const link = document.createElement('a');
  5439. link.href = `${API_BASE}/printers/${printerId}/files/dl/${encodeURIComponent(status.token)}/${encodeURIComponent(filename)}`;
  5440. link.download = filename;
  5441. document.body.appendChild(link);
  5442. link.click();
  5443. link.remove();
  5444. return {
  5445. requested: status.requested,
  5446. successful: status.successful,
  5447. failed: status.failed,
  5448. };
  5449. } catch (error) {
  5450. if (jobId) {
  5451. await request(`/printers/${printerId}/files/download-jobs/${jobId}`, { method: 'DELETE' }).catch(() => undefined);
  5452. }
  5453. throw error;
  5454. }
  5455. },
  5456. deletePrinterFile: (printerId: number, path: string) =>
  5457. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  5458. method: 'DELETE',
  5459. }),
  5460. getPrinterStorage: (printerId: number) =>
  5461. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  5462. // Archives
  5463. getArchives: (printerId?: number, projectId?: number, limit = 10000, offset = 0, dateFrom?: string, dateTo?: string) => {
  5464. const params = new URLSearchParams();
  5465. if (printerId) params.set('printer_id', String(printerId));
  5466. if (projectId) params.set('project_id', String(projectId));
  5467. params.set('limit', String(limit));
  5468. params.set('offset', String(offset));
  5469. if (dateFrom) params.set('date_from', dateFrom);
  5470. if (dateTo) params.set('date_to', dateTo);
  5471. addDayZone(params);
  5472. return request<Archive[]>(`/archives/?${params}`);
  5473. },
  5474. // Latest archive of every printer in one request, for the printer cards.
  5475. getLastArchivePerPrinter: () => request<Archive[]>('/archives/last-per-printer'),
  5476. getArchivesSlim: (dateFrom?: string, dateTo?: string, createdById?: number) => {
  5477. const params = new URLSearchParams();
  5478. if (dateFrom) params.set('date_from', dateFrom);
  5479. if (dateTo) params.set('date_to', dateTo);
  5480. addDayZone(params);
  5481. if (createdById !== undefined) params.set('created_by_id', String(createdById));
  5482. const qs = params.toString();
  5483. return request<ArchiveSlim[]>(`/archives/slim${qs ? `?${qs}` : ''}`);
  5484. },
  5485. getArchive: (id: number, runId?: number | null) =>
  5486. request<Archive>(`/archives/${id}${runId != null ? `?run_id=${runId}` : ''}`),
  5487. getArchiveRuns: (id: number) => request<PrintLogResponse>(`/archives/${id}/runs`),
  5488. // The prints of the archives the caller sees that ended between two days
  5489. // (archive redesign P4: the calendar), in id order.
  5490. getArchivePrints: (params: { dateFrom: string; dateTo: string; printerId?: number; limit?: number; offset?: number }) => {
  5491. const search = new URLSearchParams({ date_from: params.dateFrom, date_to: params.dateTo });
  5492. if (params.printerId) search.set('printer_id', String(params.printerId));
  5493. if (params.limit) search.set('limit', String(params.limit));
  5494. if (params.offset) search.set('offset', String(params.offset));
  5495. addDayZone(search);
  5496. return request<PrintLogResponse>(`/archives/prints?${search}`);
  5497. },
  5498. /**
  5499. * Pre-flight for the delete-confirm modal (#1734). Returns the number of
  5500. * related queue items that will be removed along with the archive AND how
  5501. * many are currently printing (server 409s on delete if > 0).
  5502. */
  5503. getArchiveDeleteImpact: (id: number) =>
  5504. request<{ related_queue_items: number; currently_printing: number }>(
  5505. `/archives/${id}/delete-impact`
  5506. ),
  5507. getNo3MFWarning: () =>
  5508. request<{
  5509. has_fallback: boolean;
  5510. reason:
  5511. | 'ftps_cooloff'
  5512. | 'ftp_transfer_failed'
  5513. | 'internal_storage'
  5514. | 'no_external_storage'
  5515. | 'internal_history'
  5516. | null;
  5517. }>(
  5518. '/archives/no-3mf-warning',
  5519. ),
  5520. updateArchive: (id: number, data: {
  5521. printer_id?: number | null;
  5522. project_id?: number | null;
  5523. print_name?: string;
  5524. is_favorite?: boolean;
  5525. tags?: string;
  5526. notes?: string;
  5527. cost?: number;
  5528. failure_reason?: string | null;
  5529. status?: string;
  5530. quantity?: number;
  5531. external_url?: string | null;
  5532. filament_used_grams?: number | null;
  5533. // Post-print outcome verdict (#1898); null clears it
  5534. user_verdict?: 'good' | 'reject' | null;
  5535. // Which surface answered. The backend only accepts the sources a client
  5536. // can honestly claim and defaults to 'api' when none is given.
  5537. user_verdict_source?: 'dialog' | 'printer_card';
  5538. // The run the verdict / outcome is for; omitted means the latest run.
  5539. run_id?: number;
  5540. }) =>
  5541. request<Archive>(`/archives/${id}`, {
  5542. method: 'PATCH',
  5543. body: JSON.stringify(data),
  5544. }),
  5545. toggleFavorite: (id: number) =>
  5546. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  5547. // Soft-deletes by default (#1343): files removed from disk, row hidden
  5548. // from listings, but its filament / time / cost / energy contribution
  5549. // stays in Quick Stats. Pass purgeStats=true to hard-delete and drop the
  5550. // row from statistics too.
  5551. deleteArchive: (id: number, purgeStats: boolean = false) =>
  5552. request<void>(`/archives/${id}${purgeStats ? '?purge_stats=true' : ''}`, { method: 'DELETE' }),
  5553. // ========== Archive auto-purge (#1008 follow-up) ==========
  5554. previewArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5555. request<ArchivePurgePreview>(
  5556. `/archives/purge/preview?older_than_days=${olderThanDays}&purge_stats=${purgeStats}`,
  5557. ),
  5558. // #1390: purgeStats=false (default) soft-deletes each old archive — Quick Stats
  5559. // preserved, files removed from disk, row hidden via deleted_at. true matches
  5560. // the single-archive delete's `?purge_stats=true` semantics (hard-deletes the
  5561. // linked PrintLogEntry rows so the contribution drops from /stats too).
  5562. executeArchivePurge: (olderThanDays: number, purgeStats: boolean = false) =>
  5563. request<{ deleted: number; purge_stats: boolean }>('/archives/purge', {
  5564. method: 'POST',
  5565. body: JSON.stringify({ older_than_days: olderThanDays, purge_stats: purgeStats }),
  5566. }),
  5567. // Archives of one file merge into the oldest (archive redesign P2).
  5568. previewArchiveMerge: () => request<ArchiveMergePreview>('/archives/merge-preview'),
  5569. /** How many duplicate groups there are; cheap, for offering the merge. */
  5570. getArchiveMergeCount: () => request<{ groups: number }>('/archives/merge-count'),
  5571. mergeArchives: (survivorIds: number[]) =>
  5572. request<ArchiveMergeResult>('/archives/merge', {
  5573. method: 'POST',
  5574. body: JSON.stringify({ survivor_ids: survivorIds }),
  5575. }),
  5576. getArchivePurgeSettings: () =>
  5577. request<ArchivePurgeSettings>('/archives/purge/settings'),
  5578. updateArchivePurgeSettings: (body: ArchivePurgeSettings) =>
  5579. request<ArchivePurgeSettings>('/archives/purge/settings', {
  5580. method: 'PUT',
  5581. body: JSON.stringify(body),
  5582. }),
  5583. getArchiveStats: (options?: { dateFrom?: string; dateTo?: string; createdById?: number }) => {
  5584. const params = new URLSearchParams();
  5585. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5586. if (options?.dateTo) params.set('date_to', options.dateTo);
  5587. addDayZone(params);
  5588. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5589. const qs = params.toString();
  5590. return request<ArchiveStats>(`/archives/stats${qs ? `?${qs}` : ''}`);
  5591. },
  5592. // Tag management
  5593. getTags: () => request<TagInfo[]>('/archives/tags'),
  5594. renameTag: (oldName: string, newName: string) =>
  5595. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(oldName)}`, {
  5596. method: 'PUT',
  5597. body: JSON.stringify({ new_name: newName }),
  5598. }),
  5599. deleteTag: (name: string) =>
  5600. request<{ affected: number }>(`/archives/tags/${encodeURIComponent(name)}`, {
  5601. method: 'DELETE',
  5602. }),
  5603. recalculateCosts: () =>
  5604. request<{
  5605. message: string;
  5606. updated: number;
  5607. preserved: number;
  5608. usage_repriced: number;
  5609. spoolman_unreachable: number;
  5610. }>('/archives/recalculate-costs', { method: 'POST' }),
  5611. getFailureAnalysis: (options?: { days?: number; dateFrom?: string; dateTo?: string; printerId?: number; projectId?: number; createdById?: number }) => {
  5612. const params = new URLSearchParams();
  5613. if (options?.days) params.set('days', String(options.days));
  5614. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5615. if (options?.dateTo) params.set('date_to', options.dateTo);
  5616. addDayZone(params);
  5617. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5618. if (options?.projectId) params.set('project_id', String(options.projectId));
  5619. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5620. const qs = params.toString();
  5621. return request<FailureAnalysis>(`/archives/analysis/failures${qs ? `?${qs}` : ''}`);
  5622. },
  5623. compareArchives: (archiveIds: number[]) =>
  5624. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  5625. exportArchives: async (options?: {
  5626. format?: 'csv' | 'xlsx';
  5627. fields?: string[];
  5628. printerId?: number;
  5629. projectId?: number;
  5630. status?: string;
  5631. dateFrom?: string;
  5632. dateTo?: string;
  5633. search?: string;
  5634. }): Promise<{ blob: Blob; filename: string }> => {
  5635. const params = new URLSearchParams();
  5636. if (options?.format) params.set('format', options.format);
  5637. if (options?.fields) params.set('fields', options.fields.join(','));
  5638. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5639. if (options?.projectId) params.set('project_id', String(options.projectId));
  5640. if (options?.status) params.set('status', options.status);
  5641. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  5642. if (options?.dateTo) params.set('date_to', options.dateTo);
  5643. addDayZone(params);
  5644. if (options?.search) params.set('search', options.search);
  5645. const headers: Record<string, string> = {};
  5646. if (authToken) {
  5647. headers['Authorization'] = `Bearer ${authToken}`;
  5648. }
  5649. const response = await fetch(`${API_BASE}/archives/export?${params}`, { headers });
  5650. if (!response.ok) {
  5651. const error = await response.json().catch(() => ({}));
  5652. throw new Error(error.detail || `HTTP ${response.status}`);
  5653. }
  5654. const contentDisposition = response.headers.get('Content-Disposition');
  5655. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  5656. if (contentDisposition) {
  5657. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5658. if (match) filename = match[1];
  5659. }
  5660. const blob = await response.blob();
  5661. return { blob, filename };
  5662. },
  5663. exportStats: async (options?: {
  5664. format?: 'csv' | 'xlsx';
  5665. days?: number;
  5666. printerId?: number;
  5667. projectId?: number;
  5668. createdById?: number;
  5669. }): Promise<{ blob: Blob; filename: string }> => {
  5670. const params = new URLSearchParams();
  5671. if (options?.format) params.set('format', options.format);
  5672. if (options?.days) params.set('days', String(options.days));
  5673. if (options?.printerId) params.set('printer_id', String(options.printerId));
  5674. if (options?.projectId) params.set('project_id', String(options.projectId));
  5675. if (options?.createdById !== undefined) params.set('created_by_id', String(options.createdById));
  5676. const headers: Record<string, string> = {};
  5677. if (authToken) {
  5678. headers['Authorization'] = `Bearer ${authToken}`;
  5679. }
  5680. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`, { headers });
  5681. if (!response.ok) {
  5682. const error = await response.json().catch(() => ({}));
  5683. throw new Error(error.detail || `HTTP ${response.status}`);
  5684. }
  5685. const contentDisposition = response.headers.get('Content-Disposition');
  5686. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  5687. if (contentDisposition) {
  5688. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  5689. if (match) filename = match[1];
  5690. }
  5691. const blob = await response.blob();
  5692. return { blob, filename };
  5693. },
  5694. getArchiveThumbnail: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`),
  5695. getArchivePlateThumbnail: (id: number, plateIndex: number) =>
  5696. withMediaToken(`${API_BASE}/archives/${id}/plate-thumbnail/${plateIndex}`),
  5697. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  5698. downloadArchive: async (id: number, filename?: string): Promise<void> => {
  5699. const headers: Record<string, string> = {};
  5700. if (authToken) {
  5701. headers['Authorization'] = `Bearer ${authToken}`;
  5702. }
  5703. const response = await fetch(`${API_BASE}/archives/${id}/download`, { headers });
  5704. if (!response.ok) {
  5705. const error = await response.json().catch(() => ({}));
  5706. throw new Error(error.detail || `HTTP ${response.status}`);
  5707. }
  5708. const disposition = response.headers.get('Content-Disposition');
  5709. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `archive_${id}.3mf`;
  5710. const blob = await response.blob();
  5711. const url = window.URL.createObjectURL(blob);
  5712. const a = document.createElement('a');
  5713. a.href = url;
  5714. a.download = downloadFilename;
  5715. document.body.appendChild(a);
  5716. a.click();
  5717. document.body.removeChild(a);
  5718. window.URL.revokeObjectURL(url);
  5719. },
  5720. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  5721. getArchiveTimelapse: (id: number) => withMediaToken(`${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`),
  5722. getArchiveRunTimelapse: (id: number, runId: number) =>
  5723. withMediaToken(`${API_BASE}/archives/${id}/runs/${runId}/timelapse?v=${Date.now()}`),
  5724. downloadArchiveTimelapse: async (id: number, filename: string): Promise<void> => {
  5725. const prepared = await request<{ token: string; filename: string }>(
  5726. `/archives/${id}/media-download-token`,
  5727. { method: 'POST' },
  5728. );
  5729. const link = document.createElement('a');
  5730. link.href = `${API_BASE}/archives/${id}/media/dl/${encodeURIComponent(prepared.token)}/${encodeURIComponent(filename)}`;
  5731. link.download = filename;
  5732. document.body.appendChild(link);
  5733. link.click();
  5734. link.remove();
  5735. },
  5736. getArchivePrinterMedia: (id: number) =>
  5737. request<ArchivePrinterMedia>(`/archives/${id}/printer-media`),
  5738. scanArchiveTimelapse: (id: number) =>
  5739. request<{
  5740. status: string;
  5741. message: string;
  5742. filename?: string;
  5743. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  5744. }>(`/archives/${id}/timelapse/scan`, {
  5745. method: 'POST',
  5746. }),
  5747. selectArchiveTimelapse: (id: number, filename: string) =>
  5748. request<{ status: string; message: string; filename: string }>(
  5749. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  5750. { method: 'POST' }
  5751. ),
  5752. deleteArchiveTimelapse: (id: number) =>
  5753. request<{ status: string }>(`/archives/${id}/timelapse`, {
  5754. method: 'DELETE',
  5755. }),
  5756. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5757. const formData = new FormData();
  5758. formData.append('file', file);
  5759. const headers: Record<string, string> = {};
  5760. if (authToken) {
  5761. headers['Authorization'] = `Bearer ${authToken}`;
  5762. }
  5763. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  5764. method: 'POST',
  5765. headers,
  5766. body: formData,
  5767. });
  5768. if (!response.ok) {
  5769. const error = await response.json().catch(() => ({}));
  5770. throw new Error(error.detail || `HTTP ${response.status}`);
  5771. }
  5772. return response.json();
  5773. },
  5774. // Timelapse Editor
  5775. getTimelapseInfo: (archiveId: number) =>
  5776. request<{
  5777. duration: number;
  5778. width: number;
  5779. height: number;
  5780. fps: number;
  5781. codec: string;
  5782. file_size: number;
  5783. has_audio: boolean;
  5784. }>(`/archives/${archiveId}/timelapse/info`),
  5785. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  5786. request<{
  5787. thumbnails: string[];
  5788. timestamps: number[];
  5789. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  5790. processTimelapse: async (
  5791. archiveId: number,
  5792. params: {
  5793. trimStart?: number;
  5794. trimEnd?: number;
  5795. speed?: number;
  5796. /** Music volume, 0 to 1. */
  5797. audioVolume?: number;
  5798. saveMode: 'replace' | 'new';
  5799. outputFilename?: string;
  5800. },
  5801. audioFile?: File
  5802. ): Promise<TimelapseJob> => {
  5803. const formData = new FormData();
  5804. formData.append('trim_start', String(params.trimStart ?? 0));
  5805. if (params.trimEnd !== undefined) {
  5806. formData.append('trim_end', String(params.trimEnd));
  5807. }
  5808. formData.append('speed', String(params.speed ?? 1));
  5809. if (params.audioVolume !== undefined) {
  5810. formData.append('audio_volume', String(params.audioVolume));
  5811. }
  5812. formData.append('save_mode', params.saveMode);
  5813. if (params.outputFilename) {
  5814. formData.append('output_filename', params.outputFilename);
  5815. }
  5816. if (audioFile) {
  5817. formData.append('audio', audioFile);
  5818. }
  5819. const headers: Record<string, string> = {};
  5820. if (authToken) {
  5821. headers['Authorization'] = `Bearer ${authToken}`;
  5822. }
  5823. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  5824. method: 'POST',
  5825. headers,
  5826. body: formData,
  5827. });
  5828. if (!response.ok) {
  5829. const error = await response.json().catch(() => ({}));
  5830. throw new Error(error.detail || `HTTP ${response.status}`);
  5831. }
  5832. return response.json();
  5833. },
  5834. // The archive's running or last re-encode; null when there has been none.
  5835. getTimelapseJob: async (archiveId: number): Promise<TimelapseJob | null> => {
  5836. try {
  5837. return await request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`);
  5838. } catch (error) {
  5839. if (error instanceof ApiError && error.status === 404) return null;
  5840. throw error;
  5841. }
  5842. },
  5843. cancelTimelapseJob: (archiveId: number) =>
  5844. request<TimelapseJob>(`/archives/${archiveId}/timelapse/job`, { method: 'DELETE' }),
  5845. // Photos
  5846. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  5847. withMediaToken(`${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`),
  5848. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  5849. const formData = new FormData();
  5850. formData.append('file', file);
  5851. const headers: Record<string, string> = {};
  5852. if (authToken) {
  5853. headers['Authorization'] = `Bearer ${authToken}`;
  5854. }
  5855. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  5856. headers,
  5857. method: 'POST',
  5858. body: formData,
  5859. });
  5860. if (!response.ok) {
  5861. const error = await response.json().catch(() => ({}));
  5862. throw new Error(error.detail || `HTTP ${response.status}`);
  5863. }
  5864. return response.json();
  5865. },
  5866. deleteArchivePhoto: (archiveId: number, filename: string) =>
  5867. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  5868. method: 'DELETE',
  5869. }),
  5870. // Source 3MF (original slicer project file)
  5871. getSource3mfDownloadUrl: (archiveId: number) =>
  5872. `${API_BASE}/archives/${archiveId}/source`,
  5873. downloadSource3mf: async (archiveId: number): Promise<void> => {
  5874. const headers: Record<string, string> = {};
  5875. if (authToken) {
  5876. headers['Authorization'] = `Bearer ${authToken}`;
  5877. }
  5878. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, { headers });
  5879. if (!response.ok) {
  5880. const error = await response.json().catch(() => ({}));
  5881. throw new Error(error.detail || `HTTP ${response.status}`);
  5882. }
  5883. const disposition = response.headers.get('Content-Disposition');
  5884. const filename = parseContentDispositionFilename(disposition) || `source_${archiveId}.3mf`;
  5885. const blob = await response.blob();
  5886. const url = window.URL.createObjectURL(blob);
  5887. const a = document.createElement('a');
  5888. a.href = url;
  5889. a.download = filename;
  5890. document.body.appendChild(a);
  5891. a.click();
  5892. document.body.removeChild(a);
  5893. window.URL.revokeObjectURL(url);
  5894. },
  5895. getSource3mfForSlicer: (archiveId: number, filename: string) => {
  5896. // Sanitize: slicers url_decode() the entire URL, so / \ ? # in filenames break path routing
  5897. const safe = filename.replace(/[/\\?#]/g, '_');
  5898. return `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5899. },
  5900. createSourceSlicerToken: (archiveId: number) =>
  5901. request<{ token: string }>(`/archives/${archiveId}/source-slicer-token`, { method: 'POST' }),
  5902. getSourceSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  5903. const safe = filename.replace(/[/\\?#]/g, '_');
  5904. return `${API_BASE}/archives/${archiveId}/source-dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  5905. },
  5906. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5907. const formData = new FormData();
  5908. formData.append('file', file);
  5909. const headers: Record<string, string> = {};
  5910. if (authToken) {
  5911. headers['Authorization'] = `Bearer ${authToken}`;
  5912. }
  5913. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  5914. method: 'POST',
  5915. headers,
  5916. body: formData,
  5917. });
  5918. if (!response.ok) {
  5919. const error = await response.json().catch(() => ({}));
  5920. throw new Error(error.detail || `HTTP ${response.status}`);
  5921. }
  5922. return response.json();
  5923. },
  5924. deleteSource3mf: (archiveId: number) =>
  5925. request<{ status: string }>(`/archives/${archiveId}/source`, {
  5926. method: 'DELETE',
  5927. }),
  5928. // F3D (Fusion 360 design file)
  5929. downloadF3d: async (archiveId: number): Promise<void> => {
  5930. const headers: Record<string, string> = {};
  5931. if (authToken) {
  5932. headers['Authorization'] = `Bearer ${authToken}`;
  5933. }
  5934. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, { headers });
  5935. if (!response.ok) {
  5936. const error = await response.json().catch(() => ({}));
  5937. throw new Error(error.detail || `HTTP ${response.status}`);
  5938. }
  5939. const disposition = response.headers.get('Content-Disposition');
  5940. const filename = parseContentDispositionFilename(disposition) || `archive_${archiveId}.f3d`;
  5941. const blob = await response.blob();
  5942. const url = window.URL.createObjectURL(blob);
  5943. const a = document.createElement('a');
  5944. a.href = url;
  5945. a.download = filename;
  5946. document.body.appendChild(a);
  5947. a.click();
  5948. document.body.removeChild(a);
  5949. window.URL.revokeObjectURL(url);
  5950. },
  5951. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  5952. const formData = new FormData();
  5953. formData.append('file', file);
  5954. const headers: Record<string, string> = {};
  5955. if (authToken) {
  5956. headers['Authorization'] = `Bearer ${authToken}`;
  5957. }
  5958. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  5959. method: 'POST',
  5960. headers,
  5961. body: formData,
  5962. });
  5963. if (!response.ok) {
  5964. const error = await response.json().catch(() => ({}));
  5965. throw new Error(error.detail || `HTTP ${response.status}`);
  5966. }
  5967. return response.json();
  5968. },
  5969. deleteF3d: (archiveId: number) =>
  5970. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  5971. method: 'DELETE',
  5972. }),
  5973. // QR Code
  5974. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  5975. withMediaToken(`${API_BASE}/archives/${archiveId}/qrcode?size=${size}`),
  5976. getArchiveCapabilities: (id: number) =>
  5977. request<{
  5978. has_model: boolean;
  5979. has_gcode: boolean;
  5980. has_source: boolean;
  5981. build_volume: { x: number; y: number; z: number };
  5982. filament_colors: string[];
  5983. }>(`/archives/${id}/capabilities`),
  5984. // Project Page
  5985. getArchiveProjectPage: (id: number) =>
  5986. request<{
  5987. title: string | null;
  5988. description: string | null;
  5989. designer: string | null;
  5990. designer_user_id: string | null;
  5991. license: string | null;
  5992. copyright: string | null;
  5993. creation_date: string | null;
  5994. modification_date: string | null;
  5995. origin: string | null;
  5996. profile_title: string | null;
  5997. profile_description: string | null;
  5998. profile_cover: string | null;
  5999. profile_user_id: string | null;
  6000. profile_user_name: string | null;
  6001. design_model_id: string | null;
  6002. design_profile_id: string | null;
  6003. design_region: string | null;
  6004. model_pictures: Array<{ name: string; path: string; url: string }>;
  6005. profile_pictures: Array<{ name: string; path: string; url: string }>;
  6006. thumbnails: Array<{ name: string; path: string; url: string }>;
  6007. }>(`/archives/${id}/project-page`),
  6008. updateArchiveProjectPage: (id: number, data: {
  6009. title?: string;
  6010. description?: string;
  6011. designer?: string;
  6012. license?: string;
  6013. copyright?: string;
  6014. profile_title?: string;
  6015. profile_description?: string;
  6016. }) =>
  6017. request(`/archives/${id}/project-page`, {
  6018. method: 'PATCH',
  6019. body: JSON.stringify(data),
  6020. }),
  6021. getArchiveForSlicer: (id: number, filename: string) => {
  6022. const safe = filename.replace(/[/\\?#]/g, '_');
  6023. return `${API_BASE}/archives/${id}/file/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  6024. },
  6025. createArchiveSlicerToken: (archiveId: number) =>
  6026. request<{ token: string }>(`/archives/${archiveId}/slicer-token`, { method: 'POST' }),
  6027. getArchiveSlicerDownloadUrl: (archiveId: number, token: string, filename: string) => {
  6028. const safe = filename.replace(/[/\\?#]/g, '_');
  6029. return `${API_BASE}/archives/${archiveId}/dl/${token}/${encodeURIComponent(safe.endsWith('.3mf') ? safe : safe + '.3mf')}`;
  6030. },
  6031. getArchivePlates: (archiveId: number) =>
  6032. request<ArchivePlatesResponse>(`/archives/${archiveId}/plates`),
  6033. getArchiveFilamentRequirements: (
  6034. archiveId: number,
  6035. plateId?: number,
  6036. requestId?: string,
  6037. /** Ask for one entry per project slot instead of only the slots this
  6038. * plate consumes. The slice modal needs it: its filament list is
  6039. * positional, so a source whose only used slot is 4 must still present
  6040. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  6041. * AMS matching must NOT set this — it wants the used-only list. */
  6042. fullSlots?: boolean,
  6043. ) => {
  6044. const qs = new URLSearchParams();
  6045. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  6046. if (requestId) qs.set('request_id', requestId);
  6047. if (fullSlots) qs.set('full_slots', 'true');
  6048. return request<{
  6049. archive_id: number;
  6050. filename: string;
  6051. plate_id: number | null;
  6052. filaments: Array<{
  6053. slot_id: number;
  6054. type: string;
  6055. color: string;
  6056. used_grams: number;
  6057. used_meters: number;
  6058. used_in_plate?: boolean;
  6059. }>;
  6060. }>(`/archives/${archiveId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  6061. },
  6062. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  6063. const formData = new FormData();
  6064. files.forEach((file) => formData.append('files', file));
  6065. const url = printerId
  6066. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  6067. : `${API_BASE}/archives/upload-bulk`;
  6068. const headers: Record<string, string> = {};
  6069. if (authToken) {
  6070. headers['Authorization'] = `Bearer ${authToken}`;
  6071. }
  6072. const response = await fetch(url, {
  6073. method: 'POST',
  6074. headers,
  6075. body: formData,
  6076. });
  6077. if (!response.ok) {
  6078. const error = await response.json().catch(() => ({}));
  6079. throw new Error(error.detail || `HTTP ${response.status}`);
  6080. }
  6081. return response.json();
  6082. },
  6083. // Print Log
  6084. getPrintLog: (params?: {
  6085. search?: string;
  6086. printerId?: number;
  6087. username?: string;
  6088. status?: string;
  6089. dateFrom?: string;
  6090. dateTo?: string;
  6091. limit?: number;
  6092. offset?: number;
  6093. // Sorting is server-side because paging is: ordering only the rows the
  6094. // client holds would sort one page, not the log (#2636).
  6095. sortBy?: string;
  6096. sortDir?: 'asc' | 'desc';
  6097. }) => {
  6098. const searchParams = new URLSearchParams();
  6099. if (params?.search) searchParams.set('search', params.search);
  6100. if (params?.printerId) searchParams.set('printer_id', String(params.printerId));
  6101. if (params?.username) searchParams.set('created_by_username', params.username);
  6102. if (params?.status) searchParams.set('status', params.status);
  6103. if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
  6104. if (params?.dateTo) searchParams.set('date_to', params.dateTo);
  6105. if (params?.limit) searchParams.set('limit', String(params.limit));
  6106. if (params?.offset !== undefined) searchParams.set('offset', String(params.offset));
  6107. if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
  6108. if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
  6109. return request<PrintLogResponse>(`/print-log/?${searchParams}`);
  6110. },
  6111. getPrintLogThumbnail: (id: number) => withMediaToken(`${API_BASE}/print-log/${id}/thumbnail`),
  6112. clearPrintLog: () =>
  6113. request<{ deleted: number }>('/print-log/', { method: 'DELETE' }),
  6114. deletePrintLogEntry: (id: number) =>
  6115. request<{ status: string; id: number }>(`/print-log/${id}`, { method: 'DELETE' }),
  6116. // Edit failure_reason / status on a single Print Log row (#1687 part 4).
  6117. // Distinct from updateArchive: archives describe the model, log entries
  6118. // describe a single print event. Orphan entries (no archive_id) have no
  6119. // archive to reach through and this is the only path to classify them.
  6120. updatePrintLogEntry: (
  6121. id: number,
  6122. body: { failure_reason?: string | null; status?: string; notes?: string | null },
  6123. ) =>
  6124. request<PrintLogEntry>(`/print-log/${id}`, {
  6125. method: 'PATCH',
  6126. body: JSON.stringify(body),
  6127. }),
  6128. // Settings
  6129. getSettings: () => request<AppSettings>('/settings/'),
  6130. getDefaultSidebarOrder: () => request<{ default_sidebar_order: string }>('/settings/default-sidebar-order'),
  6131. // Public subset of settings for UI rendering — no settings:read required.
  6132. // Used by pages whose users may not have SETTINGS_READ (e.g. operators with
  6133. // only printers:clear_plate). Keep in sync with _UI_PREFERENCE_FIELDS in
  6134. // backend/app/api/routes/settings.py.
  6135. getUiPreferences: () =>
  6136. request<{
  6137. require_plate_clear?: boolean;
  6138. check_printer_firmware?: boolean;
  6139. camera_view_mode?: 'window' | 'embedded';
  6140. time_format?: 'system' | '12h' | '24h';
  6141. date_format?: string;
  6142. drying_presets?: string;
  6143. ams_humidity_thresholds?: string;
  6144. ams_humidity_good?: number;
  6145. ams_humidity_fair?: number;
  6146. ams_temp_good?: number;
  6147. ams_temp_fair?: number;
  6148. bed_cooled_threshold?: number;
  6149. nozzle_temp_presets?: string;
  6150. bed_temp_presets?: string;
  6151. chamber_temp_presets?: string;
  6152. fan_speed_presets?: string;
  6153. }>('/settings/ui-preferences'),
  6154. // Install configuration the app shell needs, for any signed-in user. Separate
  6155. // from getUiPreferences: that endpoint is public because its fields are
  6156. // defaults shipped with the app, while these describe how this deployment is
  6157. // configured. Neither requires settings:read -- which is the point, since a
  6158. // non-admin reading GET /settings gets a 403 and every gate that consults it
  6159. // silently takes its fallback (#3023). Keep in sync with _UI_FLAG_FIELDS in
  6160. // backend/app/api/routes/settings.py.
  6161. getUiFlags: () => request<UiSettings>('/settings/ui-flags'),
  6162. // The two above together: what a page needs from the settings when its user
  6163. // may not read GET /settings. See useUiSettings.
  6164. getUiSettings: async (): Promise<UiSettings> => {
  6165. const [preferences, flags] = await Promise.all([api.getUiPreferences(), api.getUiFlags()]);
  6166. return { ...(preferences as UiSettings), ...flags };
  6167. },
  6168. updateSettings: (data: AppSettingsUpdate) =>
  6169. request<AppSettings>('/settings/', {
  6170. method: 'PUT',
  6171. body: JSON.stringify(data),
  6172. }),
  6173. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  6174. getPandaBreathStatus: () => request<PandaBreathStatus>('/settings/panda-breath/status'),
  6175. exportBackup: async (): Promise<{ blob: Blob; filename: string }> => {
  6176. // New simplified backup - complete database + all files
  6177. const url = `${API_BASE}/settings/backup`;
  6178. const headers: Record<string, string> = {};
  6179. if (authToken) {
  6180. headers['Authorization'] = `Bearer ${authToken}`;
  6181. }
  6182. const response = await fetch(url, { headers });
  6183. // Check for errors
  6184. if (!response.ok) {
  6185. const errorText = await response.text();
  6186. throw new Error(errorText || `Backup failed with status ${response.status}`);
  6187. }
  6188. // Get filename from Content-Disposition header
  6189. const contentDisposition = response.headers.get('Content-Disposition');
  6190. let filename = 'bambuddy-backup.zip';
  6191. if (contentDisposition) {
  6192. const match = contentDisposition.match(/filename=([^;]+)/);
  6193. if (match) filename = match[1].trim().replace(/^"(.*)"$/, '$1');
  6194. }
  6195. const blob = await response.blob();
  6196. return { blob, filename };
  6197. },
  6198. importBackup: async (file: File) => {
  6199. // New simplified restore - replaces database + all directories
  6200. const formData = new FormData();
  6201. formData.append('file', file);
  6202. const url = `${API_BASE}/settings/restore`;
  6203. const headers: Record<string, string> = {};
  6204. if (authToken) {
  6205. headers['Authorization'] = `Bearer ${authToken}`;
  6206. }
  6207. const response = await fetch(url, {
  6208. method: 'POST',
  6209. headers,
  6210. body: formData,
  6211. });
  6212. const data = (await response.json().catch(() => null)) as {
  6213. success?: boolean;
  6214. message?: string;
  6215. detail?: string;
  6216. } | null;
  6217. // A refused restore is an HTTPException, so the body is {detail}, not
  6218. // {success, message}. Returning it unmapped made `success` undefined and
  6219. // `message` undefined too — the modal then raised an empty error toast,
  6220. // which is the one case where the reason matters most (e.g. a backup this
  6221. // version cannot import names the columns and both versions).
  6222. if (!response.ok) {
  6223. return { success: false, message: data?.detail ?? data?.message ?? '' };
  6224. }
  6225. return (data ?? { success: false, message: '' }) as {
  6226. success: boolean;
  6227. message: string;
  6228. };
  6229. },
  6230. checkFfmpeg: () =>
  6231. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  6232. getNetworkInterfaces: () =>
  6233. request<{ interfaces: NetworkInterface[] }>('/settings/network-interfaces'),
  6234. // Cloud
  6235. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  6236. cloudLogin: (email: string, password: string, region = 'global') =>
  6237. request<CloudLoginResponse>('/cloud/login', {
  6238. method: 'POST',
  6239. body: JSON.stringify({ email, password, region }),
  6240. }),
  6241. cloudVerify: (email: string, code: string, tfaKey?: string, region: string = 'global') =>
  6242. request<CloudLoginResponse>('/cloud/verify', {
  6243. method: 'POST',
  6244. body: JSON.stringify({ email, code, tfa_key: tfaKey, region }),
  6245. }),
  6246. cloudSetToken: (access_token: string, region: string = 'global') =>
  6247. request<CloudAuthStatus>('/cloud/token', {
  6248. method: 'POST',
  6249. body: JSON.stringify({ access_token, region }),
  6250. }),
  6251. cloudLogout: () =>
  6252. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  6253. // Orca Cloud — RFC 8628 device pairing. deviceStart() returns a short
  6254. // user_code + verification link; the user approves it in their Orca Cloud
  6255. // settings while the frontend polls devicePoll() every `interval` seconds
  6256. // until the status flips to 'complete' (or a terminal deny/expire).
  6257. orcaCloudDeviceStart: () =>
  6258. request<OrcaDeviceStartResponse>('/orca-cloud/device/start', {
  6259. method: 'POST',
  6260. }),
  6261. orcaCloudDevicePoll: () =>
  6262. request<OrcaDevicePollResponse>('/orca-cloud/device/poll', {
  6263. method: 'POST',
  6264. }),
  6265. orcaCloudStatus: () =>
  6266. request<OrcaAuthStatusResponse>('/orca-cloud/status'),
  6267. orcaCloudLogout: () =>
  6268. request<{ success: boolean }>('/orca-cloud/logout', { method: 'POST' }),
  6269. orcaCloudListProfiles: () =>
  6270. request<OrcaProfileListResponse>('/orca-cloud/profiles'),
  6271. orcaCloudGetProfile: (id: string) =>
  6272. request<OrcaProfileDetail>(`/orca-cloud/profiles/${id}`),
  6273. getCloudSettings: (version = '02.04.00.70') =>
  6274. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  6275. getBuiltinFilaments: () =>
  6276. request<BuiltinFilament[]>('/cloud/builtin-filaments'),
  6277. getFilamentIdMap: () =>
  6278. request<Record<string, string>>('/cloud/filament-id-map'),
  6279. /** Material-disambiguated hex→name lookup. Same hex can map to different
  6280. * catalog names depending on material (e.g. #000000 is "Charcoal" in PLA
  6281. * Matte but "Black" in PLA Basic). The flat ``/inventory/colors/map``
  6282. * collapses these to the first hit; this endpoint preserves the material
  6283. * context. Returns ``{color_name: null}`` when the hex isn't in the
  6284. * catalog at all. #1718. */
  6285. getColorByMaterial: (hex: string, material?: string) => {
  6286. const params = new URLSearchParams({ hex });
  6287. if (material) params.set('material', material);
  6288. return request<{ color_name: string | null }>(
  6289. `/inventory/colors/by-material?${params.toString()}`,
  6290. );
  6291. },
  6292. // MakerWorld URL-paste import flow.
  6293. getMakerworldStatus: () =>
  6294. request<MakerworldStatus>('/makerworld/status'),
  6295. resolveMakerworldUrl: (url: string) =>
  6296. request<MakerworldResolvedModel>('/makerworld/resolve', {
  6297. method: 'POST',
  6298. body: JSON.stringify({ url }),
  6299. }),
  6300. getMakerworldRecentImports: (limit = 10) =>
  6301. request<MakerworldRecentImport[]>(`/makerworld/recent-imports?limit=${limit}`),
  6302. importMakerworldInstance: (
  6303. model_id: number,
  6304. instance_id: number | null,
  6305. profile_id?: number | null,
  6306. folder_id?: number | null,
  6307. ) =>
  6308. request<MakerworldImportResponse>('/makerworld/import', {
  6309. method: 'POST',
  6310. body: JSON.stringify({
  6311. model_id,
  6312. instance_id: instance_id ?? null,
  6313. profile_id: profile_id ?? null,
  6314. folder_id: folder_id ?? null,
  6315. }),
  6316. }),
  6317. // Manyfold (#1471).
  6318. getManyfoldConfig: () => request<ManyfoldConfig>('/manyfold/config'),
  6319. updateManyfoldConfig: (data: ManyfoldConfigInput) =>
  6320. request<ManyfoldConfig>('/manyfold/config', { method: 'PUT', body: JSON.stringify(data) }),
  6321. deleteManyfoldConfig: () => request<void>('/manyfold/config', { method: 'DELETE' }),
  6322. testManyfoldConfig: (data: ManyfoldConfigInput) =>
  6323. request<{ model_count: number }>('/manyfold/config/test', { method: 'POST', body: JSON.stringify(data) }),
  6324. getManyfoldStatus: () => request<ManyfoldStatus>('/manyfold/status'),
  6325. listManyfoldModels: (query: string, page: number) => {
  6326. const params = new URLSearchParams({ page: String(page) });
  6327. if (query) params.set('q', query);
  6328. return request<ManyfoldModelList>(`/manyfold/models?${params.toString()}`);
  6329. },
  6330. getManyfoldModel: (modelId: string) =>
  6331. request<ManyfoldModel>(`/manyfold/models/${encodeURIComponent(modelId)}`),
  6332. /** The model's preview, or null when it has none. Fetched rather than used
  6333. * as an <img src>: a failing protected <img> makes the app renew its media
  6334. * token, and models without a preview answer 404. */
  6335. getManyfoldPreview: async (modelId: string): Promise<Blob | null> => {
  6336. const headers: Record<string, string> = {};
  6337. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6338. const response = await fetch(`${API_BASE}/manyfold/models/${encodeURIComponent(modelId)}/preview`, { headers });
  6339. if (!response.ok) return null;
  6340. return response.blob();
  6341. },
  6342. importManyfoldFile: (modelId: string, fileId: string, folderId: number | null) =>
  6343. request<ManyfoldImportResponse>('/manyfold/import', {
  6344. method: 'POST',
  6345. body: JSON.stringify({ model_id: modelId, file_id: fileId, folder_id: folderId }),
  6346. }),
  6347. getCloudSettingDetail: (settingId: string) =>
  6348. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  6349. createCloudSetting: (data: SlicerSettingCreate) =>
  6350. request<SlicerSettingDetail>('/cloud/settings', {
  6351. method: 'POST',
  6352. body: JSON.stringify(data),
  6353. }),
  6354. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  6355. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  6356. method: 'PUT',
  6357. body: JSON.stringify(data),
  6358. }),
  6359. deleteCloudSetting: (settingId: string) =>
  6360. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  6361. method: 'DELETE',
  6362. }),
  6363. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  6364. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  6365. getFilamentInfo: (settingIds: string[]) =>
  6366. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  6367. method: 'POST',
  6368. body: JSON.stringify(settingIds),
  6369. }),
  6370. // Smart Plugs
  6371. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  6372. getSmartPlugByPrinter: (printerId: number) => smartPlugBatch(printerId),
  6373. getScriptPlugsByPrinter: (printerId: number) => scriptPlugsBatch(printerId),
  6374. createSmartPlug: (data: SmartPlugCreate) =>
  6375. request<SmartPlug>('/smart-plugs/', {
  6376. method: 'POST',
  6377. body: JSON.stringify(data),
  6378. }),
  6379. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  6380. request<SmartPlug>(`/smart-plugs/${id}`, {
  6381. method: 'PATCH',
  6382. body: JSON.stringify(data),
  6383. }),
  6384. deleteSmartPlug: (id: number) =>
  6385. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  6386. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  6387. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  6388. method: 'POST',
  6389. body: JSON.stringify({ action }),
  6390. }),
  6391. getSmartPlugStatus: (id: number) =>
  6392. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  6393. // plug_id: the saved plug being edited, whose stored password fills in the placeholder.
  6394. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null, plug_id?: number) =>
  6395. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  6396. method: 'POST',
  6397. body: JSON.stringify({ ip_address, username, password, plug_id }),
  6398. }),
  6399. // Tasmota Discovery (auto-detects network)
  6400. startTasmotaScan: () =>
  6401. request<TasmotaScanStatus>('/smart-plugs/discover/scan', { method: 'POST' }),
  6402. getTasmotaScanStatus: () =>
  6403. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  6404. stopTasmotaScan: () =>
  6405. request<TasmotaScanStatus>('/smart-plugs/discover/stop', { method: 'POST' }),
  6406. getDiscoveredTasmotaDevices: () =>
  6407. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  6408. // Home Assistant Integration
  6409. testHAConnection: (url: string, token: string) =>
  6410. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  6411. method: 'POST',
  6412. body: JSON.stringify({ url, token }),
  6413. }),
  6414. getHAEntities: (search?: string) => {
  6415. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6416. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  6417. },
  6418. getHASensorEntities: () =>
  6419. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  6420. // Home Assistant sensors bound to a printer (#1148, #448)
  6421. getHASensors: (printerId?: number) =>
  6422. request<PrinterHASensor[]>(`/ha-sensors/${printerId ? `?printer_id=${printerId}` : ''}`),
  6423. getHASensorReadings: (printerId: number) => haSensorReadingsBatch(printerId),
  6424. getBindableHAEntities: (search?: string) => {
  6425. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6426. return request<HADisplayEntity[]>(`/ha-sensors/entities${params}`);
  6427. },
  6428. createHASensor: (data: PrinterHASensorCreate) =>
  6429. request<PrinterHASensor>('/ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6430. updateHASensor: (id: number, data: PrinterHASensorUpdate) =>
  6431. request<PrinterHASensor>(`/ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6432. deleteHASensor: (id: number) =>
  6433. request<{ message: string }>(`/ha-sensors/${id}`, { method: 'DELETE' }),
  6434. getLocationHASensors: (locationId?: number) =>
  6435. request<LocationHASensor[]>(`/location-ha-sensors/${locationId ? `?location_id=${locationId}` : ''}`),
  6436. getLocationHASensorReadings: (locationId: number, showOnCard = true) =>
  6437. request<LocationHASensorReading[]>(
  6438. `/location-ha-sensors/by-location/${locationId}/readings?show_on_card=${showOnCard}`
  6439. ),
  6440. getBindableLocationHAEntities: (search?: string) => {
  6441. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  6442. return request<HADisplayEntity[]>(`/location-ha-sensors/entities${params}`);
  6443. },
  6444. createLocationHASensor: (data: LocationHASensorCreate) =>
  6445. request<LocationHASensor>('/location-ha-sensors/', { method: 'POST', body: JSON.stringify(data) }),
  6446. updateLocationHASensor: (id: number, data: LocationHASensorUpdate) =>
  6447. request<LocationHASensor>(`/location-ha-sensors/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  6448. deleteLocationHASensor: (id: number) =>
  6449. request<{ message: string }>(`/location-ha-sensors/${id}`, { method: 'DELETE' }),
  6450. // REST smart plug
  6451. // plug_id: the saved plug being edited, whose stored headers fill in the placeholder.
  6452. testRESTConnection: (url: string, method: string = 'GET', headers?: string | null, plug_id?: number) =>
  6453. request<{ success: boolean; error: string | null }>('/smart-plugs/rest/test-connection', {
  6454. method: 'POST',
  6455. body: JSON.stringify({ url, method, headers, plug_id }),
  6456. }),
  6457. // Print Queue
  6458. getQueue: (printerId?: number, status?: string, targetModel?: string) => {
  6459. const params = new URLSearchParams();
  6460. if (printerId) params.set('printer_id', String(printerId));
  6461. if (status) params.set('status', status);
  6462. if (targetModel) params.set('target_model', targetModel);
  6463. return request<PrintQueueItem[]>(`/queue/?${params}`);
  6464. },
  6465. // History (completed / failed / skipped / cancelled), one page at a time.
  6466. getQueueHistory: (params: QueueHistoryParams) =>
  6467. request<QueueHistoryPage>(`/queue/history?${queueHistorySearch(params)}`),
  6468. // Removes the history matching the same filters, server-side.
  6469. clearQueueHistory: (params: QueueHistoryFilters) =>
  6470. request<{ cleared: number; kept: number }>(`/queue/history/clear?${queueHistorySearch(params)}`, {
  6471. method: 'POST',
  6472. }),
  6473. // One printer's queue as GET /queue/?printer_id= returns it: its own jobs
  6474. // plus the "Any <model>" jobs for its model. Batched across printer cards.
  6475. getPrinterQueue: (printerId: number, status: string) => printerQueueBatch(status)(printerId),
  6476. addToQueue: (data: PrintQueueItemCreate) =>
  6477. request<PrintQueueItem>('/queue/', {
  6478. method: 'POST',
  6479. body: JSON.stringify(data),
  6480. }),
  6481. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  6482. request<PrintQueueItem>(`/queue/${id}`, {
  6483. method: 'PATCH',
  6484. body: JSON.stringify(data),
  6485. }),
  6486. /** `deleted` is false when the item was kept as cancelled instead: it is the
  6487. * last run a batch order could re-queue its plate from (#2960). */
  6488. removeFromQueue: (id: number) =>
  6489. request<{ message: string; deleted: boolean }>(`/queue/${id}`, { method: 'DELETE' }),
  6490. reorderQueue: (items: { id: number; position: number }[]) =>
  6491. request<{ message: string }>('/queue/reorder', {
  6492. method: 'POST',
  6493. body: JSON.stringify({ items }),
  6494. }),
  6495. cancelQueueItem: (id: number) =>
  6496. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  6497. stopQueueItem: (id: number) =>
  6498. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  6499. /**
  6500. * Start a staged queue item. The backend re-checks live filament deficit
  6501. * for the assigned spool and, when short, returns 409 with a structured
  6502. * payload so the caller can confirm and retry. Pass `skipFilamentCheck`
  6503. * after the user confirms "Print Anyway" (#1496).
  6504. */
  6505. startQueueItem: (id: number, opts?: { skipFilamentCheck?: boolean }) => {
  6506. const qs = opts?.skipFilamentCheck ? '?skip_filament_check=true' : '';
  6507. return request<PrintQueueItem>(`/queue/${id}/start${qs}`, { method: 'POST' });
  6508. },
  6509. /**
  6510. * Clear the `require_previous_success` gate for a printer after the user
  6511. * resolves the failure. Acknowledges any failed/aborted predecessors and
  6512. * restores skipped items whose error_message matches the gate string
  6513. * back to pending. Returns counts so the UI can render a precise toast.
  6514. */
  6515. // A job for any printer of a model waits when the last print failed on every
  6516. // free one; this clears the gate on the model's printers.
  6517. resumeModelQueueAfterFailure: (model: string) =>
  6518. request<{ acknowledged: number; printers: number }>(
  6519. `/queue/model/${encodeURIComponent(model)}/resume`,
  6520. { method: 'POST' },
  6521. ),
  6522. resumeQueueAfterFailure: (printerId: number) =>
  6523. request<{ acknowledged: number; restored: number }>(
  6524. `/queue/printer/${printerId}/resume`,
  6525. { method: 'POST' },
  6526. ),
  6527. bulkUpdateQueue: (data: PrintQueueBulkUpdate) =>
  6528. request<PrintQueueBulkUpdateResponse>('/queue/bulk', {
  6529. method: 'PATCH',
  6530. body: JSON.stringify(data),
  6531. }),
  6532. // Batches
  6533. getBatches: (status?: string) => {
  6534. const params = status ? `?status=${status}` : '';
  6535. return request<PrintBatch[]>(`/queue/batches${params}`);
  6536. },
  6537. cancelBatch: (id: number) =>
  6538. request<{ message: string }>(`/queue/batches/${id}`, { method: 'DELETE' }),
  6539. createBatch: (data: PrintBatchCreate) =>
  6540. request<PrintBatch>('/queue/batches', {
  6541. method: 'POST',
  6542. body: JSON.stringify(data),
  6543. }),
  6544. dispatchBatch: (id: number, data: PrintBatchDispatchRequest = {}) =>
  6545. request<PrintBatch>(`/queue/batches/${id}/dispatch`, {
  6546. method: 'POST',
  6547. body: JSON.stringify(data),
  6548. }),
  6549. ungroupBatch: (id: number) =>
  6550. request<{ ungrouped_count: number; message: string }>(
  6551. `/queue/batches/${id}/ungroup`,
  6552. { method: 'POST' },
  6553. ),
  6554. // K-Profiles
  6555. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  6556. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  6557. setKProfile: (printerId: number, profile: KProfileCreate) =>
  6558. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6559. method: 'POST',
  6560. body: JSON.stringify(profile),
  6561. }),
  6562. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  6563. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/`, {
  6564. method: 'DELETE',
  6565. body: JSON.stringify(profile),
  6566. }),
  6567. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  6568. request<KProfileWriteResult>(`/printers/${printerId}/kprofiles/batch`, {
  6569. method: 'POST',
  6570. body: JSON.stringify(profiles),
  6571. }),
  6572. // Finance
  6573. getMyBalance: () => request<WalletBalance>('/finance/me/balance'),
  6574. getMyTransactions: (limit = 50, offset = 0) =>
  6575. request<WalletTransactionListResponse>(`/finance/me/transactions?limit=${limit}&offset=${offset}`),
  6576. getAllTransactions: (limit = 50, offset = 0, userId?: number) => {
  6577. const params = new URLSearchParams();
  6578. params.set('limit', String(limit));
  6579. params.set('offset', String(offset));
  6580. if (userId !== undefined) params.set('user_id', String(userId));
  6581. return request<WalletTransactionListResponse>(`/finance/transactions?${params.toString()}`);
  6582. },
  6583. deleteTransaction: (transactionId: number) =>
  6584. request<{ status: string }>(`/finance/transactions/${transactionId}`, {
  6585. method: 'DELETE',
  6586. }),
  6587. editTransaction: (transactionId: number, data: TransactionEditRequest) =>
  6588. request<WalletTransaction>(`/finance/transactions/${transactionId}`, {
  6589. method: 'PATCH',
  6590. body: JSON.stringify(data),
  6591. }),
  6592. createManualPrint: (data: ManualPrintRequest) =>
  6593. request<WalletTransaction>('/finance/transactions/manual', {
  6594. method: 'POST',
  6595. body: JSON.stringify(data),
  6596. }),
  6597. getMyCostCenters: () => request<CostCenterSummary[]>('/finance/cost-centers/mine'),
  6598. listCostCenters: (includeInactive = false) =>
  6599. request<CostCenterSummary[]>(`/finance/cost-centers?include_inactive=${includeInactive ? 'true' : 'false'}`),
  6600. createCostCenter: (data: CostCenterCreateRequest) =>
  6601. request<CostCenterSummary>('/finance/cost-centers', {
  6602. method: 'POST',
  6603. body: JSON.stringify(data),
  6604. }),
  6605. updateCostCenter: (costCenterId: number, data: CostCenterUpdateRequest) =>
  6606. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}`, {
  6607. method: 'PATCH',
  6608. body: JSON.stringify(data),
  6609. }),
  6610. updateCostCenterBudgets: (costCenterId: number, data: CostCenterBudgetUpdateRequest) =>
  6611. request<CostCenterSummary>(`/finance/cost-centers/${costCenterId}/budgets`, {
  6612. method: 'PATCH',
  6613. body: JSON.stringify(data),
  6614. }),
  6615. deleteCostCenter: (costCenterId: number) =>
  6616. request<{ status: string }>(`/finance/cost-centers/${costCenterId}`, {
  6617. method: 'DELETE',
  6618. }),
  6619. getCostCenter: (costCenterId: number) =>
  6620. request<CostCenterDetail>(`/finance/cost-centers/${costCenterId}`),
  6621. upsertCostCenterMember: (costCenterId: number, data: CostCenterMemberRequest) =>
  6622. request<CostCenterMemberResponse>(`/finance/cost-centers/${costCenterId}/members`, {
  6623. method: 'POST',
  6624. body: JSON.stringify(data),
  6625. }),
  6626. removeCostCenterMember: (costCenterId: number, userId: number) =>
  6627. request<{ status: string }>(`/finance/cost-centers/${costCenterId}/members/${userId}`, {
  6628. method: 'DELETE',
  6629. }),
  6630. depositUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6631. request<WalletAdjustmentResponse>(`/finance/users/${userId}/deposit`, {
  6632. method: 'POST',
  6633. body: JSON.stringify(data),
  6634. }),
  6635. withdrawUserBalance: (userId: number, data: WalletAdjustmentRequest) =>
  6636. request<WalletAdjustmentResponse>(`/finance/users/${userId}/withdraw`, {
  6637. method: 'POST',
  6638. body: JSON.stringify(data),
  6639. }),
  6640. rebuildBalanceLedger: () =>
  6641. request<{ status: string }>('/finance/rebuild-balance-ledger', {
  6642. method: 'POST',
  6643. }),
  6644. // K-Profile Notes (stored locally, not on printer)
  6645. getKProfileNotes: (printerId: number) =>
  6646. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  6647. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  6648. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  6649. method: 'PUT',
  6650. body: JSON.stringify({ setting_id: settingId, note }),
  6651. }),
  6652. // Slot Preset Mappings
  6653. getSlotPresets: (printerId: number) => slotPresetsBatch(printerId),
  6654. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string, presetSource = 'cloud', trayInfoIdx?: string) =>
  6655. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}&preset_source=${encodeURIComponent(presetSource)}${trayInfoIdx ? `&tray_info_idx=${encodeURIComponent(trayInfoIdx)}` : ''}`, {
  6656. method: 'PUT',
  6657. }),
  6658. // AMS Labels (user-defined friendly names)
  6659. getAmsLabels: (printerId: number) => amsLabelsBatch(printerId),
  6660. saveAmsLabel: (printerId: number, amsId: number, label: string, amsSerial = '') =>
  6661. request<{ ams_id: number; label: string }>(
  6662. `/printers/${printerId}/ams-labels/${amsId}`,
  6663. {
  6664. method: 'PUT',
  6665. body: JSON.stringify({ label, ams_serial: amsSerial }),
  6666. }
  6667. ),
  6668. deleteAmsLabel: (printerId: number, amsId: number, amsSerial = '') =>
  6669. request<{ success: boolean }>(`/printers/${printerId}/ams-labels/${amsId}?ams_serial=${encodeURIComponent(amsSerial)}`, {
  6670. method: 'DELETE',
  6671. }),
  6672. configureAmsSlot: (
  6673. printerId: number,
  6674. amsId: number,
  6675. trayId: number,
  6676. config: {
  6677. tray_info_idx: string;
  6678. tray_type: string;
  6679. tray_sub_brands: string;
  6680. tray_color: string;
  6681. nozzle_temp_min: number;
  6682. nozzle_temp_max: number;
  6683. cali_idx: number;
  6684. nozzle_diameter: string;
  6685. setting_id?: string;
  6686. kprofile_filament_id?: string;
  6687. kprofile_setting_id?: string;
  6688. k_value?: number;
  6689. // Orca Cloud profile the slot is set to; the backend looks up its
  6690. // filament id when tray_info_idx is empty (#3216).
  6691. orca_profile_id?: string;
  6692. }
  6693. ) => {
  6694. const params = new URLSearchParams({
  6695. tray_info_idx: config.tray_info_idx,
  6696. tray_type: config.tray_type,
  6697. tray_sub_brands: config.tray_sub_brands,
  6698. tray_color: config.tray_color,
  6699. nozzle_temp_min: config.nozzle_temp_min.toString(),
  6700. nozzle_temp_max: config.nozzle_temp_max.toString(),
  6701. cali_idx: config.cali_idx.toString(),
  6702. nozzle_diameter: config.nozzle_diameter,
  6703. });
  6704. if (config.setting_id) {
  6705. params.set('setting_id', config.setting_id);
  6706. }
  6707. if (config.kprofile_filament_id) {
  6708. params.set('kprofile_filament_id', config.kprofile_filament_id);
  6709. }
  6710. if (config.kprofile_setting_id) {
  6711. params.set('kprofile_setting_id', config.kprofile_setting_id);
  6712. }
  6713. if (config.k_value !== undefined && config.k_value > 0) {
  6714. params.set('k_value', config.k_value.toString());
  6715. }
  6716. if (config.orca_profile_id) {
  6717. params.set('orca_profile_id', config.orca_profile_id);
  6718. }
  6719. return request<{
  6720. success: boolean;
  6721. message: string;
  6722. // The filament id the slot was actually given.
  6723. tray_info_idx?: string;
  6724. // Why an Orca profile went out as the generic for its material, or "".
  6725. orca_fallback_reason?: '' | 'no_filament_id' | 'lookup_failed' | 'no_permission';
  6726. /** A manual K value could not be sent; the filament setting was. */
  6727. k_value_unsent?: boolean;
  6728. }>(
  6729. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  6730. { method: 'POST' }
  6731. );
  6732. },
  6733. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  6734. request<{ success: boolean; message: string }>(
  6735. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  6736. { method: 'POST' }
  6737. ),
  6738. // Notification Providers
  6739. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  6740. createNotificationProvider: (data: NotificationProviderCreate) =>
  6741. request<NotificationProvider>('/notifications/', {
  6742. method: 'POST',
  6743. body: JSON.stringify(data),
  6744. }),
  6745. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  6746. request<NotificationProvider>(`/notifications/${id}`, {
  6747. method: 'PATCH',
  6748. body: JSON.stringify(data),
  6749. }),
  6750. deleteNotificationProvider: (id: number) =>
  6751. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  6752. testNotificationProvider: (id: number) =>
  6753. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  6754. testNotificationConfig: (data: NotificationTestRequest) =>
  6755. request<NotificationTestResponse>('/notifications/test-config', {
  6756. method: 'POST',
  6757. body: JSON.stringify(data),
  6758. }),
  6759. testAllNotificationProviders: () =>
  6760. request<{
  6761. tested: number;
  6762. success: number;
  6763. failed: number;
  6764. results: Array<{
  6765. provider_id: number;
  6766. provider_name: string;
  6767. provider_type: string;
  6768. success: boolean;
  6769. message: string;
  6770. }>;
  6771. }>('/notifications/test-all', { method: 'POST' }),
  6772. // Notification Templates
  6773. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  6774. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  6775. request<NotificationTemplate>(`/notification-templates/${id}`, {
  6776. method: 'PUT',
  6777. body: JSON.stringify(data),
  6778. }),
  6779. resetNotificationTemplate: (id: number) =>
  6780. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  6781. method: 'POST',
  6782. }),
  6783. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  6784. previewTemplate: (data: TemplatePreviewRequest) =>
  6785. request<TemplatePreviewResponse>('/notification-templates/preview', {
  6786. method: 'POST',
  6787. body: JSON.stringify(data),
  6788. }),
  6789. // Notification Logs
  6790. getNotificationLogs: (params?: {
  6791. limit?: number;
  6792. offset?: number;
  6793. provider_id?: number;
  6794. event_type?: string;
  6795. success?: boolean;
  6796. days?: number;
  6797. }) => {
  6798. const searchParams = new URLSearchParams();
  6799. if (params?.limit) searchParams.set('limit', String(params.limit));
  6800. if (params?.offset) searchParams.set('offset', String(params.offset));
  6801. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  6802. if (params?.event_type) searchParams.set('event_type', params.event_type);
  6803. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  6804. if (params?.days) searchParams.set('days', String(params.days));
  6805. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  6806. },
  6807. getNotificationLogStats: (days = 7) =>
  6808. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  6809. clearNotificationLogs: (olderThanDays = 30) =>
  6810. request<{ deleted: number; message: string }>(
  6811. `/notifications/logs?older_than_days=${olderThanDays}`,
  6812. { method: 'DELETE' }
  6813. ),
  6814. // Spoolman Integration
  6815. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  6816. migrateSpoolmanTags: (dryRun: boolean) =>
  6817. request<SpoolmanTagMigrationReport>(`/spoolman/inventory/tags/migrate?dry_run=${dryRun}`, {
  6818. method: 'POST',
  6819. }),
  6820. connectSpoolman: () =>
  6821. request<{ success: boolean; message: string }>('/spoolman/connect', {
  6822. method: 'POST',
  6823. }),
  6824. syncPrinterAms: (printerId: number) =>
  6825. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  6826. method: 'POST',
  6827. }),
  6828. syncAllPrintersAms: () =>
  6829. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  6830. method: 'POST',
  6831. }),
  6832. getSpoolmanInventoryFilaments: () =>
  6833. request<SpoolmanFilamentEntry[]>('/spoolman/inventory/filaments'),
  6834. getUnlinkedSpools: () =>
  6835. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  6836. getLinkedSpools: () =>
  6837. request<LinkedSpoolsMap>('/spoolman/spools/linked'),
  6838. linkSpool: (
  6839. spoolId: number,
  6840. context: {
  6841. spoolTag: string;
  6842. printerId: number;
  6843. amsId: number;
  6844. trayId: number;
  6845. }
  6846. ) =>
  6847. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  6848. method: 'POST',
  6849. body: JSON.stringify({
  6850. spool_tag: context.spoolTag,
  6851. printer_id: context.printerId,
  6852. ams_id: context.amsId,
  6853. tray_id: context.trayId,
  6854. }),
  6855. }),
  6856. unlinkSpool: (spoolId: number) =>
  6857. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/unlink`, {
  6858. method: 'POST',
  6859. }),
  6860. createSpoolmanSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6861. request<{ success: boolean; spool_id: number | null }>(`/spoolman/spools/from-slot`, {
  6862. method: 'POST',
  6863. body: JSON.stringify(data),
  6864. }),
  6865. createSpoolFromSlot: (data: { printer_id: number; ams_id: number; tray_id: number }) =>
  6866. request<InventorySpool>(`/inventory/spools/from-slot`, {
  6867. method: 'POST',
  6868. body: JSON.stringify(data),
  6869. }),
  6870. getSpoolmanSettings: () =>
  6871. 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'),
  6872. 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; }) =>
  6873. 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', {
  6874. method: 'PUT',
  6875. body: JSON.stringify(data),
  6876. }),
  6877. // Inventory
  6878. getSpools: (includeArchived = false) =>
  6879. request<InventorySpool[]>(`/inventory/spools?include_archived=${includeArchived}`),
  6880. getSpool: (id: number) => request<InventorySpool>(`/inventory/spools/${id}`),
  6881. createSpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  6882. request<InventorySpool>('/inventory/spools', {
  6883. method: 'POST',
  6884. body: JSON.stringify(data),
  6885. }),
  6886. bulkCreateSpools: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>, quantity: number) =>
  6887. request<InventorySpool[]>('/inventory/spools/bulk', {
  6888. method: 'POST',
  6889. body: JSON.stringify({ spool: data, quantity }),
  6890. }),
  6891. // ── CSV import/export (#1576) ────────────────────────────────────────────
  6892. // dry_run=true → preview (no write); omitted → real import. Both share one
  6893. // multipart upload helper; see `uploadSpoolsCsv` below.
  6894. importSpoolsCsvPreview: (file: File): Promise<CsvImportPreview> => uploadSpoolsCsv<CsvImportPreview>(file, true),
  6895. importSpoolsCsv: (file: File): Promise<CsvImportResult> => uploadSpoolsCsv<CsvImportResult>(file, false),
  6896. exportSpoolsCsv: async (): Promise<void> => {
  6897. const headers: Record<string, string> = {};
  6898. if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
  6899. const response = await fetch(`${API_BASE}/inventory/spools/export`, { headers });
  6900. if (!response.ok) {
  6901. const error = await response.json().catch(() => ({}));
  6902. throw new Error(error.detail || `HTTP ${response.status}`);
  6903. }
  6904. const disposition = response.headers.get('Content-Disposition');
  6905. const filename = parseContentDispositionFilename(disposition) || 'bambuddy_inventory.csv';
  6906. const blob = await response.blob();
  6907. const url = window.URL.createObjectURL(blob);
  6908. const a = document.createElement('a');
  6909. a.href = url;
  6910. a.download = filename;
  6911. document.body.appendChild(a);
  6912. a.click();
  6913. document.body.removeChild(a);
  6914. window.URL.revokeObjectURL(url);
  6915. },
  6916. updateSpool: (id: number, data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6917. request<InventorySpool>(`/inventory/spools/${id}`, {
  6918. method: 'PATCH',
  6919. body: JSON.stringify(data),
  6920. }),
  6921. deleteSpool: (id: number) =>
  6922. request<{ status: string }>(`/inventory/spools/${id}`, { method: 'DELETE' }),
  6923. archiveSpool: (id: number) =>
  6924. request<InventorySpool>(`/inventory/spools/${id}/archive`, { method: 'POST' }),
  6925. restoreSpool: (id: number) =>
  6926. request<InventorySpool>(`/inventory/spools/${id}/restore`, { method: 'POST' }),
  6927. resetSpoolConsumedCounter: (id: number) =>
  6928. request<InventorySpool>(`/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  6929. bulkResetSpoolConsumedCounter: (spoolIds: number[]) =>
  6930. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/inventory/spools/reset-consumed-counter-bulk`, {
  6931. method: 'POST',
  6932. body: JSON.stringify({ spool_ids: spoolIds }),
  6933. }),
  6934. bulkUpdateSpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  6935. request<{ updated: number; not_found: number[] }>(`/inventory/spools/bulk-update`, {
  6936. method: 'POST',
  6937. body: JSON.stringify({ ids, update }),
  6938. }),
  6939. bulkDeleteSpools: (ids: number[]) =>
  6940. request<{ deleted: number; not_found: number[] }>(`/inventory/spools/bulk-delete`, {
  6941. method: 'POST',
  6942. body: JSON.stringify({ ids }),
  6943. }),
  6944. bulkArchiveSpools: (ids: number[]) =>
  6945. request<{ archived: number; already_archived: number[]; not_found: number[] }>(`/inventory/spools/bulk-archive`, {
  6946. method: 'POST',
  6947. body: JSON.stringify({ ids }),
  6948. }),
  6949. bulkRestoreSpools: (ids: number[]) =>
  6950. request<{ restored: number; already_active: number[]; not_found: number[] }>(`/inventory/spools/bulk-restore`, {
  6951. method: 'POST',
  6952. body: JSON.stringify({ ids }),
  6953. }),
  6954. getSpoolKProfiles: (spoolId: number) =>
  6955. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`),
  6956. saveSpoolKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  6957. request<SpoolKProfile[]>(`/inventory/spools/${spoolId}/k-profiles`, {
  6958. method: 'PUT',
  6959. body: JSON.stringify(profiles),
  6960. }),
  6961. /**
  6962. * What the spool assigned to this slot is configured to use *here* -- its
  6963. * per-printer-model filament preset and the K profile for this slot's hotend.
  6964. * Nulls when the slot holds no known spool.
  6965. */
  6966. getSlotSpoolDefaults: (printerId: number, amsId: number, trayId: number) =>
  6967. request<SlotSpoolDefaults>(`/printers/${printerId}/slots/${amsId}/${trayId}/spool-defaults`),
  6968. getSpoolFilamentPresets: (spoolId: number) =>
  6969. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`),
  6970. saveSpoolFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  6971. request<SpoolFilamentPreset[]>(`/inventory/spools/${spoolId}/filament-presets`, {
  6972. method: 'PUT',
  6973. body: JSON.stringify(presets),
  6974. }),
  6975. getProfileDefaults: () => request<ProfileDefault[]>('/inventory/profile-defaults'),
  6976. resolveProfileDefault: (key: ProfileDefaultKey) => {
  6977. const params = new URLSearchParams({
  6978. brand: key.brand,
  6979. material: key.material,
  6980. subtype: key.subtype,
  6981. color_name: key.color_name,
  6982. });
  6983. return request<ResolvedProfileDefault | null>(`/inventory/profile-defaults/resolve?${params}`);
  6984. },
  6985. saveProfileDefault: (data: ProfileDefaultInput) =>
  6986. request<ProfileDefault>('/inventory/profile-defaults', {
  6987. method: 'PUT',
  6988. body: JSON.stringify(data),
  6989. }),
  6990. deleteProfileDefault: (defaultId: number) =>
  6991. request<{ status: string }>(`/inventory/profile-defaults/${defaultId}`, { method: 'DELETE' }),
  6992. /** Fills in what active spools of the default's product lack; the inventory mode picks the route. */
  6993. applyProfileDefault: (defaultId: number, spoolmanMode: boolean) =>
  6994. request<{ updated: number }>(
  6995. spoolmanMode
  6996. ? `/spoolman/inventory/profile-defaults/${defaultId}/apply`
  6997. : `/inventory/profile-defaults/${defaultId}/apply`,
  6998. { method: 'POST' },
  6999. ),
  7000. getAssignments: (printerId?: number) =>
  7001. request<SpoolAssignment[]>(`/inventory/assignments${printerId ? `?printer_id=${printerId}` : ''}`),
  7002. // move: the spool also leaves any other slot it is in, in the same
  7003. // transaction (#1574) -- for a scanned spool, the one in the user's hand.
  7004. assignSpool: (data: { spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7005. request<SpoolAssignment>('/inventory/assignments', {
  7006. method: 'POST',
  7007. body: JSON.stringify(data),
  7008. }),
  7009. unassignSpool: (printerId: number, amsId: number, trayId: number) =>
  7010. request<{ status: string }>(`/inventory/assignments/${printerId}/${amsId}/${trayId}`, { method: 'DELETE' }),
  7011. // ── Spool label printing (#809) ──────────────────────────────────────────
  7012. // The print endpoints return a PDF, a PNG, or a ZIP of PNGs (#2981); the
  7013. // preview endpoints one PNG. Callers get the Blob and decide what to do.
  7014. printSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  7015. postForBlob('/inventory/labels', data),
  7016. printSpoolmanSpoolLabels: (data: PrintSpoolLabelsRequest): Promise<Blob> =>
  7017. postForBlob('/spoolman/labels', data),
  7018. previewSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  7019. postForBlob('/inventory/labels/preview', data, signal),
  7020. previewSpoolmanSpoolLabel: (data: PreviewSpoolLabelRequest, signal?: AbortSignal): Promise<Blob> =>
  7021. postForBlob('/spoolman/labels/preview', data, signal),
  7022. getLabelTemplates: () => request<SavedLabelTemplate[]>('/label-templates'),
  7023. createLabelTemplate: (data: { name: string; layout: LabelSheetLayout }) =>
  7024. request<SavedLabelTemplate>('/label-templates', { method: 'POST', body: JSON.stringify(data) }),
  7025. updateLabelTemplate: (id: number, data: { name: string; layout: LabelSheetLayout }) =>
  7026. request<SavedLabelTemplate>(`/label-templates/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7027. deleteLabelTemplate: (id: number) => request<void>(`/label-templates/${id}`, { method: 'DELETE' }),
  7028. getSpoolCatalog: () =>
  7029. request<SpoolCatalogEntry[]>('/inventory/catalog'),
  7030. addCatalogEntry: (data: { name: string; weight: number }) =>
  7031. request<SpoolCatalogEntry>('/inventory/catalog', { method: 'POST', body: JSON.stringify(data) }),
  7032. updateCatalogEntry: (id: number, data: { name: string; weight: number }) =>
  7033. request<SpoolCatalogEntry>(`/inventory/catalog/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7034. deleteCatalogEntry: (id: number) =>
  7035. request<{ status: string }>(`/inventory/catalog/${id}`, { method: 'DELETE' }),
  7036. bulkDeleteCatalogEntries: (ids: number[]) =>
  7037. request<{ deleted: number }>('/inventory/catalog/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7038. resetSpoolCatalog: () =>
  7039. request<{ status: string }>('/inventory/catalog/reset', { method: 'POST' }),
  7040. // ── Suppliers (#2988) — inventory master data, Locations pattern ─────────
  7041. getSuppliers: () =>
  7042. request<Supplier[]>('/inventory/suppliers'),
  7043. createSupplier: (data: SupplierInput) =>
  7044. request<Supplier>('/inventory/suppliers', { method: 'POST', body: JSON.stringify(data) }),
  7045. updateSupplier: (id: number, data: Partial<SupplierInput>) =>
  7046. request<Supplier>(`/inventory/suppliers/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  7047. deleteSupplier: (id: number) =>
  7048. request<{ status: string }>(`/inventory/suppliers/${id}`, { method: 'DELETE' }),
  7049. setSpoolSuppliers: (spoolId: number, links: SpoolSupplierLinkInput[]) =>
  7050. request<SpoolSupplierLink[]>(`/inventory/spools/${spoolId}/suppliers`, {
  7051. method: 'PUT',
  7052. body: JSON.stringify(links),
  7053. }),
  7054. // Spoolman parity: the assignment rows live Bambuddy-side, keyed by the
  7055. // remote spool id — same request/response shape as the built-in inventory.
  7056. setSpoolmanSpoolSuppliers: (spoolmanSpoolId: number, links: SpoolSupplierLinkInput[]) =>
  7057. request<SpoolSupplierLink[]>(`/spoolman/inventory/spools/${spoolmanSpoolId}/suppliers`, {
  7058. method: 'PUT',
  7059. body: JSON.stringify(links),
  7060. }),
  7061. // date_from/date_to scope the usage half only, so the widget can follow the
  7062. // dashboard timeframe; stock stays point-in-time.
  7063. getSupplierStats: (dateFrom?: string, dateTo?: string) => {
  7064. const params = new URLSearchParams();
  7065. if (dateFrom) params.set('date_from', dateFrom);
  7066. if (dateTo) params.set('date_to', dateTo);
  7067. addDayZone(params);
  7068. const qs = params.toString();
  7069. return request<SupplierStats[]>(`/inventory/stats/suppliers${qs ? `?${qs}` : ''}`);
  7070. },
  7071. getLocations: () =>
  7072. request<StorageLocation[]>('/inventory/locations'),
  7073. createLocation: (data: { name: string; identifier?: string | null }) =>
  7074. request<StorageLocation>('/inventory/locations', { method: 'POST', body: JSON.stringify(data) }),
  7075. updateLocation: (id: number, data: { name?: string; identifier?: string | null }) =>
  7076. request<StorageLocation>(`/inventory/locations/${id}`, { method: 'PATCH', body: JSON.stringify(data) }),
  7077. deleteLocation: (id: number) =>
  7078. request<{ status: string }>(`/inventory/locations/${id}`, { method: 'DELETE' }),
  7079. getColorCatalog: () =>
  7080. request<ColorCatalogEntry[]>('/inventory/colors'),
  7081. /** Flat hex→name map, plus the names collapsing it loses. ``by_material`` is
  7082. * keyed ``"<material>|<hex>"`` and only carries entries that differ from the
  7083. * flat answer (e.g. ``"pla matte|ffffff" -> "Ivory White"`` where the flat
  7084. * map says "Jade White"). #2875. */
  7085. getColorNameMap: () =>
  7086. request<{
  7087. colors: Record<string, string>;
  7088. by_material?: Record<string, string>;
  7089. bambu?: BambuCatalogColor[];
  7090. preset_materials?: Record<string, string>;
  7091. }>('/inventory/colors/map'),
  7092. addColorEntry: (data: {
  7093. manufacturer: string;
  7094. color_name: string;
  7095. hex_color: string;
  7096. material: string | null;
  7097. extra_colors?: string | null;
  7098. effect_type?: string | null;
  7099. }) =>
  7100. request<ColorCatalogEntry>('/inventory/colors', { method: 'POST', body: JSON.stringify(data) }),
  7101. updateColorEntry: (
  7102. id: number,
  7103. data: {
  7104. manufacturer: string;
  7105. color_name: string;
  7106. hex_color: string;
  7107. material: string | null;
  7108. extra_colors?: string | null;
  7109. effect_type?: string | null;
  7110. },
  7111. ) => request<ColorCatalogEntry>(`/inventory/colors/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  7112. deleteColorEntry: (id: number) =>
  7113. request<{ status: string }>(`/inventory/colors/${id}`, { method: 'DELETE' }),
  7114. bulkDeleteColorEntries: (ids: number[]) =>
  7115. request<{ deleted: number }>('/inventory/colors/bulk-delete', { method: 'POST', body: JSON.stringify({ ids }) }),
  7116. resetColorCatalog: () =>
  7117. request<{ status: string }>('/inventory/colors/reset', { method: 'POST' }),
  7118. searchColors: (manufacturer?: string, material?: string) =>
  7119. request<ColorCatalogEntry[]>(`/inventory/colors/search?${manufacturer ? `manufacturer=${encodeURIComponent(manufacturer)}` : ''}${manufacturer && material ? '&' : ''}${material ? `material=${encodeURIComponent(material)}` : ''}`),
  7120. linkTagToSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string; tag_type?: string; data_origin?: string }) =>
  7121. request<InventorySpool>(`/inventory/spools/${spoolId}/link-tag`, {
  7122. method: 'PATCH',
  7123. body: JSON.stringify(data),
  7124. }),
  7125. // Per-material-number inventory aggregate (#2870). The date range narrows
  7126. // the usage half only — stock is point-in-time.
  7127. getMaterialNumberStats: (options?: { dateFrom?: string; dateTo?: string }) => {
  7128. const params = new URLSearchParams();
  7129. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  7130. if (options?.dateTo) params.set('date_to', options.dateTo);
  7131. addDayZone(params);
  7132. const qs = params.toString();
  7133. return request<MaterialNumberStats[]>(`/inventory/stats/material-numbers${qs ? `?${qs}` : ''}`);
  7134. },
  7135. getSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7136. request<SpoolUsageRecord[]>(`/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7137. // One inventory's at a time: ``spoolman`` for the Spoolman spools' (#3407).
  7138. getAllUsageHistory: (limit = 100, printerId?: number, spoolman = false) =>
  7139. request<SpoolUsageRecord[]>(
  7140. `/inventory/usage?limit=${limit}${printerId ? `&printer_id=${printerId}` : ''}${spoolman ? '&spoolman=true' : ''}`,
  7141. ),
  7142. getSpoolmanSpoolUsageHistory: (spoolId: number, limit = 50) =>
  7143. request<SpoolUsageRecord[]>(`/spoolman/inventory/spools/${spoolId}/usage?limit=${limit}`),
  7144. clearSpoolmanSpoolUsageHistory: (spoolId: number) =>
  7145. request<{ status: string }>(`/spoolman/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7146. clearSpoolUsageHistory: (spoolId: number) =>
  7147. request<{ status: string }>(`/inventory/spools/${spoolId}/usage`, { method: 'DELETE' }),
  7148. syncWeightsFromAms: () =>
  7149. request<{ synced: number; skipped: number; printing?: number }>('/inventory/sync-ams-weights', { method: 'POST' }),
  7150. getSkuSettings: () =>
  7151. request<FilamentSkuSettings[]>('/inventory/sku-settings'),
  7152. upsertSkuSettings: (data: Omit<FilamentSkuSettings, 'id'>) =>
  7153. request<FilamentSkuSettings>('/inventory/sku-settings', {
  7154. method: 'POST',
  7155. body: JSON.stringify(data),
  7156. }),
  7157. getShoppingList: () =>
  7158. request<ShoppingListItem[]>('/inventory/shopping-list'),
  7159. addToShoppingList: (data: ShoppingListItemCreate) =>
  7160. request<ShoppingListItem>('/inventory/shopping-list', {
  7161. method: 'POST',
  7162. body: JSON.stringify(data),
  7163. }),
  7164. removeFromShoppingList: (id: number) =>
  7165. request<{ status: string }>(`/inventory/shopping-list/${id}`, { method: 'DELETE' }),
  7166. clearShoppingList: () =>
  7167. request<{ deleted: number }>('/inventory/shopping-list', { method: 'DELETE' }),
  7168. updateShoppingListStatus: (id: number, status: 'pending' | 'purchased' | 'received') =>
  7169. request<ShoppingListItem>(`/inventory/shopping-list/${id}/status`, {
  7170. method: 'PATCH',
  7171. body: JSON.stringify({ status }),
  7172. }),
  7173. getFilamentPresets: () =>
  7174. request<SlicerSetting[]>('/cloud/filaments'),
  7175. // Spoolman Inventory proxy (unified UI when Spoolman is enabled)
  7176. getSpoolmanInventorySpools: (includeArchived = false) =>
  7177. request<InventorySpool[]>(`/spoolman/inventory/spools?include_archived=${includeArchived}`),
  7178. getSpoolmanInventorySpool: (id: number) =>
  7179. request<InventorySpool>(`/spoolman/inventory/spools/${id}`),
  7180. createSpoolmanInventorySpool: (data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>) =>
  7181. request<InventorySpool>('/spoolman/inventory/spools', {
  7182. method: 'POST',
  7183. body: JSON.stringify(data),
  7184. }),
  7185. bulkCreateSpoolmanInventorySpools: (
  7186. data: Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>,
  7187. quantity: number,
  7188. ) =>
  7189. request<SpoolmanBulkCreateResult | InventorySpool[]>('/spoolman/inventory/spools/bulk', {
  7190. method: 'POST',
  7191. body: JSON.stringify({ spool: data, quantity }),
  7192. }),
  7193. updateSpoolmanInventorySpool: (
  7194. id: number,
  7195. data: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>,
  7196. ) =>
  7197. request<InventorySpool>(`/spoolman/inventory/spools/${id}`, {
  7198. method: 'PATCH',
  7199. body: JSON.stringify(data),
  7200. }),
  7201. deleteSpoolmanInventorySpool: (id: number) =>
  7202. request<{ status: string }>(`/spoolman/inventory/spools/${id}`, { method: 'DELETE' }),
  7203. archiveSpoolmanInventorySpool: (id: number) =>
  7204. request<InventorySpool>(`/spoolman/inventory/spools/${id}/archive`, { method: 'POST' }),
  7205. restoreSpoolmanInventorySpool: (id: number) =>
  7206. request<InventorySpool>(`/spoolman/inventory/spools/${id}/restore`, { method: 'POST' }),
  7207. resetSpoolmanInventorySpoolConsumedCounter: (id: number) =>
  7208. request<InventorySpool>(`/spoolman/inventory/spools/${id}/reset-consumed-counter`, { method: 'POST' }),
  7209. bulkResetSpoolmanInventorySpoolConsumedCounter: (spoolIds: number[]) =>
  7210. request<{ reset: number; not_found?: number[]; errors?: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/reset-consumed-counter-bulk`, {
  7211. method: 'POST',
  7212. body: JSON.stringify({ spool_ids: spoolIds }),
  7213. }),
  7214. bulkUpdateSpoolmanInventorySpools: (ids: number[], update: Partial<Omit<InventorySpool, 'id' | 'archived_at' | 'created_at' | 'updated_at' | 'k_profiles'>>) =>
  7215. request<{ updated: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-update`, {
  7216. method: 'POST',
  7217. body: JSON.stringify({ ids, update }),
  7218. }),
  7219. bulkDeleteSpoolmanInventorySpools: (ids: number[]) =>
  7220. request<{ deleted: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-delete`, {
  7221. method: 'POST',
  7222. body: JSON.stringify({ ids }),
  7223. }),
  7224. bulkArchiveSpoolmanInventorySpools: (ids: number[]) =>
  7225. request<{ archived: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-archive`, {
  7226. method: 'POST',
  7227. body: JSON.stringify({ ids }),
  7228. }),
  7229. bulkRestoreSpoolmanInventorySpools: (ids: number[]) =>
  7230. request<{ restored: number; errors: Array<{ id: number; status: number; detail: string }> }>(`/spoolman/inventory/spools/bulk-restore`, {
  7231. method: 'POST',
  7232. body: JSON.stringify({ ids }),
  7233. }),
  7234. linkTagToSpoolmanSpool: (spoolId: number, data: { tag_uid?: string; tray_uuid?: string }) =>
  7235. request<InventorySpool>(`/spoolman/inventory/spools/${spoolId}/tag`, {
  7236. method: 'PATCH',
  7237. body: JSON.stringify(data),
  7238. }),
  7239. syncSpoolmanSpoolWeight: (spoolId: number, weightGrams: number) =>
  7240. request<{ status: string; weight_used: number }>(`/spoolman/inventory/spools/${spoolId}/weight`, {
  7241. method: 'PATCH',
  7242. body: JSON.stringify({ weight_grams: weightGrams }),
  7243. }),
  7244. // move: as assignSpool's (#1574).
  7245. assignSpoolmanSlot: (data: { spoolman_spool_id: number; printer_id: number; ams_id: number; tray_id: number; move?: boolean }) =>
  7246. request<InventorySpool>('/spoolman/inventory/slot-assignments', {
  7247. method: 'POST',
  7248. body: JSON.stringify(data),
  7249. }),
  7250. unassignSpoolmanSlot: (spoolmanSpoolId: number) =>
  7251. request<InventorySpool>(`/spoolman/inventory/slot-assignments/${spoolmanSpoolId}`, { method: 'DELETE' }),
  7252. getSpoolmanSlotAssignments: (printerId?: number) =>
  7253. request<Array<{
  7254. printer_id: number;
  7255. printer_name: string | null;
  7256. ams_id: number;
  7257. tray_id: number;
  7258. spoolman_spool_id: number;
  7259. ams_label: string | null;
  7260. printer_model?: string | null;
  7261. }>>(
  7262. printerId !== undefined
  7263. ? `/spoolman/inventory/slot-assignments/all?printer_id=${printerId}`
  7264. : '/spoolman/inventory/slot-assignments/all',
  7265. ),
  7266. syncSpoolmanAmsWeights: () =>
  7267. request<{ synced: number; skipped: number; printing?: number }>('/spoolman/inventory/sync-ams-weights', { method: 'POST' }),
  7268. saveSpoolmanKProfiles: (spoolId: number, profiles: SpoolKProfileInput[]) =>
  7269. request<SpoolKProfile[]>(`/spoolman/inventory/spools/${spoolId}/k-profiles`, {
  7270. method: 'PUT',
  7271. body: JSON.stringify(profiles),
  7272. }),
  7273. getSpoolmanFilamentPresets: (spoolId: number) =>
  7274. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`),
  7275. saveSpoolmanFilamentPresets: (spoolId: number, presets: SpoolFilamentPresetInput[]) =>
  7276. request<SpoolFilamentPreset[]>(`/spoolman/inventory/spools/${spoolId}/filament-presets`, {
  7277. method: 'PUT',
  7278. body: JSON.stringify(presets),
  7279. }),
  7280. // Updates
  7281. getVersion: () => request<VersionInfo>('/updates/version'),
  7282. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  7283. applyUpdate: () =>
  7284. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean; is_ha_addon?: boolean; is_windows_installer?: boolean }>('/updates/apply', {
  7285. method: 'POST',
  7286. }),
  7287. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  7288. // Maintenance
  7289. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  7290. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  7291. request<MaintenanceType>('/maintenance/types', {
  7292. method: 'POST',
  7293. body: JSON.stringify(data),
  7294. }),
  7295. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  7296. request<MaintenanceType>(`/maintenance/types/${id}`, {
  7297. method: 'PATCH',
  7298. body: JSON.stringify(data),
  7299. }),
  7300. deleteMaintenanceType: (id: number) =>
  7301. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  7302. restoreDefaultMaintenanceTypes: () =>
  7303. request<{ restored: number }>(`/maintenance/types/restore-defaults`, { method: 'POST' }),
  7304. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  7305. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  7306. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  7307. method: 'PATCH',
  7308. body: JSON.stringify(data),
  7309. }),
  7310. performMaintenance: (itemId: number, notes?: string) =>
  7311. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  7312. method: 'POST',
  7313. body: JSON.stringify({ notes }),
  7314. }),
  7315. setPrinterHours: (printerId: number, totalHours: number) =>
  7316. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  7317. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  7318. { method: 'PATCH' }
  7319. ),
  7320. assignMaintenanceType: (printerId: number, typeId: number) =>
  7321. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  7322. method: 'POST',
  7323. }),
  7324. removeMaintenanceItem: (itemId: number) =>
  7325. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  7326. method: 'DELETE',
  7327. }),
  7328. // Camera
  7329. getCameraStreamToken: () =>
  7330. request<{ token: string }>('/printers/camera/stream-token', { method: 'POST' }),
  7331. // Media token (#3025) — the credential for thumbnails, plate previews,
  7332. // timelapses, cover images and link icons. Minted behind plain auth rather
  7333. // than camera:view, and identified, so those routes gate on the resource's
  7334. // own permission and ownership instead of on the camera.
  7335. getMediaToken: () => request<{ token: string }>('/auth/media-token', { method: 'POST' }),
  7336. // WebSocket auth (GHSA-r2qv follow-up) — mint a short-lived token for
  7337. // the /ws connection. Browsers can't attach Authorization headers to a
  7338. // WebSocket handshake, so the token rides in the ?token= query param.
  7339. getWebSocketToken: () =>
  7340. request<{ token: string }>('/auth/ws-token', { method: 'POST' }),
  7341. // Connected apps: sign-in to external applications with Bambuddy
  7342. listConnectedApps: () => request<ConnectedApp[]>('/connect/apps'),
  7343. createConnectedApp: (payload: { name: string; redirect_uri: string }) =>
  7344. request<ConnectedApp>('/connect/apps', { method: 'POST', body: JSON.stringify(payload) }),
  7345. updateConnectedApp: (id: number, payload: { name?: string; redirect_uri?: string; enabled?: boolean }) =>
  7346. request<ConnectedApp>(`/connect/apps/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
  7347. rotateConnectedAppSecret: (id: number) =>
  7348. request<ConnectedApp>(`/connect/apps/${id}/rotate-secret`, { method: 'POST' }),
  7349. deleteConnectedApp: (id: number) => request<void>(`/connect/apps/${id}`, { method: 'DELETE' }),
  7350. getConnectAuthorizeInfo: (clientId: string, redirectUri: string) =>
  7351. request<ConnectAuthorizeInfo>(
  7352. `/connect/authorize/info?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}`,
  7353. ),
  7354. connectAuthorize: (payload: {
  7355. client_id: string;
  7356. redirect_uri: string;
  7357. code_challenge: string;
  7358. code_challenge_method: 'S256';
  7359. }) =>
  7360. request<{ code: string; redirect_uri: string }>('/connect/authorize', {
  7361. method: 'POST',
  7362. body: JSON.stringify(payload),
  7363. }),
  7364. // Long-lived camera tokens (#1108, #2531)
  7365. createLongLivedCameraToken: (payload: {
  7366. name: string;
  7367. expires_in_days: number;
  7368. scope?: LongLivedTokenScope;
  7369. }) =>
  7370. request<LongLivedCameraToken>('/auth/tokens', {
  7371. method: 'POST',
  7372. body: JSON.stringify({ scope: 'camera_stream', ...payload }),
  7373. }),
  7374. listMyLongLivedCameraTokens: () =>
  7375. request<LongLivedCameraToken[]>('/auth/tokens'),
  7376. listAllLongLivedCameraTokens: () =>
  7377. request<LongLivedCameraToken[]>('/auth/tokens/all'),
  7378. revokeLongLivedCameraToken: (tokenId: number) =>
  7379. request<void>(`/auth/tokens/${tokenId}`, { method: 'DELETE' }),
  7380. // Token-authenticated Cam Wall feed (#2531). `token` is omitted only when
  7381. // auth is disabled, where the backend gate is a no-op anyway.
  7382. getCamWallPrinters: (token?: string) =>
  7383. request<CamWallPrinter[]>(
  7384. token ? `/camwall/printers?token=${encodeURIComponent(token)}` : '/camwall/printers',
  7385. ),
  7386. // Token-authenticated streaming-overlay feed (#2613). OBS (or any embed with
  7387. // no login session) loads /overlay/{id}?token=... and this backs it. `token`
  7388. // is omitted only when auth is disabled, where the backend gate is a no-op.
  7389. getOverlayStatus: (printerId: number, token?: string) =>
  7390. request<OverlayStatus>(
  7391. token
  7392. ? `/printers/${printerId}/overlay-status?token=${encodeURIComponent(token)}`
  7393. : `/printers/${printerId}/overlay-status`,
  7394. ),
  7395. getCameraStatus: (printerId: number) =>
  7396. request<{ active: boolean; stalled: boolean }>(`/printers/${printerId}/camera/status`),
  7397. diagnoseCamera: (printerId: number) =>
  7398. request<CameraDiagnoseResult>(`/printers/${printerId}/camera/diagnose`, { method: 'POST' }),
  7399. diagnosePrinter: (printerId: number) =>
  7400. request<PrinterDiagnosticResult>(`/printers/${printerId}/diagnostic`),
  7401. diagnoseConnection: (body: {
  7402. ip_address: string;
  7403. serial_number?: string;
  7404. access_code?: string;
  7405. }) =>
  7406. request<PrinterDiagnosticResult>('/printers/diagnostic', {
  7407. method: 'POST',
  7408. body: JSON.stringify(body),
  7409. }),
  7410. // Plate Detection - Multi-reference calibration (stores up to 5 references per printer)
  7411. checkPlateEmpty: (printerId: number, options?: { useExternal?: boolean; includeDebugImage?: boolean }) => {
  7412. const params = new URLSearchParams();
  7413. // Only forward use_external when the caller explicitly sets it. Omitted →
  7414. // backend derives the default from the printer's external_camera_enabled
  7415. // setting so calibration and runtime checks use the same camera (#1359).
  7416. if (options?.useExternal !== undefined) {
  7417. params.set('use_external', String(options.useExternal));
  7418. }
  7419. params.set('include_debug_image', String(options?.includeDebugImage ?? false));
  7420. return request<PlateDetectionResult>(
  7421. `/printers/${printerId}/camera/check-plate?${params.toString()}`
  7422. );
  7423. },
  7424. calibratePlateDetection: (printerId: number, options?: { label?: string; useExternal?: boolean }) => {
  7425. const params = new URLSearchParams();
  7426. if (options?.label) params.set('label', options.label);
  7427. if (options?.useExternal !== undefined) {
  7428. params.set('use_external', String(options.useExternal));
  7429. }
  7430. return request<CalibrationResult & { index: number }>(
  7431. `/printers/${printerId}/camera/plate-detection/calibrate?${params.toString()}`,
  7432. { method: 'POST' }
  7433. );
  7434. },
  7435. getPlateReferences: (printerId: number) => {
  7436. return request<{
  7437. references: PlateReference[];
  7438. max_references: number;
  7439. }>(`/printers/${printerId}/camera/plate-detection/references`);
  7440. },
  7441. getPlateReferenceThumbnailUrl: (printerId: number, index: number) =>
  7442. withStreamToken(`${API_BASE}/printers/${printerId}/camera/plate-detection/references/${index}/thumbnail`),
  7443. updatePlateReferenceLabel: (printerId: number, index: number, label: string) => {
  7444. const params = new URLSearchParams();
  7445. params.set('label', label);
  7446. return request<{ success: boolean; index: number; label: string }>(
  7447. `/printers/${printerId}/camera/plate-detection/references/${index}?${params.toString()}`,
  7448. { method: 'PUT' }
  7449. );
  7450. },
  7451. deletePlateReference: (printerId: number, index: number) => {
  7452. return request<{ success: boolean; message: string }>(
  7453. `/printers/${printerId}/camera/plate-detection/references/${index}`,
  7454. { method: 'DELETE' }
  7455. );
  7456. },
  7457. // External Links
  7458. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  7459. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  7460. createExternalLink: (data: ExternalLinkCreate) =>
  7461. request<ExternalLink>('/external-links/', {
  7462. method: 'POST',
  7463. body: JSON.stringify(data),
  7464. }),
  7465. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  7466. request<ExternalLink>(`/external-links/${id}`, {
  7467. method: 'PATCH',
  7468. body: JSON.stringify(data),
  7469. }),
  7470. deleteExternalLink: (id: number) =>
  7471. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  7472. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  7473. const formData = new FormData();
  7474. formData.append('file', file);
  7475. const headers: Record<string, string> = {};
  7476. if (authToken) {
  7477. headers['Authorization'] = `Bearer ${authToken}`;
  7478. }
  7479. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  7480. method: 'POST',
  7481. headers,
  7482. body: formData,
  7483. });
  7484. if (!response.ok) {
  7485. const error = await response.json().catch(() => ({}));
  7486. throw new Error(error.detail || `HTTP ${response.status}`);
  7487. }
  7488. return response.json();
  7489. },
  7490. deleteExternalLinkIcon: (id: number) =>
  7491. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  7492. getExternalLinkIconUrl: (id: number) => withMediaToken(`${API_BASE}/external-links/${id}/icon`),
  7493. // Projects
  7494. getProjects: (status?: string) => {
  7495. const params = new URLSearchParams();
  7496. if (status) params.set('status', status);
  7497. return request<ProjectListItem[]>(`/projects/?${params}`);
  7498. },
  7499. getProject: (id: number) => request<Project>(`/projects/${id}`),
  7500. createProject: (data: ProjectCreate) =>
  7501. request<Project>('/projects/', {
  7502. method: 'POST',
  7503. body: JSON.stringify(data),
  7504. }),
  7505. updateProject: (id: number, data: ProjectUpdate) =>
  7506. request<Project>(`/projects/${id}`, {
  7507. method: 'PATCH',
  7508. body: JSON.stringify(data),
  7509. }),
  7510. deleteProject: (id: number) =>
  7511. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  7512. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  7513. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  7514. // Completed-run counts per library file (#1897); files with 0 runs are omitted
  7515. getProjectFileProgress: (id: number) =>
  7516. request<ProjectFileProgress[]>(`/projects/${id}/file-progress`),
  7517. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  7518. request<{ message: string; count: number }>(`/projects/${projectId}/add-archives`, {
  7519. method: 'POST',
  7520. body: JSON.stringify({ archive_ids: archiveIds }),
  7521. }),
  7522. // #1155: Cover image
  7523. // Browsers can't attach `Authorization: Bearer ...` to `<img src>`, so we
  7524. // append the stream-token query string the same way archive thumbnails do.
  7525. // `version` cache-busts the browser copy after a re-upload. It has to go on
  7526. // before the token does: callers used to append their own `?v=` to the
  7527. // returned URL, which already ended in `?token=…`, so the second `?` landed
  7528. // inside the token value and the image 401'd whenever auth was enabled.
  7529. getProjectCoverImageUrl: (projectId: number, version?: string | number) =>
  7530. withMediaToken(
  7531. `${API_BASE}/projects/${projectId}/cover-image${
  7532. version === undefined ? '' : `?v=${encodeURIComponent(String(version))}`
  7533. }`
  7534. ),
  7535. uploadProjectCoverImage: async (
  7536. projectId: number,
  7537. file: File
  7538. ): Promise<{ status: string; filename: string; size: number }> => {
  7539. const formData = new FormData();
  7540. formData.append('file', file);
  7541. const headers: Record<string, string> = {};
  7542. if (authToken) {
  7543. headers['Authorization'] = `Bearer ${authToken}`;
  7544. }
  7545. const response = await fetch(`${API_BASE}/projects/${projectId}/cover-image`, {
  7546. method: 'POST',
  7547. headers,
  7548. body: formData,
  7549. });
  7550. if (!response.ok) {
  7551. const error = await response.json().catch(() => ({}));
  7552. throw new Error(error.detail || `HTTP ${response.status}`);
  7553. }
  7554. return response.json();
  7555. },
  7556. deleteProjectCoverImage: (projectId: number) =>
  7557. request<{ status: string }>(`/projects/${projectId}/cover-image`, { method: 'DELETE' }),
  7558. // BOM (Bill of Materials)
  7559. getProjectBOM: (projectId: number) =>
  7560. request<BOMItem[]>(`/projects/${projectId}/bom`),
  7561. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  7562. request<BOMItem>(`/projects/${projectId}/bom`, {
  7563. method: 'POST',
  7564. body: JSON.stringify(data),
  7565. }),
  7566. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  7567. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  7568. method: 'PATCH',
  7569. body: JSON.stringify(data),
  7570. }),
  7571. deleteBOMItem: (projectId: number, itemId: number) =>
  7572. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  7573. method: 'DELETE',
  7574. }),
  7575. // Templates
  7576. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  7577. createTemplateFromProject: (projectId: number) =>
  7578. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  7579. createProjectFromTemplate: (templateId: number, name?: string) =>
  7580. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  7581. method: 'POST',
  7582. }),
  7583. // Timeline
  7584. getProjectTimeline: (projectId: number, limit = 50) =>
  7585. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  7586. // Project Export/Import
  7587. exportProjectJson: (projectId: number) =>
  7588. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  7589. importProject: (data: ProjectImport) =>
  7590. request<Project>('/projects/import', {
  7591. method: 'POST',
  7592. body: JSON.stringify(data),
  7593. }),
  7594. importProjectFile: async (file: File): Promise<Project> => {
  7595. const formData = new FormData();
  7596. formData.append('file', file);
  7597. const headers: Record<string, string> = {};
  7598. if (authToken) {
  7599. headers['Authorization'] = `Bearer ${authToken}`;
  7600. }
  7601. const response = await fetch(`${API_BASE}/projects/import/file`, {
  7602. method: 'POST',
  7603. headers,
  7604. body: formData,
  7605. });
  7606. if (!response.ok) {
  7607. const error = await response.json().catch(() => ({}));
  7608. throw new Error(error.detail || `HTTP ${response.status}`);
  7609. }
  7610. return response.json();
  7611. },
  7612. exportProjectZip: async (projectId: number): Promise<{ blob: Blob; filename: string }> => {
  7613. const headers: Record<string, string> = {};
  7614. if (authToken) {
  7615. headers['Authorization'] = `Bearer ${authToken}`;
  7616. }
  7617. const response = await fetch(`${API_BASE}/projects/${projectId}/export`, {
  7618. headers,
  7619. });
  7620. if (!response.ok) {
  7621. const error = await response.json().catch(() => ({}));
  7622. throw new Error(error.detail || `HTTP ${response.status}`);
  7623. }
  7624. const contentDisposition = response.headers.get('Content-Disposition');
  7625. const filename = parseContentDispositionFilename(contentDisposition) || `project_${projectId}.zip`;
  7626. const blob = await response.blob();
  7627. return { blob, filename };
  7628. },
  7629. // API Keys
  7630. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  7631. createAPIKey: (data: APIKeyCreate) =>
  7632. request<APIKeyCreateResponse>('/api-keys/', {
  7633. method: 'POST',
  7634. body: JSON.stringify(data),
  7635. }),
  7636. deleteAPIKey: (id: number) =>
  7637. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  7638. // AMS History
  7639. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  7640. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  7641. // Printer heater (nozzle / bed / chamber) sensor history
  7642. getPrinterSensorHistory: (printerId: number, hours = 24, kinds?: string[]) => {
  7643. const params = new URLSearchParams({ hours: String(hours) });
  7644. if (kinds && kinds.length > 0) params.set('kinds', kinds.join(','));
  7645. return request<PrinterSensorHistoryResponse>(`/printer-sensor-history/${printerId}?${params.toString()}`);
  7646. },
  7647. // System Info
  7648. getSystemInfo: () => request<SystemInfo>('/system/info'),
  7649. getSystemHealth: () => request<SystemHealthResult>('/system/health'),
  7650. getStorageUsage: (options?: { refresh?: boolean }) => {
  7651. const params = new URLSearchParams();
  7652. if (options?.refresh) {
  7653. params.set('refresh', 'true');
  7654. }
  7655. const query = params.toString();
  7656. return request<StorageUsageResponse>(`/system/storage-usage${query ? `?${query}` : ''}`);
  7657. },
  7658. // Library (File Manager)
  7659. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  7660. createLibraryFolder: (data: LibraryFolderCreate) =>
  7661. request<LibraryFolder>('/library/folders', {
  7662. method: 'POST',
  7663. body: JSON.stringify(data),
  7664. }),
  7665. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  7666. request<LibraryFolder>(`/library/folders/${id}`, {
  7667. method: 'PUT',
  7668. body: JSON.stringify(data),
  7669. }),
  7670. deleteLibraryFolder: (id: number) =>
  7671. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  7672. createExternalFolder: (data: ExternalFolderCreate) =>
  7673. request<LibraryFolder>('/library/folders/external', {
  7674. method: 'POST',
  7675. body: JSON.stringify(data),
  7676. }),
  7677. scanExternalFolder: (folderId: number) =>
  7678. request<{ status: string; added: number; removed: number }>(`/library/folders/${folderId}/scan`, {
  7679. method: 'POST',
  7680. }),
  7681. getLibraryFoldersByProject: (projectId: number) =>
  7682. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  7683. getLibraryFoldersByArchive: (archiveId: number) => foldersByArchiveBatch(archiveId),
  7684. getLibraryFiles: (
  7685. folderId?: number | null,
  7686. includeRoot = true,
  7687. projectId?: number,
  7688. scope?: 'internal' | 'external',
  7689. recursive = false,
  7690. tagIds: number[] = [],
  7691. ) => {
  7692. const params = new URLSearchParams();
  7693. if (folderId !== undefined && folderId !== null) {
  7694. params.set('folder_id', String(folderId));
  7695. }
  7696. if (projectId !== undefined) {
  7697. params.set('project_id', String(projectId));
  7698. }
  7699. params.set('include_root', String(includeRoot));
  7700. if (scope === 'internal') params.set('internal_only', 'true');
  7701. else if (scope === 'external') params.set('external_only', 'true');
  7702. // recursive=true expands the folder_id filter to include every descendant
  7703. // folder (#1268). Only meaningful when folder_id is set; ignored server-side
  7704. // otherwise. Off by default so non-search callers keep folder-scoped behavior.
  7705. if (recursive) params.set('recursive', 'true');
  7706. // Tag filter (#1268). Repeated ?tag_ids=N&tag_ids=M form for AND semantics
  7707. // — backend joins the association table and HAVING COUNT(DISTINCT) matches
  7708. // the array length. Tag filter intentionally bypasses folder scoping
  7709. // server-side (cross-cutting design decision).
  7710. for (const tagId of tagIds) {
  7711. params.append('tag_ids', String(tagId));
  7712. }
  7713. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  7714. },
  7715. getLibraryFolderReadme: (folderId: number) =>
  7716. request<{ filename: string; content: string; truncated: boolean }>(
  7717. `/library/folders/${folderId}/readme`,
  7718. ),
  7719. // ============ Library tag catalog (#1268) ============
  7720. getLibraryTags: () =>
  7721. request<LibraryTag[]>('/library/tags'),
  7722. createLibraryTag: (name: string) =>
  7723. request<LibraryTag>('/library/tags', {
  7724. method: 'POST',
  7725. body: JSON.stringify({ name }),
  7726. }),
  7727. updateLibraryTag: (id: number, name: string) =>
  7728. request<LibraryTag>(`/library/tags/${id}`, {
  7729. method: 'PATCH',
  7730. body: JSON.stringify({ name }),
  7731. }),
  7732. deleteLibraryTag: (id: number) =>
  7733. request<void>(`/library/tags/${id}`, { method: 'DELETE' }),
  7734. bulkAssignLibraryTags: (
  7735. fileIds: number[],
  7736. tagIds: number[],
  7737. action: 'add' | 'remove' | 'replace',
  7738. ) =>
  7739. request<LibraryTagBulkAssignResult>('/library/tags/bulk-assign', {
  7740. method: 'POST',
  7741. body: JSON.stringify({ file_ids: fileIds, tag_ids: tagIds, action }),
  7742. }),
  7743. // ============ Variant groups (#671 / #2570) ============
  7744. // "These files are the same job sliced for different printers." Consumed from
  7745. // both ends: the queue picks a printer and needs the matching file, the File
  7746. // Manager's print action has the printer and needs the same match.
  7747. createVariantGroup: (
  7748. members: { library_file_id: number; target_model?: string }[],
  7749. name?: string,
  7750. ) =>
  7751. request<VariantGroup>('/library/variant-groups', {
  7752. method: 'POST',
  7753. body: JSON.stringify({ members, ...(name ? { name } : {}) }),
  7754. }),
  7755. getVariantGroup: (groupId: number) =>
  7756. request<VariantGroup>(`/library/variant-groups/${groupId}`),
  7757. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  7758. uploadLibraryFile: async (
  7759. file: File,
  7760. folderId?: number | null,
  7761. generateStlThumbnails: boolean = true
  7762. ): Promise<LibraryFileUploadResponse> => {
  7763. const formData = new FormData();
  7764. formData.append('file', file);
  7765. const params = new URLSearchParams();
  7766. if (folderId) params.set('folder_id', String(folderId));
  7767. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7768. const headers: Record<string, string> = {};
  7769. if (authToken) {
  7770. headers['Authorization'] = `Bearer ${authToken}`;
  7771. }
  7772. const response = await fetch(`${API_BASE}/library/files?${params}`, {
  7773. method: 'POST',
  7774. headers,
  7775. body: formData,
  7776. });
  7777. if (!response.ok) {
  7778. const error = await response.json().catch(() => ({}));
  7779. throw new Error(error.detail || `HTTP ${response.status}`);
  7780. }
  7781. return response.json();
  7782. },
  7783. extractZipFile: async (
  7784. file: File,
  7785. folderId?: number | null,
  7786. preserveStructure: boolean = true,
  7787. createFolderFromZip: boolean = false,
  7788. generateStlThumbnails: boolean = true
  7789. ): Promise<ZipExtractResponse> => {
  7790. const formData = new FormData();
  7791. formData.append('file', file);
  7792. const params = new URLSearchParams();
  7793. if (folderId) params.set('folder_id', String(folderId));
  7794. params.set('preserve_structure', String(preserveStructure));
  7795. params.set('create_folder_from_zip', String(createFolderFromZip));
  7796. params.set('generate_stl_thumbnails', String(generateStlThumbnails));
  7797. const headers: Record<string, string> = {};
  7798. if (authToken) {
  7799. headers['Authorization'] = `Bearer ${authToken}`;
  7800. }
  7801. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  7802. method: 'POST',
  7803. headers,
  7804. body: formData,
  7805. });
  7806. if (!response.ok) {
  7807. const error = await response.json().catch(() => ({}));
  7808. throw new Error(error.detail || `HTTP ${response.status}`);
  7809. }
  7810. return response.json();
  7811. },
  7812. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  7813. request<LibraryFile>(`/library/files/${id}`, {
  7814. method: 'PUT',
  7815. body: JSON.stringify(data),
  7816. }),
  7817. deleteLibraryFile: (id: number) =>
  7818. request<{ status: string; message: string; trashed: boolean }>(`/library/files/${id}`, { method: 'DELETE' }),
  7819. // ========== Library Trash (#1008) ==========
  7820. previewLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7821. request<LibraryPurgePreview>(
  7822. `/library/purge/preview?older_than_days=${olderThanDays}&include_never_printed=${includeNeverPrinted}`,
  7823. ),
  7824. executeLibraryPurge: (olderThanDays: number, includeNeverPrinted: boolean = true) =>
  7825. request<{ moved_to_trash: number }>('/library/purge', {
  7826. method: 'POST',
  7827. body: JSON.stringify({ older_than_days: olderThanDays, include_never_printed: includeNeverPrinted }),
  7828. }),
  7829. listLibraryTrash: (limit: number = 100, offset: number = 0) =>
  7830. request<LibraryTrashListResponse>(`/library/trash?limit=${limit}&offset=${offset}`),
  7831. restoreLibraryTrash: (fileId: number) =>
  7832. request<{ status: string; id: number }>(`/library/trash/${fileId}/restore`, { method: 'POST' }),
  7833. hardDeleteLibraryTrash: (fileId: number) =>
  7834. request<{ status: string }>(`/library/trash/${fileId}`, { method: 'DELETE' }),
  7835. emptyLibraryTrash: () => request<{ deleted: number }>('/library/trash', { method: 'DELETE' }),
  7836. getLibraryTrashSettings: () =>
  7837. request<LibraryTrashSettings>('/library/trash/settings'),
  7838. updateLibraryTrashSettings: (body: LibraryTrashSettings) =>
  7839. request<LibraryTrashSettings>('/library/trash/settings', {
  7840. method: 'PUT',
  7841. body: JSON.stringify(body),
  7842. }),
  7843. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  7844. createLibrarySlicerToken: (fileId: number) =>
  7845. request<{ token: string }>(`/library/files/${fileId}/slicer-token`, { method: 'POST' }),
  7846. getLibrarySlicerDownloadUrl: (fileId: number, token: string, filename: string) =>
  7847. `${API_BASE}/library/files/${fileId}/dl/${token}/${encodeURIComponent(buildSlicerUrlFilename(filename))}`,
  7848. downloadLibraryFile: async (id: number, filename?: string): Promise<void> => {
  7849. const headers: Record<string, string> = {};
  7850. if (authToken) {
  7851. headers['Authorization'] = `Bearer ${authToken}`;
  7852. }
  7853. const response = await fetch(`${API_BASE}/library/files/${id}/download`, { headers });
  7854. if (!response.ok) {
  7855. const error = await response.json().catch(() => ({}));
  7856. throw new Error(error.detail || `HTTP ${response.status}`);
  7857. }
  7858. const disposition = response.headers.get('Content-Disposition');
  7859. const downloadFilename = parseContentDispositionFilename(disposition) || filename || `file_${id}`;
  7860. const blob = await response.blob();
  7861. const url = window.URL.createObjectURL(blob);
  7862. const a = document.createElement('a');
  7863. a.href = url;
  7864. a.download = downloadFilename;
  7865. document.body.appendChild(a);
  7866. a.click();
  7867. document.body.removeChild(a);
  7868. window.URL.revokeObjectURL(url);
  7869. },
  7870. getLibraryFileThumbnailUrl: (id: number) => withMediaToken(`${API_BASE}/library/files/${id}/thumbnail`),
  7871. // Client-rendered preview thumbnail upload (#2976). STEP/PDF/spreadsheet
  7872. // previews render in the browser; the first render is posted back so the
  7873. // grid gets a thumbnail without a server-side renderer for those formats.
  7874. uploadLibraryPreviewThumbnail: async (fileId: number, thumbnail: Blob): Promise<{ updated: boolean }> => {
  7875. const formData = new FormData();
  7876. formData.append('thumbnail', thumbnail, 'preview.png');
  7877. const headers: Record<string, string> = {};
  7878. if (authToken) {
  7879. headers['Authorization'] = `Bearer ${authToken}`;
  7880. }
  7881. const response = await fetch(`${API_BASE}/library/files/${fileId}/preview-thumbnail`, {
  7882. method: 'POST',
  7883. headers,
  7884. body: formData,
  7885. });
  7886. if (!response.ok) {
  7887. const error = await response.json().catch(() => ({}));
  7888. throw new Error(error.detail || `HTTP ${response.status}`);
  7889. }
  7890. return response.json();
  7891. },
  7892. getLibraryFilePlateThumbnail: (id: number, plateIndex: number) =>
  7893. withMediaToken(`${API_BASE}/library/files/${id}/plate-thumbnail/${plateIndex}`),
  7894. // Photos of the printed result (#3077) — same shape as the archive photo API.
  7895. getLibraryFilePhotoUrl: (fileId: number, filename: string) =>
  7896. withMediaToken(`${API_BASE}/library/files/${fileId}/photos/${encodeURIComponent(filename)}`),
  7897. uploadLibraryFilePhoto: async (fileId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  7898. const formData = new FormData();
  7899. formData.append('file', file);
  7900. const headers: Record<string, string> = {};
  7901. if (authToken) {
  7902. headers['Authorization'] = `Bearer ${authToken}`;
  7903. }
  7904. const response = await fetch(`${API_BASE}/library/files/${fileId}/photos`, {
  7905. method: 'POST',
  7906. headers,
  7907. body: formData,
  7908. });
  7909. if (!response.ok) {
  7910. const error = await response.json().catch(() => ({}));
  7911. throw new Error(error.detail || `HTTP ${response.status}`);
  7912. }
  7913. return response.json();
  7914. },
  7915. deleteLibraryFilePhoto: (fileId: number, filename: string) =>
  7916. request<{ status: string; photos: string[] }>(`/library/files/${fileId}/photos/${encodeURIComponent(filename)}`, {
  7917. method: 'DELETE',
  7918. }),
  7919. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  7920. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  7921. request<{ status: string; moved: number }>('/library/files/move', {
  7922. method: 'POST',
  7923. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  7924. }),
  7925. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  7926. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  7927. method: 'POST',
  7928. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  7929. }),
  7930. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  7931. batchGenerateStlThumbnails: (options: {
  7932. file_ids?: number[];
  7933. folder_id?: number;
  7934. all_missing?: boolean;
  7935. }) =>
  7936. request<BatchThumbnailResponse>('/library/generate-stl-thumbnails', {
  7937. method: 'POST',
  7938. body: JSON.stringify(options),
  7939. }),
  7940. combineLibraryFiles: (items: { file_id: number; copies: number }[], filename: string, folderId: number | null) =>
  7941. request<LibraryFileUploadResponse>('/library/files/combine', {
  7942. method: 'POST',
  7943. body: JSON.stringify({ items, filename, folder_id: folderId }),
  7944. }),
  7945. getLibraryFilePlates: (fileId: number) =>
  7946. request<LibraryFilePlatesResponse>(`/library/files/${fileId}/plates`),
  7947. getLibraryFileFilamentRequirements: (
  7948. fileId: number,
  7949. plateId?: number,
  7950. requestId?: string,
  7951. /** Ask for one entry per project slot instead of only the slots this
  7952. * plate consumes. The slice modal needs it: its filament list is
  7953. * positional, so a source whose only used slot is 4 must still present
  7954. * four rows or the user's pick is bound to slot 1 (#2712). Print-time
  7955. * AMS matching must NOT set this — it wants the used-only list. */
  7956. fullSlots?: boolean,
  7957. ) => {
  7958. const qs = new URLSearchParams();
  7959. if (plateId !== undefined) qs.set('plate_id', String(plateId));
  7960. if (requestId) qs.set('request_id', requestId);
  7961. if (fullSlots) qs.set('full_slots', 'true');
  7962. return request<{
  7963. file_id: number;
  7964. filename: string;
  7965. filaments: Array<{
  7966. slot_id: number;
  7967. type: string;
  7968. color: string;
  7969. used_grams: number;
  7970. used_meters: number;
  7971. used_in_plate?: boolean;
  7972. }>;
  7973. }>(`/library/files/${fileId}/filament-requirements${qs.toString() ? `?${qs}` : ''}`);
  7974. },
  7975. /** Poll the sidecar's per-request progress snapshot via the Bambuddy
  7976. * proxy. Used by the SliceModal's filament-discovery path so the inline
  7977. * spinner + persistent toast can show "Generating G-code (45%)" while
  7978. * the preview slice runs. Returns null on 404 (sidecar doesn't yet
  7979. * have an entry — early race window — or it expired) so the poller
  7980. * can keep trying. */
  7981. getPreviewSliceProgress: async (requestId: string): Promise<SliceJobProgress | null> => {
  7982. try {
  7983. return await request<SliceJobProgress>(`/slicer/preview-progress/${encodeURIComponent(requestId)}`);
  7984. } catch {
  7985. return null;
  7986. }
  7987. },
  7988. // GitHub Backup
  7989. getGitHubBackupConfig: () =>
  7990. request<GitHubBackupConfig | null>('/github-backup/config'),
  7991. getGitHubBackupCloudAccounts: () =>
  7992. request<CloudAccountCounts>('/github-backup/cloud-accounts'),
  7993. saveGitHubBackupConfig: (config: GitHubBackupConfigCreate) =>
  7994. request<GitHubBackupConfig>('/github-backup/config', {
  7995. method: 'POST',
  7996. body: JSON.stringify(config),
  7997. }),
  7998. updateGitHubBackupConfig: (config: Partial<GitHubBackupConfigCreate>) =>
  7999. request<GitHubBackupConfig>('/github-backup/config', {
  8000. method: 'PATCH',
  8001. body: JSON.stringify(config),
  8002. }),
  8003. testGitHubConnection: (repoUrl: string, token: string, provider: GitProviderType = 'github') =>
  8004. request<GitHubTestConnectionResponse>('/github-backup/test', {
  8005. method: 'POST',
  8006. body: JSON.stringify({ repo_url: repoUrl, token, provider }),
  8007. }),
  8008. testGitHubStoredConnection: () =>
  8009. request<GitHubTestConnectionResponse>('/github-backup/test-stored', { method: 'POST' }),
  8010. triggerGitHubBackup: () =>
  8011. request<GitHubBackupTriggerResponse>('/github-backup/run', { method: 'POST' }),
  8012. getGitHubBackupStatus: () =>
  8013. request<GitHubBackupStatus>('/github-backup/status'),
  8014. getGitHubBackupLogs: (limit: number = 50) =>
  8015. request<GitHubBackupLog[]>(`/github-backup/logs?limit=${limit}`),
  8016. clearGitHubBackupLogs: (keepLast: number = 10) =>
  8017. request<{ deleted: number; message: string }>(`/github-backup/logs?keep_last=${keepLast}`, { method: 'DELETE' }),
  8018. // Restore from a Git backup (#2656)
  8019. getGitHubBackupCommits: (limit: number = 20) =>
  8020. request<GitHubCommitListResponse>(`/github-backup/commits?limit=${limit}`),
  8021. getGitHubRestorePreview: (ref: string = 'HEAD') =>
  8022. request<GitHubRestorePreview>(`/github-backup/restore/preview?ref=${encodeURIComponent(ref)}`),
  8023. restoreFromGitHub: (payload: GitHubRestoreRequest) =>
  8024. request<GitHubRestoreResponse>('/github-backup/restore', {
  8025. method: 'POST',
  8026. body: JSON.stringify(payload),
  8027. }),
  8028. // Scheduled local backups
  8029. getLocalBackupStatus: () =>
  8030. request<LocalBackupStatus>('/local-backup/status'),
  8031. triggerLocalBackup: () =>
  8032. request<{ success: boolean; message: string; filename?: string }>('/local-backup/run', { method: 'POST' }),
  8033. checkLocalBackupPath: () =>
  8034. request<LocalBackupPathCheck>('/local-backup/path-check'),
  8035. getLocalBackups: () =>
  8036. request<LocalBackupFile[]>('/local-backup/backups'),
  8037. downloadLocalBackup: async (filename: string): Promise<{ blob: Blob; filename: string }> => {
  8038. const response = await fetch(`${API_BASE}/local-backup/backups/${encodeURIComponent(filename)}/download`, {
  8039. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8040. });
  8041. if (!response.ok) throw new Error('Download failed');
  8042. const blob = await response.blob();
  8043. return { blob, filename };
  8044. },
  8045. restoreLocalBackup: (filename: string) =>
  8046. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}/restore`, { method: 'POST' }),
  8047. deleteLocalBackup: (filename: string) =>
  8048. request<{ success: boolean; message: string }>(`/local-backup/backups/${encodeURIComponent(filename)}`, { method: 'DELETE' }),
  8049. // Obico AI failure detection
  8050. getObicoStatus: () =>
  8051. request<ObicoStatus>('/obico/status'),
  8052. getObicoPrinterStatus: () =>
  8053. request<ObicoPrinterStatus>('/obico/printer-status'),
  8054. // `token` is sent as-is, so an empty string tests with no token at all.
  8055. // Omitting the argument makes the backend fall back to the saved token.
  8056. testObicoConnection: (url: string, token?: string) =>
  8057. request<ObicoTestConnection>('/obico/test-connection', {
  8058. method: 'POST',
  8059. body: JSON.stringify(token === undefined ? { url } : { url, token }),
  8060. }),
  8061. // OctoEverywhere AI failure detection
  8062. getOctoEverywhereStatus: () =>
  8063. request<OctoEverywhereStatus>('/octoeverywhere/status'),
  8064. getOctoEverywherePrinterStatus: () =>
  8065. request<OctoEverywherePrinterStatus>('/octoeverywhere/printer-status'),
  8066. // An omitted key uses the saved key; an explicit empty key is rejected.
  8067. testOctoEverywhereConnection: (apiKey?: string, confidence?: OctoEverywhereConfidence) =>
  8068. request<OctoEverywhereTestConnection>('/octoeverywhere/test-connection', {
  8069. method: 'POST',
  8070. body: JSON.stringify({ api_key: apiKey, confidence }),
  8071. }),
  8072. // Slicer API — slice in the background. Both endpoints return 202 + a
  8073. // job_id; poll /slice-jobs/{id} until status is `completed` or `failed`.
  8074. sliceLibraryFile: (fileId: number, body: SliceRequest) =>
  8075. request<SliceJobEnqueueResponse>(`/library/files/${fileId}/slice`, {
  8076. method: 'POST',
  8077. body: JSON.stringify(body),
  8078. }),
  8079. sliceArchive: (archiveId: number, body: SliceRequest) =>
  8080. request<SliceJobEnqueueResponse>(`/archives/${archiveId}/slice`, {
  8081. method: 'POST',
  8082. body: JSON.stringify(body),
  8083. }),
  8084. getSliceJob: (jobId: number) =>
  8085. request<SliceJobState>(`/slice-jobs/${jobId}`),
  8086. // Unified slicer-preset listing — cloud + local + standard, deduped by name.
  8087. // Used by the SliceModal; see UnifiedPresetsResponse for the shape and
  8088. // backend/app/api/routes/slicer_presets.py for the priority rules.
  8089. // `refresh` bypasses the in-process cloud and bundled-preset caches on the
  8090. // backend; the SliceModal's Refresh button passes true so a preset deleted
  8091. // in Bambu Studio or Bambu Handy shows up without the 5-min TTL wait.
  8092. getSlicerPresets: (options?: { refresh?: boolean }) =>
  8093. request<UnifiedPresetsResponse>(
  8094. options?.refresh ? '/slicer/presets?refresh=true' : '/slicer/presets',
  8095. ),
  8096. // Slicer Pipelines (#1425) — preset bundles the SliceModal can apply in
  8097. // one click. CRUD is gated on PIPELINES_READ / PIPELINES_WRITE.
  8098. listSlicerPipelines: () =>
  8099. request<SlicerPipelinesListResponse>('/slicer-pipelines/'),
  8100. createSlicerPipeline: (data: SlicerPipelineCreateRequest) =>
  8101. request<SlicerPipeline>('/slicer-pipelines/', {
  8102. method: 'POST',
  8103. body: JSON.stringify(data),
  8104. }),
  8105. updateSlicerPipeline: (id: number, data: SlicerPipelineUpdateRequest) =>
  8106. request<SlicerPipeline>(`/slicer-pipelines/${id}`, {
  8107. method: 'PUT',
  8108. body: JSON.stringify(data),
  8109. }),
  8110. deleteSlicerPipeline: (id: number) =>
  8111. request<void>(`/slicer-pipelines/${id}`, { method: 'DELETE' }),
  8112. checkPipelineEligibility: (
  8113. pipelineId: number,
  8114. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8115. ) =>
  8116. request<PipelineEligibilityReport>(`/slicer-pipelines/${pipelineId}/check-eligibility`, {
  8117. method: 'POST',
  8118. body: JSON.stringify(
  8119. source.kind === 'libraryFile'
  8120. ? { source_library_file_id: source.id }
  8121. : { source_archive_id: source.id },
  8122. ),
  8123. }),
  8124. runPipeline: (
  8125. pipelineId: number,
  8126. source: { kind: 'libraryFile'; id: number } | { kind: 'archive'; id: number },
  8127. force = false,
  8128. copies = 1,
  8129. ) =>
  8130. request<PipelineRun>(`/slicer-pipelines/${pipelineId}/run`, {
  8131. method: 'POST',
  8132. body: JSON.stringify({
  8133. ...(source.kind === 'libraryFile'
  8134. ? { source_library_file_id: source.id }
  8135. : { source_archive_id: source.id }),
  8136. force,
  8137. copies,
  8138. }),
  8139. }),
  8140. listPipelineRuns: (pipelineId: number, limit = 5) =>
  8141. request<PipelineRunListResponse>(
  8142. `/slicer-pipelines/${pipelineId}/runs?limit=${limit}`,
  8143. ),
  8144. // Dashboard list across all pipelines (#1425 PR C).
  8145. listAllPipelineRuns: (params: {
  8146. limit?: number;
  8147. offset?: number;
  8148. pipelineId?: number;
  8149. status?: string;
  8150. targetPrinterId?: number;
  8151. targetModelClass?: string;
  8152. } = {}) => {
  8153. const search = new URLSearchParams();
  8154. if (params.limit) search.set('limit', String(params.limit));
  8155. if (params.offset) search.set('offset', String(params.offset));
  8156. if (params.pipelineId) search.set('pipeline_id', String(params.pipelineId));
  8157. if (params.status) search.set('status', params.status);
  8158. if (params.targetPrinterId) search.set('target_printer_id', String(params.targetPrinterId));
  8159. if (params.targetModelClass) search.set('target_model_class', params.targetModelClass);
  8160. const q = search.toString();
  8161. return request<PipelineRunListResponse>(
  8162. `/pipeline-runs${q ? '?' + q : ''}`,
  8163. );
  8164. },
  8165. // Clear terminal pipeline runs (#1425 PR C polish). Deletes all runs in
  8166. // a terminal state (completed/failed/cancelled/partial_failure); in-flight
  8167. // runs are preserved.
  8168. clearTerminalPipelineRuns: () =>
  8169. request<{ deleted: number }>('/pipeline-runs/clear', { method: 'POST' }),
  8170. cancelPipelineRun: (runId: number) =>
  8171. request<PipelineRun>(`/pipeline-runs/${runId}/cancel`, { method: 'POST' }),
  8172. retryFailedPipelineRun: (runId: number) =>
  8173. request<PipelineRun>(`/pipeline-runs/${runId}/retry-failed`, { method: 'POST' }),
  8174. // Canonical Bambu printer-model registry — "Bambu Lab <model>" → short code.
  8175. // Single source of truth shared with backend (PRINTER_MODEL_MAP); the
  8176. // SliceModal uses this to classify cloud / standard presets by their
  8177. // `@BBL <code>` suffix against the selected printer-preset name (#1325).
  8178. getSlicerPrinterModels: () =>
  8179. request<Record<string, string>>('/slicer/printer-models'),
  8180. getSlicerLoadedSpools: () =>
  8181. request<LoadedSpoolsResponse>('/slicer/loaded-spools'),
  8182. /**
  8183. * Effective values of a process preset, with its `inherits:` chain flattened
  8184. * by the slicer sidecar. Powers the slice modal's settings panel, which would
  8185. * otherwise show the option schema's compiled-in defaults (a preset setting a
  8186. * 0.42mm line width appears as the C++ default of 0).
  8187. *
  8188. * `resolved: false` means the values could not be obtained -- sidecar offline,
  8189. * too old for the endpoint, or slicing not configured -- and the caller should
  8190. * fall back to schema defaults rather than treat it as a failure.
  8191. */
  8192. getSlicerPresetValues: (ref: PresetRef) =>
  8193. request<SlicerPresetValues>(
  8194. `/slicer/preset-values?source=${encodeURIComponent(ref.source)}&id=${encodeURIComponent(ref.id)}`,
  8195. ),
  8196. // Local Presets (OrcaSlicer imports)
  8197. getLocalPresets: () =>
  8198. request<LocalPresetsResponse>('/local-presets/'),
  8199. importLocalPresets: (formData: FormData) =>
  8200. fetch(`${API_BASE}/local-presets/import`, {
  8201. method: 'POST',
  8202. headers: authToken ? { 'Authorization': `Bearer ${authToken}` } : {},
  8203. body: formData,
  8204. }).then(async (res) => {
  8205. if (!res.ok) {
  8206. const err = await res.json().catch(() => ({}));
  8207. throw new Error(err.detail || `HTTP ${res.status}`);
  8208. }
  8209. return res.json() as Promise<ImportResponse>;
  8210. }),
  8211. deleteLocalPreset: (id: number) =>
  8212. request<{ success: boolean }>(`/local-presets/${id}`, { method: 'DELETE' }),
  8213. };
  8214. // AMS History types
  8215. export interface AMSHistoryPoint {
  8216. recorded_at: string;
  8217. humidity: number | null;
  8218. humidity_raw: number | null;
  8219. temperature: number | null;
  8220. }
  8221. export interface AMSHistoryResponse {
  8222. printer_id: number;
  8223. ams_id: number;
  8224. data: AMSHistoryPoint[];
  8225. min_humidity: number | null;
  8226. max_humidity: number | null;
  8227. avg_humidity: number | null;
  8228. min_temperature: number | null;
  8229. max_temperature: number | null;
  8230. avg_temperature: number | null;
  8231. }
  8232. export type HeaterSensorKind = 'nozzle' | 'nozzle_2' | 'bed' | 'chamber';
  8233. export interface HeaterHistoryPoint {
  8234. recorded_at: string;
  8235. value: number | null;
  8236. target: number | null;
  8237. }
  8238. export interface HeaterSeries {
  8239. sensor_kind: HeaterSensorKind;
  8240. data: HeaterHistoryPoint[];
  8241. min_value: number | null;
  8242. max_value: number | null;
  8243. avg_value: number | null;
  8244. }
  8245. export interface PrinterSensorHistoryResponse {
  8246. printer_id: number;
  8247. series: HeaterSeries[];
  8248. }
  8249. // System Info types
  8250. export interface SystemInfo {
  8251. app: {
  8252. version: string;
  8253. base_dir: string;
  8254. archive_dir: string;
  8255. };
  8256. database: {
  8257. engine: string;
  8258. version: string;
  8259. archives: number;
  8260. archives_completed: number;
  8261. archives_failed: number;
  8262. archives_printing: number;
  8263. printers: number;
  8264. filaments: number;
  8265. projects: number;
  8266. smart_plugs: number;
  8267. total_print_time_seconds: number;
  8268. total_print_time_formatted: string;
  8269. total_filament_grams: number;
  8270. total_filament_kg: number;
  8271. };
  8272. printers: {
  8273. total: number;
  8274. connected: number;
  8275. connected_list: Array<{
  8276. id: number;
  8277. name: string;
  8278. state: string;
  8279. model: string;
  8280. }>;
  8281. };
  8282. storage: {
  8283. archive_size_bytes: number;
  8284. archive_size_formatted: string;
  8285. database_size_bytes: number;
  8286. database_size_formatted: string;
  8287. disk_total_bytes: number;
  8288. disk_total_formatted: string;
  8289. disk_used_bytes: number;
  8290. disk_used_formatted: string;
  8291. disk_free_bytes: number;
  8292. disk_free_formatted: string;
  8293. disk_percent_used: number;
  8294. };
  8295. system: {
  8296. platform: string;
  8297. platform_release: string;
  8298. platform_version: string;
  8299. architecture: string;
  8300. hostname: string;
  8301. python_version: string;
  8302. uptime_seconds: number;
  8303. uptime_formatted: string;
  8304. boot_time: string;
  8305. };
  8306. memory: {
  8307. total_bytes: number;
  8308. total_formatted: string;
  8309. available_bytes: number;
  8310. available_formatted: string;
  8311. used_bytes: number;
  8312. used_formatted: string;
  8313. percent_used: number;
  8314. };
  8315. cpu: {
  8316. count: number;
  8317. count_logical: number;
  8318. percent: number;
  8319. };
  8320. }
  8321. export interface StorageUsageCategory {
  8322. key: string;
  8323. label: string;
  8324. bytes: number;
  8325. formatted: string;
  8326. percent_of_total: number;
  8327. }
  8328. export interface StorageUsageOtherItem {
  8329. bucket: string;
  8330. label: string;
  8331. kind: 'system' | 'data';
  8332. deletable: boolean;
  8333. bytes: number;
  8334. formatted: string;
  8335. percent_of_total: number;
  8336. }
  8337. export interface StorageUsageResponse {
  8338. roots: string[];
  8339. total_bytes: number;
  8340. total_formatted: string;
  8341. categories: StorageUsageCategory[];
  8342. other_breakdown: StorageUsageOtherItem[];
  8343. scan_errors: number;
  8344. generated_at: string;
  8345. cache: {
  8346. hit: boolean;
  8347. age_seconds: number;
  8348. max_age_seconds: number;
  8349. };
  8350. }
  8351. // Library (File Manager) types
  8352. export interface LibraryFolderTree {
  8353. id: number;
  8354. name: string;
  8355. parent_id: number | null;
  8356. project_id: number | null;
  8357. archive_id: number | null;
  8358. project_name: string | null;
  8359. archive_name: string | null;
  8360. is_external: boolean;
  8361. external_path: string | null;
  8362. external_readonly: boolean;
  8363. file_count: number;
  8364. // max(folder.updated_at, max(immediate-child file.updated_at)). Used by
  8365. // the File Manager folder tree's "sort by recent activity" mode (#1770).
  8366. latest_activity_at: string | null;
  8367. // Ownership (#3201). can_* are for the current user: what the File
  8368. // Manager may offer on this folder. The backend enforces the same rules.
  8369. created_by_id: number | null;
  8370. shared: boolean;
  8371. can_write: boolean;
  8372. can_rename: boolean;
  8373. can_delete: boolean;
  8374. children: LibraryFolderTree[];
  8375. }
  8376. export interface LibraryFolder {
  8377. id: number;
  8378. name: string;
  8379. parent_id: number | null;
  8380. project_id: number | null;
  8381. archive_id: number | null;
  8382. project_name: string | null;
  8383. archive_name: string | null;
  8384. is_external: boolean;
  8385. external_path: string | null;
  8386. external_readonly: boolean;
  8387. external_show_hidden: boolean;
  8388. file_count: number;
  8389. latest_activity_at: string | null;
  8390. // Ownership (#3201). can_* are for the current user: what the File
  8391. // Manager may offer on this folder. The backend enforces the same rules.
  8392. created_by_id: number | null;
  8393. shared: boolean;
  8394. can_write: boolean;
  8395. can_rename: boolean;
  8396. can_delete: boolean;
  8397. created_at: string;
  8398. updated_at: string;
  8399. }
  8400. export interface LibraryFolderCreate {
  8401. name: string;
  8402. parent_id?: number | null;
  8403. project_id?: number | null;
  8404. archive_id?: number | null;
  8405. }
  8406. export interface ExternalFolderCreate {
  8407. name: string;
  8408. external_path: string;
  8409. readonly?: boolean;
  8410. show_hidden?: boolean;
  8411. parent_id?: number | null;
  8412. }
  8413. export interface LibraryFolderUpdate {
  8414. name?: string;
  8415. parent_id?: number | null;
  8416. project_id?: number | null; // 0 to unlink
  8417. archive_id?: number | null; // 0 to unlink
  8418. shared?: boolean; // library:update_all only (#3201)
  8419. }
  8420. export interface LibraryFileDuplicate {
  8421. id: number;
  8422. filename: string;
  8423. folder_id: number | null;
  8424. folder_name: string | null;
  8425. created_at: string;
  8426. }
  8427. export interface LibraryFile {
  8428. id: number;
  8429. folder_id: number | null;
  8430. folder_name: string | null;
  8431. project_id: number | null;
  8432. project_name: string | null;
  8433. is_external: boolean;
  8434. filename: string;
  8435. file_path: string;
  8436. file_type: string;
  8437. file_size: number;
  8438. file_hash: string | null;
  8439. thumbnail_path: string | null;
  8440. metadata: Record<string, unknown> | null;
  8441. print_count: number;
  8442. last_printed_at: string | null;
  8443. notes: string | null;
  8444. // User link + photos of the printed result (#3077); source_url is the
  8445. // read-only import provenance (MakerWorld).
  8446. external_url: string | null;
  8447. photos: string[];
  8448. source_url: string | null;
  8449. duplicates: LibraryFileDuplicate[] | null;
  8450. duplicate_count: number;
  8451. // User tracking (Issue #206)
  8452. created_by_id: number | null;
  8453. created_by_username: string | null;
  8454. created_at: string;
  8455. updated_at: string;
  8456. // Metadata fields
  8457. print_name: string | null;
  8458. print_time_seconds: number | null;
  8459. filament_used_grams: number | null;
  8460. sliced_for_model: string | null;
  8461. }
  8462. export interface LibraryTagSummary {
  8463. id: number;
  8464. name: string;
  8465. }
  8466. export interface LibraryFileListItem {
  8467. id: number;
  8468. folder_id: number | null;
  8469. is_external: boolean;
  8470. filename: string;
  8471. file_type: string;
  8472. file_size: number;
  8473. thumbnail_path: string | null;
  8474. print_count: number;
  8475. duplicate_count: number;
  8476. // User tracking (Issue #206)
  8477. created_by_id: number | null;
  8478. created_by_username: string | null;
  8479. created_at: string;
  8480. // Real on-disk modification time (#2680). Null for managed uploads; the date
  8481. // sort and "Modified" column use `fs_modified_at ?? created_at`.
  8482. fs_modified_at: string | null;
  8483. print_name: string | null;
  8484. print_time_seconds: number | null;
  8485. filament_used_grams: number | null;
  8486. sliced_for_model: string | null;
  8487. // Tags assigned to this file (#1268). The backend always emits an empty
  8488. // array when a file has no tags, but the field is typed optional so any
  8489. // legacy code path (or mock) that constructs a LibraryFileListItem without
  8490. // it doesn't crash the renderer. Read sites use `file.tags ?? []`.
  8491. tags?: LibraryTagSummary[];
  8492. // Variant grouping (#671 / #2570). `variant_count` is the size of the whole
  8493. // group, which may include files in other folders — never the number of
  8494. // matching rows on screen. 0 when the file is not grouped.
  8495. variant_group_id?: number | null;
  8496. variant_count?: number;
  8497. // Metadata indicators (#3077). Optional for the same reason as `tags`: older
  8498. // mocks construct list items without them. Read sites default to falsy.
  8499. external_url?: string | null;
  8500. has_notes?: boolean;
  8501. photo_count?: number;
  8502. }
  8503. // Variant groups (#671 / #2570): the same job sliced for different printers.
  8504. export interface VariantGroupMember {
  8505. library_file_id: number;
  8506. filename: string;
  8507. target_model: string;
  8508. position: number;
  8509. }
  8510. export interface VariantGroup {
  8511. id: number;
  8512. name: string;
  8513. /** In priority order — index 0 wins when several printers are free at once. */
  8514. members: VariantGroupMember[];
  8515. }
  8516. // Library tag catalog (#1268)
  8517. export interface LibraryTag {
  8518. id: number;
  8519. name: string;
  8520. file_count: number;
  8521. created_at: string;
  8522. updated_at: string;
  8523. }
  8524. export interface LibraryTagBulkAssignResult {
  8525. files_updated: number;
  8526. associations_added: number;
  8527. associations_removed: number;
  8528. }
  8529. export interface LibraryFileUpdate {
  8530. filename?: string;
  8531. folder_id?: number | null;
  8532. project_id?: number | null;
  8533. notes?: string | null;
  8534. external_url?: string | null;
  8535. }
  8536. // Library trash (#1008)
  8537. export interface LibraryTrashItem {
  8538. id: number;
  8539. filename: string;
  8540. file_size: number;
  8541. thumbnail_path: string | null;
  8542. folder_id: number | null;
  8543. folder_name: string | null;
  8544. created_by_id: number | null;
  8545. created_by_username: string | null;
  8546. deleted_at: string;
  8547. auto_purge_at: string;
  8548. }
  8549. export interface LibraryTrashListResponse {
  8550. items: LibraryTrashItem[];
  8551. total: number;
  8552. retention_days: number;
  8553. }
  8554. export interface LibraryPurgePreview {
  8555. count: number;
  8556. total_bytes: number;
  8557. sample_filenames: string[];
  8558. older_than_days: number;
  8559. include_never_printed: boolean;
  8560. }
  8561. export interface LibraryTrashSettings {
  8562. retention_days: number;
  8563. auto_purge_enabled: boolean;
  8564. auto_purge_days: number;
  8565. auto_purge_include_never_printed: boolean;
  8566. }
  8567. export interface ArchivePurgePreview {
  8568. count: number;
  8569. total_bytes: number;
  8570. sample_filenames: string[];
  8571. older_than_days: number;
  8572. }
  8573. export interface ArchiveMergeMember {
  8574. id: number;
  8575. print_name: string | null;
  8576. filename: string;
  8577. created_at: string | null;
  8578. run_count: number;
  8579. }
  8580. /** Why a group is left out: at work now, or holding files only one can keep. */
  8581. export type ArchiveMergeSkip = 'busy' | 'conflicting_files' | 'failed' | 'not_a_group';
  8582. export interface ArchiveMergeGroup {
  8583. survivor: ArchiveMergeMember;
  8584. merged: ArchiveMergeMember[];
  8585. skipped: ArchiveMergeSkip | null;
  8586. }
  8587. export interface ArchiveMergePreview {
  8588. groups: ArchiveMergeGroup[];
  8589. }
  8590. export interface ArchiveMergeResult {
  8591. merged: { survivor_id: number; merged_ids: number[] }[];
  8592. skipped: { survivor_id: number; reason: ArchiveMergeSkip }[];
  8593. }
  8594. export interface ArchivePurgeSettings {
  8595. enabled: boolean;
  8596. days: number;
  8597. // #1390: when true, bulk-deletes the linked PrintLogEntry rows so the
  8598. // contribution drops from Quick Stats too. Default false — soft-delete,
  8599. // Quick Stats preserved.
  8600. purge_stats: boolean;
  8601. }
  8602. export interface LibraryFileUploadResponse {
  8603. id: number;
  8604. filename: string;
  8605. file_type: string;
  8606. file_size: number;
  8607. thumbnail_path: string | null;
  8608. duplicate_of: number | null;
  8609. metadata: Record<string, unknown> | null;
  8610. }
  8611. export interface LibraryStats {
  8612. total_files: number;
  8613. total_folders: number;
  8614. total_size_bytes: number;
  8615. files_by_type: Record<string, number>;
  8616. total_prints: number;
  8617. disk_free_bytes: number;
  8618. disk_total_bytes: number;
  8619. disk_used_bytes: number;
  8620. }
  8621. export interface ZipExtractResult {
  8622. filename: string;
  8623. file_id: number;
  8624. folder_id: number | null;
  8625. }
  8626. export interface ZipExtractError {
  8627. filename: string;
  8628. error: string;
  8629. }
  8630. export interface ZipExtractResponse {
  8631. extracted: number;
  8632. folders_created: number;
  8633. files: ZipExtractResult[];
  8634. errors: ZipExtractError[];
  8635. }
  8636. // STL Thumbnail Generation types
  8637. export interface BatchThumbnailResult {
  8638. file_id: number;
  8639. filename: string;
  8640. success: boolean;
  8641. error?: string | null;
  8642. }
  8643. export interface BatchThumbnailResponse {
  8644. processed: number;
  8645. succeeded: number;
  8646. failed: number;
  8647. results: BatchThumbnailResult[];
  8648. }
  8649. // Discovery types
  8650. export interface DiscoveredPrinter {
  8651. serial: string;
  8652. name: string;
  8653. ip_address: string;
  8654. model: string | null;
  8655. discovered_at: string | null;
  8656. }
  8657. export interface DiscoveryStatus {
  8658. running: boolean;
  8659. }
  8660. export interface DiscoveryInfo {
  8661. is_docker: boolean;
  8662. ssdp_running: boolean;
  8663. scan_running: boolean;
  8664. subnets: string[];
  8665. }
  8666. export interface SubnetScanStatus {
  8667. running: boolean;
  8668. scanned: number;
  8669. total: number;
  8670. }
  8671. // Discovery API
  8672. export const discoveryApi = {
  8673. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  8674. startDiscovery: (duration: number = 10) =>
  8675. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  8676. stopDiscovery: () =>
  8677. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  8678. getDiscoveredPrinters: () =>
  8679. request<DiscoveredPrinter[]>('/discovery/printers'),
  8680. // Subnet scanning (for Docker environments)
  8681. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  8682. request<SubnetScanStatus>('/discovery/scan', {
  8683. method: 'POST',
  8684. body: JSON.stringify({ subnet, timeout }),
  8685. }),
  8686. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  8687. stopSubnetScan: () =>
  8688. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  8689. };
  8690. // Virtual Printer types
  8691. // Canonical wire values: `archive`, `review`, `queue`, `proxy`. The legacy
  8692. // `immediate` (→ archive) and `print_queue` (→ queue) names are still
  8693. // accepted by the backend so older API clients keep working, but new code
  8694. // should send the canonical names.
  8695. // 'archive' and 'immediate' are older names of 'library', 'print_queue' of 'queue'.
  8696. export type VirtualPrinterMode = 'library' | 'review' | 'queue' | 'proxy' | 'archive' | 'immediate' | 'print_queue';
  8697. export interface VirtualPrinterProxyStatus {
  8698. running: boolean;
  8699. target_host: string;
  8700. ftp_port: number;
  8701. mqtt_port: number;
  8702. ftp_connections: number;
  8703. mqtt_connections: number;
  8704. }
  8705. export interface VirtualPrinterStatus {
  8706. enabled: boolean;
  8707. running: boolean;
  8708. mode: VirtualPrinterMode;
  8709. name: string;
  8710. serial: string;
  8711. model: string;
  8712. model_name: string;
  8713. pending_files: number;
  8714. target_printer_ip?: string; // For proxy mode
  8715. proxy?: VirtualPrinterProxyStatus; // For proxy mode
  8716. }
  8717. export interface VirtualPrinterSettings {
  8718. tailscale_disabled: boolean;
  8719. archive_name_source: 'metadata' | 'filename'; // Source for archive's display name
  8720. status: VirtualPrinterStatus;
  8721. }
  8722. export interface NetworkInterface {
  8723. name: string;
  8724. ip: string;
  8725. netmask: string;
  8726. subnet: string;
  8727. is_alias?: boolean;
  8728. label?: string;
  8729. }
  8730. export interface PendingUpload {
  8731. id: number;
  8732. filename: string;
  8733. // Resolved name the review card should show — mirrors what archive_print
  8734. // will eventually write to PrintArchive.print_name (#1152 follow-up). Falls
  8735. // back to the stripped filename stem when the 3MF has no embedded title or
  8736. // the operator has chosen the "filename" archive-name source.
  8737. display_name: string;
  8738. file_size: number;
  8739. source_ip: string | null;
  8740. status: string;
  8741. tags: string | null;
  8742. notes: string | null;
  8743. project_id: number | null;
  8744. uploaded_at: string;
  8745. }
  8746. // Virtual Printer API
  8747. export const virtualPrinterApi = {
  8748. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  8749. updateSettings: (data: {
  8750. tailscale_disabled?: boolean;
  8751. archive_name_source?: 'metadata' | 'filename';
  8752. }) => {
  8753. const params = new URLSearchParams();
  8754. if (data.tailscale_disabled !== undefined) params.set('tailscale_disabled', String(data.tailscale_disabled));
  8755. if (data.archive_name_source !== undefined) params.set('archive_name_source', data.archive_name_source);
  8756. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  8757. method: 'PUT',
  8758. });
  8759. },
  8760. };
  8761. // Multi Virtual Printer API
  8762. export interface VirtualPrinterConfig {
  8763. id: number;
  8764. name: string;
  8765. enabled: boolean;
  8766. mode: VirtualPrinterMode;
  8767. model: string | null;
  8768. model_name: string | null;
  8769. access_code_set: boolean;
  8770. serial: string;
  8771. target_printer_id: number | null;
  8772. // File Manager folder uploads land in; null = the shared "Virtual Printer" folder.
  8773. library_folder_id: number | null;
  8774. // Queue mode: remove the file from the File Manager once its print starts.
  8775. queue_remove_after_print: boolean;
  8776. auto_dispatch: boolean;
  8777. queue_force_color_match: boolean;
  8778. save_ams_mapping: boolean;
  8779. gcode_injection: boolean;
  8780. tailscale_disabled: boolean;
  8781. bind_ip: string | null;
  8782. remote_interface_ip: string | null;
  8783. position: number;
  8784. status: { running: boolean; pending_files: number; proxy?: VirtualPrinterProxyStatus };
  8785. }
  8786. export interface VirtualPrinterListResponse {
  8787. printers: VirtualPrinterConfig[];
  8788. models: Record<string, string>;
  8789. // Serial family (first 3 characters) per model code: tells apart codes of one name (H2C: O1C 094, O1C2 31B).
  8790. model_serial_prefixes?: Record<string, string>;
  8791. }
  8792. export const multiVirtualPrinterApi = {
  8793. list: () => request<VirtualPrinterListResponse>('/virtual-printers'),
  8794. get: (id: number) => request<VirtualPrinterConfig>(`/virtual-printers/${id}`),
  8795. create: (data: {
  8796. name?: string;
  8797. enabled?: boolean;
  8798. mode?: string;
  8799. model?: string;
  8800. access_code?: string;
  8801. target_printer_id?: number;
  8802. auto_dispatch?: boolean;
  8803. queue_force_color_match?: boolean;
  8804. save_ams_mapping?: boolean;
  8805. gcode_injection?: boolean;
  8806. bind_ip?: string;
  8807. remote_interface_ip?: string;
  8808. }) =>
  8809. request<VirtualPrinterConfig>('/virtual-printers', {
  8810. method: 'POST',
  8811. body: JSON.stringify(data),
  8812. }),
  8813. update: (id: number, data: {
  8814. name?: string;
  8815. enabled?: boolean;
  8816. mode?: string;
  8817. model?: string;
  8818. access_code?: string;
  8819. // null clears the target (a queue VP then sends to any printer of its model).
  8820. target_printer_id?: number | null;
  8821. // null: back to the shared "Virtual Printer" folder.
  8822. library_folder_id?: number | null;
  8823. queue_remove_after_print?: boolean;
  8824. auto_dispatch?: boolean;
  8825. queue_force_color_match?: boolean;
  8826. save_ams_mapping?: boolean;
  8827. gcode_injection?: boolean;
  8828. tailscale_disabled?: boolean;
  8829. bind_ip?: string;
  8830. remote_interface_ip?: string;
  8831. }) =>
  8832. request<VirtualPrinterConfig>(`/virtual-printers/${id}`, {
  8833. method: 'PUT',
  8834. body: JSON.stringify(data),
  8835. }),
  8836. remove: (id: number) =>
  8837. request<{ detail: string; id: number }>(`/virtual-printers/${id}`, {
  8838. method: 'DELETE',
  8839. }),
  8840. getTailscaleStatus: () =>
  8841. request<TailscaleStatusResponse>('/virtual-printers/tailscale-status'),
  8842. getCaCertificate: () =>
  8843. request<VPCaCertificate>('/virtual-printers/ca-certificate'),
  8844. // A script that adds the CA to Bambu Studio and OrcaSlicer, with the CA
  8845. // written into it: 'windows' (.cmd) or 'unix' (.sh, Linux and macOS).
  8846. // The signed-in user's personal access code (#1430); renewing replaces it.
  8847. getMyAccessCode: () => request<{ code: string }>('/virtual-printers/my-access-code'),
  8848. renewMyAccessCode: () => request<{ code: string }>('/virtual-printers/my-access-code', { method: 'POST' }),
  8849. getCaCertificateInstaller: (platform: 'windows' | 'unix') =>
  8850. request<{ filename: string; content: string }>(`/virtual-printers/ca-certificate/installer/${platform}`),
  8851. diagnose: (id: number) =>
  8852. request<VPDiagnosticResult>(`/virtual-printers/${id}/diagnostic`),
  8853. };
  8854. /** The shared CA certificate every virtual printer presents — imported once
  8855. * into the slicer's trust store. Only the public certificate is returned. */
  8856. export interface VPCaCertificate {
  8857. pem: string;
  8858. fingerprint_sha256: string;
  8859. not_valid_after: string;
  8860. }
  8861. export type VPDiagnosticStatus = 'pass' | 'fail' | 'warn' | 'skip';
  8862. export interface VPDiagnosticCheck {
  8863. id:
  8864. | 'enabled'
  8865. | 'running'
  8866. | 'bind_interface'
  8867. | 'access_code'
  8868. | 'target_printer'
  8869. | 'port_ftps'
  8870. | 'port_mqtt'
  8871. | 'port_bind'
  8872. | 'certificate';
  8873. status: VPDiagnosticStatus;
  8874. params: Record<string, string | number>;
  8875. }
  8876. export interface VPDiagnosticResult {
  8877. vp_id: number;
  8878. vp_name: string;
  8879. mode: string;
  8880. overall: 'ok' | 'warnings' | 'problems';
  8881. checks: VPDiagnosticCheck[];
  8882. }
  8883. export interface TailscaleStatusResponse {
  8884. available: boolean;
  8885. fqdn: string;
  8886. hostname: string;
  8887. tailnet_name: string;
  8888. tailscale_ips: string[];
  8889. error: string | null;
  8890. }
  8891. // Pending Uploads API
  8892. export const pendingUploadsApi = {
  8893. list: () => request<PendingUpload[]>('/pending-uploads/'),
  8894. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  8895. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  8896. // Approve: the file goes to its virtual printer's File Manager folder.
  8897. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  8898. request<{ id: number; filename: string; folder_id: number | null }>(`/pending-uploads/${id}/archive`, {
  8899. method: 'POST',
  8900. body: JSON.stringify(data || {}),
  8901. }),
  8902. discard: (id: number) =>
  8903. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  8904. archiveAll: () =>
  8905. request<{ stored: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  8906. discardAll: () =>
  8907. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  8908. };
  8909. // Firmware API Types
  8910. export interface AvailableFirmwareVersion {
  8911. version: string;
  8912. file_available: boolean;
  8913. download_url: string | null;
  8914. release_notes: string | null;
  8915. release_time: string | null;
  8916. }
  8917. export interface FirmwareUpdateInfo {
  8918. printer_id: number;
  8919. printer_name: string;
  8920. model: string | null;
  8921. current_version: string | null;
  8922. latest_version: string | null;
  8923. update_available: boolean;
  8924. download_url: string | null;
  8925. release_notes: string | null;
  8926. available_versions: AvailableFirmwareVersion[];
  8927. }
  8928. export interface FirmwareUploadPrepare {
  8929. can_proceed: boolean;
  8930. sd_card_present: boolean;
  8931. sd_card_free_space: number;
  8932. firmware_size: number;
  8933. space_sufficient: boolean;
  8934. update_available: boolean;
  8935. current_version: string | null;
  8936. latest_version: string | null;
  8937. target_version: string | null;
  8938. firmware_filename: string | null;
  8939. errors: string[];
  8940. }
  8941. export interface FirmwareUploadStatus {
  8942. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  8943. progress: number;
  8944. message: string;
  8945. error: string | null;
  8946. firmware_filename: string | null;
  8947. firmware_version: string | null;
  8948. }
  8949. // Firmware API
  8950. export const firmwareApi = {
  8951. checkUpdates: () =>
  8952. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  8953. checkPrinterUpdate: (printerId: number) => firmwareUpdateBatch(printerId),
  8954. prepareUpload: (printerId: number, version?: string) =>
  8955. request<FirmwareUploadPrepare>(
  8956. `/firmware/updates/${printerId}/prepare${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8957. ),
  8958. startUpload: (printerId: number, version?: string) =>
  8959. request<{ started: boolean; message: string }>(
  8960. `/firmware/updates/${printerId}/upload${version ? `?version=${encodeURIComponent(version)}` : ''}`,
  8961. { method: 'POST' },
  8962. ),
  8963. getUploadStatus: (printerId: number) =>
  8964. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  8965. };
  8966. // Support types
  8967. export interface DebugLoggingState {
  8968. enabled: boolean;
  8969. enabled_at: string | null;
  8970. duration_seconds: number | null;
  8971. }
  8972. export interface LogEntry {
  8973. timestamp: string;
  8974. level: string;
  8975. logger_name: string;
  8976. message: string;
  8977. }
  8978. export interface LogsResponse {
  8979. entries: LogEntry[];
  8980. total_in_file: number;
  8981. filtered_count: number;
  8982. }
  8983. // Support API
  8984. export const supportApi = {
  8985. getDebugLoggingState: () =>
  8986. request<DebugLoggingState>('/support/debug-logging'),
  8987. setDebugLogging: (enabled: boolean) =>
  8988. request<DebugLoggingState>('/support/debug-logging', {
  8989. method: 'POST',
  8990. body: JSON.stringify({ enabled }),
  8991. }),
  8992. downloadSupportBundle: async () => {
  8993. const headers: Record<string, string> = {};
  8994. if (authToken) {
  8995. headers['Authorization'] = `Bearer ${authToken}`;
  8996. }
  8997. const response = await fetch(`${API_BASE}/support/bundle`, { headers });
  8998. if (!response.ok) {
  8999. const error = await response.json().catch(() => ({}));
  9000. throw new Error(error.detail || `HTTP ${response.status}`);
  9001. }
  9002. // Get filename from Content-Disposition header or use default
  9003. const disposition = response.headers.get('Content-Disposition');
  9004. const filename = parseContentDispositionFilename(disposition) || 'bambuddy-support.zip';
  9005. // Download the blob
  9006. const blob = await response.blob();
  9007. const url = window.URL.createObjectURL(blob);
  9008. const a = document.createElement('a');
  9009. a.href = url;
  9010. a.download = filename;
  9011. document.body.appendChild(a);
  9012. a.click();
  9013. document.body.removeChild(a);
  9014. window.URL.revokeObjectURL(url);
  9015. },
  9016. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  9017. const searchParams = new URLSearchParams();
  9018. if (params?.limit) searchParams.set('limit', params.limit.toString());
  9019. if (params?.level) searchParams.set('level', params.level);
  9020. if (params?.search) searchParams.set('search', params.search);
  9021. const query = searchParams.toString();
  9022. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  9023. },
  9024. clearLogs: () =>
  9025. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  9026. };
  9027. // SpoolBuddy types
  9028. export interface SpoolBuddyDevice {
  9029. id: number;
  9030. device_id: string;
  9031. hostname: string;
  9032. ip_address: string;
  9033. backend_url?: string | null;
  9034. firmware_version: string | null;
  9035. has_nfc: boolean;
  9036. has_scale: boolean;
  9037. tare_offset: number;
  9038. calibration_factor: number;
  9039. nfc_reader_type: string | null;
  9040. nfc_connection: string | null;
  9041. display_brightness: number;
  9042. display_blank_timeout: number;
  9043. has_backlight: boolean;
  9044. last_calibrated_at: string | null;
  9045. last_seen: string | null;
  9046. pending_command: string | null;
  9047. nfc_ok: boolean;
  9048. scale_ok: boolean;
  9049. uptime_s: number;
  9050. update_status: string | null;
  9051. update_message: string | null;
  9052. system_stats: {
  9053. os?: { os?: string; kernel?: string; arch?: string; python?: string };
  9054. cpu_temp_c?: number;
  9055. cpu_count?: number;
  9056. load_avg?: number[];
  9057. memory?: { total_mb?: number; available_mb?: number; used_mb?: number; percent?: number };
  9058. disk?: { total_gb?: number; used_gb?: number; free_gb?: number; percent?: number };
  9059. system_uptime_s?: number;
  9060. } | null;
  9061. online: boolean;
  9062. }
  9063. export interface DaemonUpdateCheck {
  9064. current_version: string;
  9065. latest_version: string | null;
  9066. update_available: boolean;
  9067. }
  9068. // SpoolBuddy API
  9069. export const spoolbuddyApi = {
  9070. getDevices: () =>
  9071. request<SpoolBuddyDevice[]>('/spoolbuddy/devices'),
  9072. deleteDevice: (deviceId: string) =>
  9073. request<{ status: string; device_id: string }>(`/spoolbuddy/devices/${deviceId}`, {
  9074. method: 'DELETE',
  9075. }),
  9076. tare: (deviceId: string) =>
  9077. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/calibration/tare`, {
  9078. method: 'POST',
  9079. body: '{}',
  9080. }),
  9081. setCalibrationFactor: (deviceId: string, knownWeightGrams: number, rawAdc: number, tareRawAdc?: number) =>
  9082. request<{ tare_offset: number; calibration_factor: number }>(`/spoolbuddy/devices/${deviceId}/calibration/set-factor`, {
  9083. method: 'POST',
  9084. body: JSON.stringify({ known_weight_grams: knownWeightGrams, raw_adc: rawAdc, tare_raw_adc: tareRawAdc }),
  9085. }),
  9086. updateSpoolWeight: (spoolId: number, weightGrams: number) =>
  9087. request<{ status: string; weight_used: number }>('/spoolbuddy/scale/update-spool-weight', {
  9088. method: 'POST',
  9089. body: JSON.stringify({ spool_id: spoolId, weight_grams: weightGrams }),
  9090. }),
  9091. updateDisplay: (deviceId: string, brightness: number, blankTimeout: number) =>
  9092. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/display`, {
  9093. method: 'PUT',
  9094. body: JSON.stringify({ brightness, blank_timeout: blankTimeout }),
  9095. }),
  9096. updateSystemConfig: (deviceId: string, backendUrl: string, apiKey?: string) =>
  9097. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/system/config`, {
  9098. method: 'POST',
  9099. body: JSON.stringify({ backend_url: backendUrl, ...(apiKey ? { api_key: apiKey } : {}) }),
  9100. }),
  9101. checkDaemonUpdate: (deviceId: string) =>
  9102. request<DaemonUpdateCheck>(`/spoolbuddy/devices/${deviceId}/update-check`),
  9103. triggerUpdate: (deviceId: string) =>
  9104. request<{ status: string; message: string }>(`/spoolbuddy/devices/${deviceId}/update`, {
  9105. method: 'POST',
  9106. body: '{}',
  9107. }),
  9108. getSSHPublicKey: () =>
  9109. request<{ public_key: string }>('/spoolbuddy/ssh/public-key'),
  9110. writeTag: (deviceId: string, spoolId: number) =>
  9111. request<{ status: string; warnings?: string[] }>('/spoolbuddy/nfc/write-tag', {
  9112. method: 'POST',
  9113. body: JSON.stringify({ device_id: deviceId, spool_id: spoolId }),
  9114. }),
  9115. cancelWrite: (deviceId: string) =>
  9116. request<{ status: string }>(`/spoolbuddy/devices/${deviceId}/cancel-write`, {
  9117. method: 'POST',
  9118. body: '{}',
  9119. }),
  9120. systemCommand: (deviceId: string, command: 'reboot' | 'shutdown' | 'restart_daemon' | 'restart_browser') =>
  9121. request<{ status: string; command: string }>(`/spoolbuddy/devices/${deviceId}/system/command`, {
  9122. method: 'POST',
  9123. body: JSON.stringify({ command }),
  9124. }),
  9125. queueDiagnostics: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9126. request<{ status: string; diagnostic: string; message: string }>(
  9127. `/spoolbuddy/diagnostics/${deviceId}/run?diagnostic=${type}`,
  9128. { method: 'POST', body: '{}' }
  9129. ),
  9130. getDiagnosticResult: (deviceId: string, type: 'nfc' | 'scale' | 'read_tag') =>
  9131. request<{ diagnostic: string; success: boolean; output: string; exit_code: number }>(
  9132. `/spoolbuddy/diagnostics/${deviceId}/result?diagnostic=${type}`,
  9133. { method: 'GET' }
  9134. ),
  9135. };
  9136. export interface BugReportRequest {
  9137. description: string;
  9138. email?: string;
  9139. screenshot_base64?: string;
  9140. include_support_info?: boolean;
  9141. debug_logs?: string;
  9142. }
  9143. export interface BugReportResponse {
  9144. success: boolean;
  9145. message: string;
  9146. issue_url?: string;
  9147. issue_number?: number;
  9148. }
  9149. export const bugReportApi = {
  9150. submit: (data: BugReportRequest) =>
  9151. request<BugReportResponse>('/bug-report/submit', {
  9152. method: 'POST',
  9153. body: JSON.stringify(data),
  9154. }),
  9155. startLogging: () =>
  9156. request<{ started: boolean; was_debug: boolean }>('/bug-report/start-logging', {
  9157. method: 'POST',
  9158. }),
  9159. stopLogging: (wasDebug: boolean) =>
  9160. request<{ logs: string }>(`/bug-report/stop-logging?was_debug=${wasDebug}`, {
  9161. method: 'POST',
  9162. }),
  9163. };
  9164. export type AnnouncementLevel = 'info' | 'important' | 'critical';
  9165. export interface AnnouncementText {
  9166. title: string;
  9167. body: string;
  9168. link_label?: string;
  9169. }
  9170. // One message from the Bambuddy maintainers. `texts` holds every language the
  9171. // message was written in; English is always there.
  9172. export interface Announcement {
  9173. id: string;
  9174. level: AnnouncementLevel;
  9175. texts: Record<string, AnnouncementText>;
  9176. link_url: string | null;
  9177. published_at: string | null;
  9178. expires_at: string | null;
  9179. // Past its expiry: kept as history, listed under "Earlier", never unread.
  9180. archived: boolean;
  9181. read: boolean;
  9182. }
  9183. // `visible` says whether this user may see announcements at all (switched on,
  9184. // and admin or "show to all users"); it keeps the sidebar entry while nothing
  9185. // is published.
  9186. export interface AnnouncementList {
  9187. visible: boolean;
  9188. announcements: Announcement[];
  9189. }
  9190. export const announcementsApi = {
  9191. list: () => request<AnnouncementList>('/announcements'),
  9192. markRead: (id: string) =>
  9193. request<void>(`/announcements/${encodeURIComponent(id)}/read`, { method: 'POST' }),
  9194. };
  9195. export interface SponsorPromptCheckResponse {
  9196. show: boolean;
  9197. milestone?: string;
  9198. family?: 'prints' | 'cost' | 'archives' | 'anniversary' | 'version-update';
  9199. threshold?: number;
  9200. payload?: Record<string, unknown>;
  9201. }
  9202. export const sponsorPromptApi = {
  9203. check: () => request<SponsorPromptCheckResponse>('/sponsor-prompt/check'),
  9204. dismiss: (milestone: string) =>
  9205. request<void>('/sponsor-prompt/dismiss', {
  9206. method: 'POST',
  9207. body: JSON.stringify({ milestone }),
  9208. }),
  9209. };