From 0e5c0ce16fa01fd66e8cdae2d9f077de3195377e Mon Sep 17 00:00:00 2001 From: phzhik Date: Sat, 11 Nov 2023 09:51:17 +0400 Subject: [PATCH] * WIP: annotate_commission_rub --- store/models.py | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/store/models.py b/store/models.py index 577fdd9..3f2e8dc 100644 --- a/store/models.py +++ b/store/models.py @@ -277,15 +277,33 @@ class ChecklistQuerySet(models.QuerySet): ) def annotate_commission_rub(self): - # FIXME: implement category commission in DB query - return self + default_commission = GlobalSettings.load().commission_rub + over_150k_commission = F('_price_rub') * settings.COMMISSION_OVER_150K - commission = GlobalSettings.load().commission_rub - return self.annotate(_commission_rub=Case( - When(GreaterThan(F("_price_rub"), 150_000), then=F("_price_rub") * settings.COMMISSION_OVER_150K), - default=commission, - output_field=DecimalField() - )) + category_commission_is_zero_and_parent_present = ( + (Q(category__commission__isnull=True) | Q(category__commission=0)) & Q(category__parent__isnull=False) + ) + + return self.annotate( + _category_commission_percent=Case( + When(category_commission_is_zero_and_parent_present, then=F('category__parent__commission')), + default=F('category__commission') + ), + + _category_commission=F('_category_commission_percent') * F('_price_rub') / 100, + + _over_150k_commission=Case( + When(GreaterThan(F("_price_rub"), 150_000), then=over_150k_commission), + default=0, + output_field=DecimalField() + ), + + _commission_rub=Case( + When(price_snapshot_id__isnull=False, then=F('price_snapshot__commission_rub')), + default=Max(default_commission, F('_over_150k_commission'), F('_category_commission')), + output_field=DecimalField() + ), + ) class PriceSnapshot(models.Model): @@ -485,10 +503,9 @@ class Checklist(models.Model): @property def commission_rub(self) -> Decimal: - # FIXME: implement category commission in DB query - # # Prefer annotated field - # if hasattr(self, '_commission_rub'): - # return self._commission_rub + # Prefer annotated field + if hasattr(self, '_commission_rub'): + return self._commission_rub # Prefer saved value if self.price_snapshot_id: