From 6903c2ff1363dd223d9a208240efe981d690af64 Mon Sep 17 00:00:00 2001 From: phzhik Date: Thu, 23 Nov 2023 02:40:30 +0400 Subject: [PATCH] * available_count for Gift --- store/migrations/0049_gift_available_count.py | 18 ++++++++++++++++++ store/models.py | 13 +++++++++++++ store/serializers.py | 9 +++++++-- 3 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 store/migrations/0049_gift_available_count.py diff --git a/store/migrations/0049_gift_available_count.py b/store/migrations/0049_gift_available_count.py new file mode 100644 index 0000000..fc99734 --- /dev/null +++ b/store/migrations/0049_gift_available_count.py @@ -0,0 +1,18 @@ +# Generated by Django 4.2.2 on 2023-11-22 22:28 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('store', '0048_globalsettings_yuan_rate_commission_and_more'), + ] + + operations = [ + migrations.AddField( + model_name='gift', + name='available_count', + field=models.PositiveSmallIntegerField(default=0, verbose_name='Доступное количество'), + ), + ] diff --git a/store/models.py b/store/models.py index fb92096..15bca0a 100644 --- a/store/models.py +++ b/store/models.py @@ -260,6 +260,7 @@ class Gift(models.Model): name = models.CharField('Название', max_length=100) image = models.ImageField('Фото', upload_to=Image.TYPE_TO_UPLOAD_PATH[Image.GIFT], null=True, blank=True) min_price = models.DecimalField('Минимальная цена в юанях', help_text='от какой суммы доступен подарок', max_digits=10, decimal_places=2, default=0) + available_count = models.PositiveSmallIntegerField('Доступное количество', default=0) def __str__(self): return self.name @@ -636,6 +637,18 @@ class Checklist(models.Model): if not self.preview_image: self.generate_preview() + # Update available gifts count + if self.gift != old_obj.gift: + # Decrement new gift + if self.gift: + self.gift.available_count = max(self.gift.available_count - 1, 0) + self.gift.save() + + # Increment new gift + if old_obj.gift: + old_obj.gift.available_count = max(old_obj.gift.available_count + 1, 0) + old_obj.gift.save() + # Save price details to snapshot if self.price_snapshot_id: # Status updated from other statuses back to DRAFT diff --git a/store/serializers.py b/store/serializers.py index 13247fd..7312150 100644 --- a/store/serializers.py +++ b/store/serializers.py @@ -200,8 +200,13 @@ class AnonymousUserChecklistSerializer(ChecklistSerializer): def validate(self, attrs): gift = attrs.get('gift') - if gift is not None and self.instance.price_yuan < gift.min_price: - raise CRMException("Can't add gift: price of order < min_price of gift") + if gift is not None: + if self.instance.price_yuan < gift.min_price: + raise CRMException("Can't add gift: price of order < min_price of gift") + + if gift.available_count == 0: + raise CRMException("Gift is not available") + return attrs