feat(discounts, orders): рефакторинг системы скидок - единый источник правды
- Добавлен combine_mode в форму создания/редактирования скидок - Добавлена колонка "Объединение" в список скидок с иконками - Добавлен фильтр по режиму объединения скидок - Добавлена валидация: только одна exclusive скидка на заказ - Удалены дублирующие поля из Order и OrderItem: - applied_discount, applied_promo_code, discount_amount - Скидки теперь хранятся только в DiscountApplication - Добавлены свойства для обратной совместимости Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -34,8 +34,7 @@ class DiscountApplier:
|
||||
from discounts.services.calculator import DiscountCalculator
|
||||
|
||||
# Удаляем предыдущую скидку на заказ
|
||||
if order.applied_promo_code:
|
||||
DiscountApplier._remove_order_discount_only(order)
|
||||
DiscountApplier._remove_order_discount_only(order)
|
||||
|
||||
# Рассчитываем скидку
|
||||
result = DiscountCalculator.calculate_order_discount(order, promo_code)
|
||||
@@ -50,21 +49,7 @@ class DiscountApplier:
|
||||
discounts_data = result['discounts']
|
||||
total_amount = result['total_amount']
|
||||
|
||||
# Применяем первую скидку в applied_discount (для обратной совместимости с Order)
|
||||
if discounts_data:
|
||||
first_discount = discounts_data[0]['discount']
|
||||
order.applied_discount = first_discount
|
||||
order.applied_promo_code = promo.code
|
||||
order.discount_amount = total_amount
|
||||
order.save(update_fields=['applied_discount', 'applied_promo_code', 'discount_amount'])
|
||||
|
||||
# Пересчитываем total_amount
|
||||
order.calculate_total()
|
||||
|
||||
# Регистрируем использование промокода
|
||||
promo.record_usage(order.customer)
|
||||
|
||||
# Создаем записи о применении для каждой скидки
|
||||
# Создаем записи о применении для каждой скидки в DiscountApplication
|
||||
for disc_data in discounts_data:
|
||||
discount = disc_data['discount']
|
||||
amount = disc_data['amount']
|
||||
@@ -85,6 +70,12 @@ class DiscountApplier:
|
||||
discount.current_usage_count += 1
|
||||
discount.save(update_fields=['current_usage_count'])
|
||||
|
||||
# Пересчитываем total_amount (использует DiscountApplication)
|
||||
order.calculate_total()
|
||||
|
||||
# Регистрируем использование промокода
|
||||
promo.record_usage(order.customer)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'discounts': discounts_data,
|
||||
@@ -124,12 +115,6 @@ class DiscountApplier:
|
||||
if order_result['discounts'] and not order_result['error']:
|
||||
total_order_amount = order_result['total_amount']
|
||||
|
||||
# Сохраняем первую скидку в applied_discount (для совместимости)
|
||||
first_discount_data = order_result['discounts'][0]
|
||||
order.applied_discount = first_discount_data['discount']
|
||||
order.discount_amount = total_order_amount
|
||||
order.save(update_fields=['applied_discount', 'discount_amount'])
|
||||
|
||||
# Создаем записи о применении для всех скидок
|
||||
for disc_data in order_result['discounts']:
|
||||
discount = disc_data['discount']
|
||||
@@ -167,12 +152,6 @@ class DiscountApplier:
|
||||
if item_result['discounts']:
|
||||
total_item_amount = item_result['total_amount']
|
||||
|
||||
# Сохраняем первую скидку в applied_discount (для совместимости)
|
||||
first_discount_data = item_result['discounts'][0]
|
||||
item.applied_discount = first_discount_data['discount']
|
||||
item.discount_amount = total_item_amount
|
||||
item.save(update_fields=['applied_discount', 'discount_amount'])
|
||||
|
||||
# Создаем записи о применении для всех скидок
|
||||
base_amount = item.price * item.quantity
|
||||
for disc_data in item_result['discounts']:
|
||||
@@ -186,7 +165,7 @@ class DiscountApplier:
|
||||
target='order_item',
|
||||
base_amount=base_amount,
|
||||
discount_amount=amount,
|
||||
final_amount=item.get_total_price(),
|
||||
final_amount=base_amount - amount,
|
||||
customer=order.customer,
|
||||
applied_by=user
|
||||
)
|
||||
@@ -216,14 +195,6 @@ class DiscountApplier:
|
||||
Args:
|
||||
order: Order
|
||||
"""
|
||||
DiscountApplier._remove_order_discount_only(order)
|
||||
|
||||
# Удаляем скидки с позиций
|
||||
order.items.update(
|
||||
applied_discount=None,
|
||||
discount_amount=Decimal('0')
|
||||
)
|
||||
|
||||
# Удаляем записи о применении
|
||||
from discounts.models import DiscountApplication
|
||||
DiscountApplication.objects.filter(order=order).delete()
|
||||
@@ -265,14 +236,6 @@ class DiscountApplier:
|
||||
# Рассчитываем сумму
|
||||
discount_amount = discount.calculate_discount_amount(Decimal(order.subtotal))
|
||||
|
||||
# Применяем к заказу
|
||||
order.applied_discount = discount
|
||||
order.discount_amount = discount_amount
|
||||
order.save(update_fields=['applied_discount', 'discount_amount'])
|
||||
|
||||
# Пересчитываем total_amount
|
||||
order.calculate_total()
|
||||
|
||||
# Создаем запись о применении
|
||||
DiscountApplication.objects.create(
|
||||
order=order,
|
||||
@@ -289,6 +252,9 @@ class DiscountApplier:
|
||||
discount.current_usage_count += 1
|
||||
discount.save(update_fields=['current_usage_count'])
|
||||
|
||||
# Пересчитываем total_amount
|
||||
order.calculate_total()
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'discount_amount': discount_amount
|
||||
@@ -307,7 +273,5 @@ class DiscountApplier:
|
||||
# Удаляем записи о применении скидок к заказу
|
||||
DiscountApplication.objects.filter(order=order, target='order').delete()
|
||||
|
||||
order.applied_discount = None
|
||||
order.applied_promo_code = None
|
||||
order.discount_amount = Decimal('0')
|
||||
order.save(update_fields=['applied_discount', 'applied_promo_code', 'discount_amount'])
|
||||
# Пересчитываем (order.discount_amount теперь свойство, берущее из DiscountApplication)
|
||||
order.calculate_total()
|
||||
|
||||
@@ -101,6 +101,22 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="id_combine_mode" class="form-label">Режим объединения с другими скидками</label>
|
||||
<select class="form-select" id="id_combine_mode" name="combine_mode">
|
||||
<option value="max_only" {% if form.combine_mode.value == 'max_only' or not form.combine_mode.value %}selected{% endif %}>
|
||||
🏆 Только максимум (применяется лучшая скидка)
|
||||
</option>
|
||||
<option value="stack" {% if form.combine_mode.value == 'stack' %}selected{% endif %}>
|
||||
📚 Складывать (суммировать с другими)
|
||||
</option>
|
||||
<option value="exclusive" {% if form.combine_mode.value == 'exclusive' %}selected{% endif %}>
|
||||
🚫 Исключающая (отменяет остальные скидки)
|
||||
</option>
|
||||
</select>
|
||||
<div class="form-text">Как эта скидка взаимодействует с другими активными скидками</div>
|
||||
</div>
|
||||
|
||||
<!-- Ограничения -->
|
||||
<h5 class="mb-3 mt-4">Ограничения</h5>
|
||||
<div class="row mb-3">
|
||||
|
||||
@@ -60,6 +60,15 @@
|
||||
<option value="inactive" {% if current_filters.is_active == 'inactive' %}selected{% endif %}>Неактивные</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label">Объединение</label>
|
||||
<select name="combine_mode" class="form-select">
|
||||
<option value="">Все</option>
|
||||
<option value="stack" {% if current_filters.combine_mode == 'stack' %}selected{% endif %}>Складывать</option>
|
||||
<option value="max_only" {% if current_filters.combine_mode == 'max_only' %}selected{% endif %}>Максимум</option>
|
||||
<option value="exclusive" {% if current_filters.combine_mode == 'exclusive' %}selected{% endif %}>Исключающая</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3 d-flex align-items-end">
|
||||
<button type="submit" class="btn btn-primary me-2">
|
||||
<i class="bi bi-funnel"></i> Применить
|
||||
@@ -84,6 +93,7 @@
|
||||
<th>Значение</th>
|
||||
<th>Область</th>
|
||||
<th>Авто</th>
|
||||
<th>Объединение</th>
|
||||
<th>Статус</th>
|
||||
<th>Промокоды</th>
|
||||
<th>Использований</th>
|
||||
@@ -129,6 +139,15 @@
|
||||
<i class="bi bi-dash-circle text-muted"></i>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if discount.combine_mode == 'stack' %}
|
||||
<span class="badge bg-secondary" title="Складывать (суммировать)">📚 Склад.</span>
|
||||
{% elif discount.combine_mode == 'max_only' %}
|
||||
<span class="badge bg-info" title="Только максимум">🏆 Макс.</span>
|
||||
{% elif discount.combine_mode == 'exclusive' %}
|
||||
<span class="badge bg-danger" title="Исключающая (отменяет остальные)">🚫 Исключ.</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if discount.is_active %}
|
||||
<span class="badge bg-success">Активна</span>
|
||||
@@ -180,10 +199,10 @@
|
||||
<ul class="pagination justify-content-center">
|
||||
{% if page_obj.has_previous %}
|
||||
<li class="page-item">
|
||||
<a class="page-link" href="?page=1{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}">«</a>
|
||||
<a class="page-link" href="?page=1{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}{% if current_filters.combine_mode %}&combine_mode={{ current_filters.combine_mode }}{% endif %}">«</a>
|
||||
</li>
|
||||
<li class="page-item">
|
||||
<a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}">‹</a>
|
||||
<a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}{% if current_filters.combine_mode %}&combine_mode={{ current_filters.combine_mode }}{% endif %}">‹</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
|
||||
@@ -193,10 +212,10 @@
|
||||
|
||||
{% if page_obj.has_next %}
|
||||
<li class="page-item">
|
||||
<a class="page-link" href="?page={{ page_obj.next_page_number }}{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}">›</a>
|
||||
<a class="page-link" href="?page={{ page_obj.next_page_number }}{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}{% if current_filters.combine_mode %}&combine_mode={{ current_filters.combine_mode }}{% endif %}">›</a>
|
||||
</li>
|
||||
<li class="page-item">
|
||||
<a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}">»</a>
|
||||
<a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if current_filters.search %}&search={{ current_filters.search }}{% endif %}{% if current_filters.type %}&type={{ current_filters.type }}{% endif %}{% if current_filters.scope %}&scope={{ current_filters.scope }}{% endif %}{% if current_filters.is_active %}&is_active={{ current_filters.is_active }}{% endif %}{% if current_filters.combine_mode %}&combine_mode={{ current_filters.combine_mode }}{% endif %}">»</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
|
||||
@@ -71,6 +71,7 @@ class DiscountListView(DiscountAccessMixin, ListView):
|
||||
discount_type = self.request.GET.get('type')
|
||||
scope = self.request.GET.get('scope')
|
||||
is_active = self.request.GET.get('is_active')
|
||||
combine_mode = self.request.GET.get('combine_mode')
|
||||
search = self.request.GET.get('search')
|
||||
|
||||
if discount_type:
|
||||
@@ -79,6 +80,8 @@ class DiscountListView(DiscountAccessMixin, ListView):
|
||||
queryset = queryset.filter(scope=scope)
|
||||
if is_active:
|
||||
queryset = queryset.filter(is_active=(is_active == 'active'))
|
||||
if combine_mode:
|
||||
queryset = queryset.filter(combine_mode=combine_mode)
|
||||
if search:
|
||||
queryset = queryset.filter(
|
||||
Q(name__icontains=search) | Q(description__icontains=search)
|
||||
@@ -92,6 +95,7 @@ class DiscountListView(DiscountAccessMixin, ListView):
|
||||
'type': self.request.GET.get('type', ''),
|
||||
'scope': self.request.GET.get('scope', ''),
|
||||
'is_active': self.request.GET.get('is_active', ''),
|
||||
'combine_mode': self.request.GET.get('combine_mode', ''),
|
||||
'search': self.request.GET.get('search', ''),
|
||||
}
|
||||
context['can_edit'] = self._can_edit()
|
||||
@@ -110,7 +114,7 @@ class DiscountCreateView(LoginRequiredMixin, RoleRequiredMixin, CreateView):
|
||||
template_name = 'discounts/discount_form.html'
|
||||
fields = [
|
||||
'name', 'description', 'discount_type', 'value', 'scope',
|
||||
'is_auto', 'is_active', 'priority',
|
||||
'is_auto', 'is_active', 'priority', 'combine_mode',
|
||||
'start_date', 'end_date',
|
||||
'min_order_amount', 'max_usage_count',
|
||||
'products', 'categories', 'excluded_products',
|
||||
@@ -119,6 +123,21 @@ class DiscountCreateView(LoginRequiredMixin, RoleRequiredMixin, CreateView):
|
||||
success_url = reverse_lazy('system_settings:discounts:list')
|
||||
|
||||
def form_valid(self, form):
|
||||
# Валидация: нельзя создать больше одной активной exclusive скидки на заказ
|
||||
if form.instance.combine_mode == 'exclusive' and form.instance.scope == 'order' and form.instance.is_active:
|
||||
existing_exclusive = Discount.objects.filter(
|
||||
combine_mode='exclusive',
|
||||
scope='order',
|
||||
is_active=True
|
||||
).exists()
|
||||
|
||||
if existing_exclusive:
|
||||
form.add_error(
|
||||
'combine_mode',
|
||||
'Уже существует активная исключающая скидка на заказ. Может быть только одна.'
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
|
||||
form.instance.created_by = self.request.user
|
||||
messages.success(self.request, f'Скидка "{form.instance.name}" создана')
|
||||
return super().form_valid(form)
|
||||
@@ -142,7 +161,7 @@ class DiscountUpdateView(LoginRequiredMixin, RoleRequiredMixin, UpdateView):
|
||||
template_name = 'discounts/discount_form.html'
|
||||
fields = [
|
||||
'name', 'description', 'discount_type', 'value', 'scope',
|
||||
'is_auto', 'is_active', 'priority',
|
||||
'is_auto', 'is_active', 'priority', 'combine_mode',
|
||||
'start_date', 'end_date',
|
||||
'min_order_amount', 'max_usage_count',
|
||||
'products', 'categories', 'excluded_products',
|
||||
@@ -151,6 +170,21 @@ class DiscountUpdateView(LoginRequiredMixin, RoleRequiredMixin, UpdateView):
|
||||
success_url = reverse_lazy('system_settings:discounts:list')
|
||||
|
||||
def form_valid(self, form):
|
||||
# Валидация: нельзя создать больше одной активной exclusive скидки на заказ
|
||||
if form.instance.combine_mode == 'exclusive' and form.instance.scope == 'order' and form.instance.is_active:
|
||||
existing_exclusive = Discount.objects.filter(
|
||||
combine_mode='exclusive',
|
||||
scope='order',
|
||||
is_active=True
|
||||
).exclude(pk=self.object.pk).exists()
|
||||
|
||||
if existing_exclusive:
|
||||
form.add_error(
|
||||
'combine_mode',
|
||||
'Уже существует активная исключающая скидка на заказ. Может быть только одна.'
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
|
||||
messages.success(self.request, f'Скидка "{form.instance.name}" обновлена')
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user