client.ts 238 KB

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