mirror of
https://github.com/mealie-recipes/mealie.git
synced 2025-12-17 15:55:13 -05:00
feat: add group statistics on profile page
* resolve file not found error and add constants * add group stats and storage functionality * generate new types * add statistics and storage cap graphs * fix: add loadFood query param #1103 * refactor to flex view
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
megabyte = 1_048_576
|
||||
gigabyte = 1_073_741_824
|
||||
|
||||
|
||||
def pretty_size(size: int) -> str:
|
||||
"""
|
||||
@@ -23,7 +26,11 @@ def get_dir_size(path: Path | str) -> int:
|
||||
"""
|
||||
Get the size of a directory
|
||||
"""
|
||||
total_size = os.path.getsize(path)
|
||||
try:
|
||||
total_size = os.path.getsize(path)
|
||||
except FileNotFoundError:
|
||||
return 0
|
||||
|
||||
for item in os.listdir(path):
|
||||
itempath = os.path.join(path, item)
|
||||
if os.path.isfile(itempath):
|
||||
|
||||
@@ -1,32 +1,31 @@
|
||||
from typing import Union
|
||||
|
||||
from sqlalchemy.orm.session import Session
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.db.models.group import Group
|
||||
from mealie.schema.meal_plan.meal import MealPlanOut
|
||||
from mealie.db.models.recipe.category import Category
|
||||
from mealie.db.models.recipe.recipe import RecipeModel
|
||||
from mealie.db.models.recipe.tag import Tag
|
||||
from mealie.db.models.recipe.tool import Tool
|
||||
from mealie.db.models.users.users import User
|
||||
from mealie.schema.group.group_statistics import GroupStatistics
|
||||
from mealie.schema.user.user import GroupInDB
|
||||
|
||||
from .repository_generic import RepositoryGeneric
|
||||
|
||||
|
||||
class RepositoryGroup(RepositoryGeneric[GroupInDB, Group]):
|
||||
def get_meals(self, session: Session, match_value: str, match_key: str = "name") -> list[MealPlanOut]:
|
||||
"""A Helper function to get the group from the database and return a sorted list of
|
||||
|
||||
Args:
|
||||
session (Session): SqlAlchemy Session
|
||||
match_value (str): Match Value
|
||||
match_key (str, optional): Match Key. Defaults to "name".
|
||||
|
||||
Returns:
|
||||
list[MealPlanOut]: [description]
|
||||
"""
|
||||
group: GroupInDB = session.query(self.sql_model).filter_by(**{match_key: match_value}).one_or_none()
|
||||
|
||||
return group.mealplans
|
||||
|
||||
def get_by_name(self, name: str, limit=1) -> Union[GroupInDB, Group, None]:
|
||||
dbgroup = self.session.query(self.sql_model).filter_by(**{"name": name}).one_or_none()
|
||||
if dbgroup is None:
|
||||
return None
|
||||
return self.schema.from_orm(dbgroup)
|
||||
|
||||
def statistics(self, group_id: UUID4) -> GroupStatistics:
|
||||
return GroupStatistics(
|
||||
total_recipes=self.session.query(RecipeModel).filter_by(group_id=group_id).count(),
|
||||
total_users=self.session.query(User).filter_by(group_id=group_id).count(),
|
||||
total_categories=self.session.query(Category).filter_by(group_id=group_id).count(),
|
||||
total_tags=self.session.query(Tag).filter_by(group_id=group_id).count(),
|
||||
total_tools=self.session.query(Tool).filter_by(group_id=group_id).count(),
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ from random import randint
|
||||
from typing import Any, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import UUID4
|
||||
from slugify import slugify
|
||||
from sqlalchemy import and_, func
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
@@ -163,7 +164,7 @@ class RepositoryRecipes(RepositoryGeneric[Recipe, RecipeModel]):
|
||||
.limit(limit)
|
||||
]
|
||||
|
||||
def get_by_slug(self, group_id: UUID, slug: str, limit=1) -> Optional[Recipe]:
|
||||
def get_by_slug(self, group_id: UUID4, slug: str, limit=1) -> Optional[Recipe]:
|
||||
dbrecipe = (
|
||||
self.session.query(RecipeModel)
|
||||
.filter(RecipeModel.group_id == group_id, RecipeModel.slug == slug)
|
||||
@@ -172,3 +173,6 @@ class RepositoryRecipes(RepositoryGeneric[Recipe, RecipeModel]):
|
||||
if dbrecipe is None:
|
||||
return None
|
||||
return self.schema.from_orm(dbrecipe)
|
||||
|
||||
def all_ids(self, group_id: UUID4) -> list[UUID4]:
|
||||
return [tpl[0] for tpl in self.session.query(RecipeModel.id).filter(RecipeModel.group_id == group_id).all()]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from functools import cached_property
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from mealie.routes._base.abc_controller import BaseUserController
|
||||
@@ -5,13 +7,29 @@ from mealie.routes._base.controller import controller
|
||||
from mealie.routes._base.routers import UserAPIRouter
|
||||
from mealie.schema.group.group_permissions import SetPermissions
|
||||
from mealie.schema.group.group_preferences import ReadGroupPreferences, UpdateGroupPreferences
|
||||
from mealie.schema.group.group_statistics import GroupStatistics, GroupStorage
|
||||
from mealie.schema.user.user import GroupInDB, UserOut
|
||||
from mealie.services.group_services.group_service import GroupService
|
||||
|
||||
router = UserAPIRouter(prefix="/groups", tags=["Groups: Self Service"])
|
||||
|
||||
|
||||
@controller(router)
|
||||
class GroupSelfServiceController(BaseUserController):
|
||||
@cached_property
|
||||
def service(self) -> GroupService:
|
||||
return GroupService(self.group_id, self.repos)
|
||||
|
||||
@router.get("/self", response_model=GroupInDB)
|
||||
def get_logged_in_user_group(self):
|
||||
"""Returns the Group Data for the Current User"""
|
||||
return self.group
|
||||
|
||||
@router.get("/members", response_model=list[UserOut])
|
||||
def get_group_members(self):
|
||||
"""Returns the Group of user lists"""
|
||||
return self.repos.users.multi_query(query_by={"group_id": self.group.id}, override_schema=UserOut)
|
||||
|
||||
@router.get("/preferences", response_model=ReadGroupPreferences)
|
||||
def get_group_preferences(self):
|
||||
return self.group.preferences
|
||||
@@ -20,18 +38,8 @@ class GroupSelfServiceController(BaseUserController):
|
||||
def update_group_preferences(self, new_pref: UpdateGroupPreferences):
|
||||
return self.repos.group_preferences.update(self.group_id, new_pref)
|
||||
|
||||
@router.get("/self", response_model=GroupInDB)
|
||||
async def get_logged_in_user_group(self):
|
||||
"""Returns the Group Data for the Current User"""
|
||||
return self.group
|
||||
|
||||
@router.get("/members", response_model=list[UserOut])
|
||||
async def get_group_members(self):
|
||||
"""Returns the Group of user lists"""
|
||||
return self.repos.users.multi_query(query_by={"group_id": self.group.id}, override_schema=UserOut)
|
||||
|
||||
@router.put("/permissions", response_model=UserOut)
|
||||
async def set_member_permissions(self, permissions: SetPermissions):
|
||||
def set_member_permissions(self, permissions: SetPermissions):
|
||||
self.checks.can_manage()
|
||||
|
||||
target_user = self.repos.users.get(permissions.user_id)
|
||||
@@ -47,3 +55,11 @@ class GroupSelfServiceController(BaseUserController):
|
||||
target_user.can_organize = permissions.can_organize
|
||||
|
||||
return self.repos.users.update(permissions.user_id, target_user)
|
||||
|
||||
@router.get("/statistics", response_model=GroupStatistics)
|
||||
def get_statistics(self):
|
||||
return self.service.calculate_statistics()
|
||||
|
||||
@router.get("/storage", response_model=GroupStorage)
|
||||
def get_storage(self):
|
||||
return self.service.calculate_group_storage()
|
||||
|
||||
@@ -6,5 +6,6 @@ from .group_migration import *
|
||||
from .group_permissions import *
|
||||
from .group_preferences import *
|
||||
from .group_shopping_list import *
|
||||
from .group_statistics import *
|
||||
from .invite_token import *
|
||||
from .webhook import *
|
||||
|
||||
26
mealie/schema/group/group_statistics.py
Normal file
26
mealie/schema/group/group_statistics.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from mealie.pkgs.stats import fs_stats
|
||||
from mealie.schema._mealie import MealieModel
|
||||
|
||||
|
||||
class GroupStatistics(MealieModel):
|
||||
total_recipes: int
|
||||
total_users: int
|
||||
total_categories: int
|
||||
total_tags: int
|
||||
total_tools: int
|
||||
|
||||
|
||||
class GroupStorage(MealieModel):
|
||||
used_storage_bytes: int
|
||||
used_storage_str: str
|
||||
total_storage_bytes: int
|
||||
total_storage_str: str
|
||||
|
||||
@classmethod
|
||||
def bytes(cls, used_storage_bytes: int, total_storage_bytes: int) -> "GroupStorage":
|
||||
return cls(
|
||||
used_storage_bytes=used_storage_bytes,
|
||||
used_storage_str=fs_stats.pretty_size(used_storage_bytes),
|
||||
total_storage_bytes=total_storage_bytes,
|
||||
total_storage_str=fs_stats.pretty_size(total_storage_bytes),
|
||||
)
|
||||
40
mealie/services/group_services/group_service.py
Normal file
40
mealie/services/group_services/group_service.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from pydantic import UUID4
|
||||
|
||||
from mealie.pkgs.stats import fs_stats
|
||||
from mealie.repos.repository_factory import AllRepositories
|
||||
from mealie.schema.group.group_statistics import GroupStatistics, GroupStorage
|
||||
from mealie.services._base_service import BaseService
|
||||
|
||||
ALLOWED_SIZE = 500 * fs_stats.megabyte
|
||||
|
||||
|
||||
class GroupService(BaseService):
|
||||
def __init__(self, group_id: UUID4, repos: AllRepositories):
|
||||
self.group_id = group_id
|
||||
self.repos = repos
|
||||
super().__init__()
|
||||
|
||||
def calculate_statistics(self, group_id: None | UUID4 = None) -> GroupStatistics:
|
||||
"""
|
||||
calculate_statistics calculates the statistics for the group and returns
|
||||
a GroupStatistics object.
|
||||
"""
|
||||
target_id = group_id or self.group_id
|
||||
|
||||
return self.repos.groups.statistics(target_id)
|
||||
|
||||
def calculate_group_storage(self, group_id: None | UUID4 = None) -> GroupStorage:
|
||||
"""
|
||||
calculate_group_storage calculates the storage used by the group and returns
|
||||
a GroupStorage object.
|
||||
"""
|
||||
|
||||
target_id = group_id or self.group_id
|
||||
|
||||
all_ids = self.repos.recipes.all_ids(target_id)
|
||||
|
||||
used_size = sum(
|
||||
fs_stats.get_dir_size(f"{self.directories.RECIPE_DATA_DIR}/{str(recipe_id)}") for recipe_id in all_ids
|
||||
)
|
||||
|
||||
return GroupStorage.bytes(used_size, ALLOWED_SIZE)
|
||||
Reference in New Issue
Block a user