diff --git a/projects/services.py b/projects/services.py new file mode 100644 index 0000000..50b9a64 --- /dev/null +++ b/projects/services.py @@ -0,0 +1,40 @@ +from .models import Project + + +ACTION_FIELD_MAP = { + 'like': 'likers', + 'scrap': 'scrappers', + } + +class ProjectBeforeRelCheckService: + @staticmethod + def check_user_project_rel(action_type: str, project: Project, user): + action = ACTION_FIELD_MAP.get(action_type) + if not action: + raise ValueError(f"'{action_type}' is unsupported action type") + + if getattr(project, action).filter(id=user.id).exists(): + return True + else: + return False + +class ProjectStateChangeService: + @staticmethod + def change_user_project_rel(action_type: str, project: Project, user, add=True): + action = ACTION_FIELD_MAP.get(action_type) + if not action: + raise ValueError(f"'{action_type}' is unsupported action type") + + user_method = getattr(getattr(project, action), 'add' if add else 'remove') + user_method(user) + + @staticmethod + def change_count_project_state(action_type: str, project: Project, add=True): + action = ACTION_FIELD_MAP.get(action_type) + if not action: + raise ValueError(f"'{action_type}' is unsupported action type") + field_name = action_type + '_count' + current_count = getattr(project, field_name) + now_count = current_count+1 if add else max(current_count-1, 0) + setattr(project, field_name, now_count) + project.save(update_fields=[field_name])