Files
colio/projects/services.py

57 lines
1.9 KiB
Python

from .models import *
from .serializers import *
from users.models import *
from common.models.choiceModels import InvitationStatus
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])
class ProjectInvitationService:
@staticmethod
def create_project_invitation(project: Project, from_user: User, to_user: User, notification: Notification):
return ProjectInvitation.objects.create(
project=project,
from_user=from_user,
to_user=to_user,
status= InvitationStatus.PENDING,
notification=notification
)