From 17ef64a767d7bab492667384fa25de9df19b184a Mon Sep 17 00:00:00 2001 From: sm4640 Date: Sat, 12 Apr 2025 01:50:10 +0900 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Feat:=20[#22]=20stateChangeService,?= =?UTF-8?q?checkRelService=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- portfolios/services.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 portfolios/services.py diff --git a/portfolios/services.py b/portfolios/services.py new file mode 100644 index 0000000..2d879b4 --- /dev/null +++ b/portfolios/services.py @@ -0,0 +1,40 @@ +from .models import Portfolio + + +ACTION_FIELD_MAP = { + 'like': 'likers', + 'scrap': 'scrappers', + } + +class PortfolioBeforeRelCheckService: + @staticmethod + def check_user_portfolio_rel(action_type: str, portfolio: Portfolio, user): + action = ACTION_FIELD_MAP.get(action_type) + if not action: + raise ValueError(f"'{action_type}' is unsupported action type") + + if getattr(portfolio, action).filter(id=user.id).exists(): + return True + else: + return False + +class PortfolioStateChangeService: + @staticmethod + def change_user_portfolio_rel(action_type: str, portfolio: Portfolio, 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(portfolio, action), 'add' if add else 'remove') + user_method(user) + + @staticmethod + def change_count_portfolio_state(action_type: str, portfolio: Portfolio, 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(portfolio, field_name) + now_count = current_count+1 if add else max(current_count-1, 0) + setattr(portfolio, field_name, now_count) + portfolio.save(update_fields=[field_name])