Упрощение системы получателей доставки

- Удалено избыточное поле customer_is_recipient из модели Order
- Добавлено свойство @property is_customer_recipient для обратной совместимости
- Заменены радиокнопки recipient_mode на чекбокс 'Другой получатель' в форме
- Добавлено поле recipient_source для выбора между историей и новым получателем
- Обновлен AddressService.process_recipient_from_form() для работы с чекбоксом
- Обновлены шаблоны: order_form.html (чекбокс вместо радиокнопок) и order_detail.html
- Удалено customer_is_recipient из admin и demo команды
- Создана миграция для удаления поля customer_is_recipient

Логика упрощена: recipient is None = получатель = покупатель, иначе - отдельный получатель
This commit is contained in:
2025-12-24 17:54:57 +03:00
parent 9f4f03e340
commit d62caa924b
9 changed files with 168 additions and 82 deletions

View File

@@ -86,9 +86,9 @@ class OrderAdmin(admin.ModelAdmin):
}),
('Получатель', {
'fields': (
'customer_is_recipient',
'recipient',
)
),
'description': 'Если получатель не указан, получателем является покупатель'
}),
('Оплата', {
'fields': (

View File

@@ -11,16 +11,24 @@ class OrderForm(forms.ModelForm):
"""Форма для создания и редактирования заказа"""
# Поля для работы с получателем
recipient_mode = forms.ChoiceField(
other_recipient = forms.BooleanField(
required=False,
initial=False,
widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
label='Другой получатель',
help_text='Если отмечено, получатель отличается от покупателя'
)
# Режим выбора другого получателя (история или новый)
recipient_source = forms.ChoiceField(
choices=[
('customer', 'Покупатель является получателем'),
('history', 'Выбрать из истории'),
('new', 'Другой получатель'),
('new', 'Новый получатель'),
],
initial='customer',
initial='new',
widget=forms.RadioSelect(attrs={'class': 'form-check-input'}),
required=False,
label='Получатель'
label='Способ указания получателя'
)
# Выбор получателя из истории
@@ -170,7 +178,6 @@ class OrderForm(forms.ModelForm):
model = Order
fields = [
'customer',
'customer_is_recipient',
'recipient',
'status',
'is_anonymous',
@@ -232,28 +239,47 @@ class OrderForm(forms.ModelForm):
'data-placeholder': 'Начните вводить имя, телефон или email'
})
# Подсказки
self.fields['customer_is_recipient'].label = 'Покупатель = получатель'
# Поле получателя опционально
self.fields['recipient'].required = False
# Инициализируем чекбокс other_recipient на основе наличия recipient
if self.instance.pk:
# При редактировании заказа: если есть recipient, чекбокс включен
if self.instance.recipient:
self.fields['other_recipient'].initial = True
# Определяем источник получателя
# Проверяем, есть ли этот recipient в истории клиента
if self.instance.customer:
customer_orders = Order.objects.filter(
customer=self.instance.customer,
recipient__isnull=False
).exclude(pk=self.instance.pk).order_by('-created_at')
history_recipients = Recipient.objects.filter(
orders__in=customer_orders
).distinct()
if self.instance.recipient in history_recipients:
self.fields['recipient_source'].initial = 'history'
self.fields['recipient_from_history'].initial = self.instance.recipient.pk
else:
self.fields['recipient_source'].initial = 'new'
self.fields['recipient_name'].initial = self.instance.recipient.name or ''
self.fields['recipient_phone'].initial = self.instance.recipient.phone or ''
else:
self.fields['other_recipient'].initial = False
# Инициализируем queryset для recipient_from_history
if self.instance.pk and self.instance.customer:
# При редактировании заказа загружаем историю получателей этого клиента
customer_orders = Order.objects.filter(
customer=self.instance.customer,
recipient__isnull=False
).order_by('-created_at')
).exclude(pk=self.instance.pk).order_by('-created_at')
self.fields['recipient_from_history'].queryset = Recipient.objects.filter(
orders__in=customer_orders
).distinct().order_by('-created_at')
# Инициализируем поля получателя из существующего recipient
if self.instance.pk and self.instance.recipient:
recipient = self.instance.recipient
self.fields['recipient_name'].initial = recipient.name or ''
self.fields['recipient_phone'].initial = recipient.phone or ''
elif not self.instance.pk:
# При создании нового заказа queryset пустой (будет заполнен через JS при выборе клиента)
self.fields['recipient_from_history'].queryset = Recipient.objects.none()
# Инициализируем queryset для pickup_warehouse
from inventory.models import Warehouse

View File

@@ -132,7 +132,6 @@ class Command(BaseCommand):
# Дополнительная информация
if random.random() > 0.7: # 30% - подарок другому человеку
order.customer_is_recipient = False
# Создаем получателя
recipient_name = f"Получатель {i+1}"
recipient_phone = f"+7{random.randint(9000000000, 9999999999)}"

View File

@@ -0,0 +1,21 @@
# Generated by Django 5.0.10 on 2025-12-24 10:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orders', '0002_initial'),
]
operations = [
migrations.RemoveField(
model_name='historicalorder',
name='customer_is_recipient',
),
migrations.RemoveField(
model_name='order',
name='customer_is_recipient',
),
]

View File

@@ -94,13 +94,7 @@ class Order(models.Model):
)
# Информация о получателе
customer_is_recipient = models.BooleanField(
default=True,
verbose_name="Покупатель является получателем",
help_text="Если отмечено, данные получателя не требуются отдельно"
)
# Получатель (если покупатель != получатель)
# Получатель (если None - получатель = покупатель, иначе - отдельный получатель)
recipient = models.ForeignKey(
Recipient,
on_delete=models.SET_NULL,
@@ -324,3 +318,8 @@ class Order(models.Model):
if hasattr(self, 'delivery') and self.delivery:
return self.delivery.pickup_warehouse
return None
@property
def is_customer_recipient(self):
"""Является ли покупатель получателем (обратная совместимость)"""
return self.recipient is None

View File

@@ -38,4 +38,4 @@ class Recipient(models.Model):
@property
def display_name(self):
"""Форматированное имя для отображения"""
return f"{self.name} - {self.phone}"
return f"Получатель{self.name} - {self.phone}"

View File

@@ -70,14 +70,16 @@ class AddressService:
Returns:
Recipient or None: Получатель для привязки к заказу или None
"""
recipient_mode = form_data.get('recipient_mode')
# Если режим "покупатель = получатель" - возвращаем None
if recipient_mode == 'customer':
# Если чекбокс "Другой получатель" не включен - возвращаем None (получатель = покупатель)
other_recipient = form_data.get('other_recipient', False)
if not other_recipient:
return None
# Определяем источник получателя
recipient_source = form_data.get('recipient_source', 'new')
# Если режим "выбрать из истории" - возвращаем выбранного получателя
if recipient_mode == 'history':
if recipient_source == 'history':
recipient_id = form_data.get('recipient_from_history')
if recipient_id:
try:
@@ -86,7 +88,7 @@ class AddressService:
return None
# Если режим "новый получатель"
if recipient_mode == 'new':
if recipient_source == 'new':
name = form_data.get('recipient_name', '').strip()
phone = form_data.get('recipient_phone', '').strip()

View File

@@ -131,7 +131,7 @@
</div>
<!-- Получатель -->
{% if not order.customer_is_recipient and order.recipient %}
{% if order.recipient %}
<div class="card mb-3">
<div class="card-header">
<h5 class="mb-0">Получатель</h5>

View File

@@ -532,54 +532,74 @@
<div class="border-top pt-3 mt-3">
<h6 class="mb-3">Получатель</h6>
<!-- Режимы выбора получателя -->
<!-- Чекбокс "Другой получатель" -->
<div class="mb-3">
{% for choice in form.recipient_mode %}
<div class="form-check">
{{ choice.tag }}
<label class="form-check-label" for="{{ choice.id_for_label }}">
{{ choice.choice_label }}
{{ form.other_recipient }}
<label class="form-check-label" for="{{ form.other_recipient.id_for_label }}">
{{ form.other_recipient.label }}
</label>
{% if form.other_recipient.help_text %}
<small class="form-text text-muted">{{ form.other_recipient.help_text }}</small>
{% endif %}
</div>
{% endfor %}
{% if form.recipient_mode.errors %}
<div class="text-danger">{{ form.recipient_mode.errors }}</div>
{% if form.other_recipient.errors %}
<div class="text-danger">{{ form.other_recipient.errors }}</div>
{% endif %}
</div>
<!-- Выбор получателя из истории -->
<div class="mb-3" id="recipient-history-field" style="display: none;">
<label for="{{ form.recipient_from_history.id_for_label }}" class="form-label">
{{ form.recipient_from_history.label }}
</label>
{{ form.recipient_from_history }}
{% if form.recipient_from_history.errors %}
<div class="text-danger">{{ form.recipient_from_history.errors }}</div>
{% endif %}
</div>
<!-- Поля нового получателя -->
<div class="row" id="recipient-new-fields" style="display: none;">
<div class="col-md-6">
<div class="mb-3">
<label for="{{ form.recipient_name.id_for_label }}" class="form-label">
Имя получателя
<!-- Блок для другого получателя (показывается при включенном чекбоксе) -->
<div id="other-recipient-block" style="display: none;">
<!-- Режим выбора получателя (история или новый) -->
<div class="mb-3">
<label class="form-label d-block mb-2">{{ form.recipient_source.label }}</label>
{% for choice in form.recipient_source %}
<div class="form-check">
{{ choice.tag }}
<label class="form-check-label" for="{{ choice.id_for_label }}">
{{ choice.choice_label }}
</label>
{{ form.recipient_name }}
{% if form.recipient_name.errors %}
<div class="text-danger">{{ form.recipient_name.errors }}</div>
{% endif %}
</div>
{% endfor %}
{% if form.recipient_source.errors %}
<div class="text-danger">{{ form.recipient_source.errors }}</div>
{% endif %}
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="{{ form.recipient_phone.id_for_label }}" class="form-label">
Телефон получателя
</label>
{{ form.recipient_phone }}
{% if form.recipient_phone.errors %}
<div class="text-danger">{{ form.recipient_phone.errors }}</div>
{% endif %}
<!-- Выбор получателя из истории -->
<div class="mb-3" id="recipient-history-field" style="display: none;">
<label for="{{ form.recipient_from_history.id_for_label }}" class="form-label">
{{ form.recipient_from_history.label }}
</label>
{{ form.recipient_from_history }}
{% if form.recipient_from_history.errors %}
<div class="text-danger">{{ form.recipient_from_history.errors }}</div>
{% endif %}
</div>
<!-- Поля нового получателя -->
<div class="row" id="recipient-new-fields" style="display: none;">
<div class="col-md-6">
<div class="mb-3">
<label for="{{ form.recipient_name.id_for_label }}" class="form-label">
Имя получателя
</label>
{{ form.recipient_name }}
{% if form.recipient_name.errors %}
<div class="text-danger">{{ form.recipient_name.errors }}</div>
{% endif %}
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="{{ form.recipient_phone.id_for_label }}" class="form-label">
Телефон получателя
</label>
{{ form.recipient_phone }}
{% if form.recipient_phone.errors %}
<div class="text-danger">{{ form.recipient_phone.errors }}</div>
{% endif %}
</div>
</div>
</div>
</div>
@@ -971,31 +991,50 @@ document.addEventListener('DOMContentLoaded', function() {
syncUIFromCheckbox();
// Показ/скрытие полей получателя
const recipientModeRadios = document.querySelectorAll('input[name="recipient_mode"]');
const otherRecipientCheckbox = document.getElementById('{{ form.other_recipient.id_for_label }}');
const otherRecipientBlock = document.getElementById('other-recipient-block');
const recipientSourceRadios = document.querySelectorAll('input[name="recipient_source"]');
const recipientHistoryField = document.getElementById('recipient-history-field');
const recipientNewFields = document.getElementById('recipient-new-fields');
function toggleRecipientFields() {
const selectedMode = document.querySelector('input[name="recipient_mode"]:checked');
if (!selectedMode) return;
function toggleOtherRecipientBlock() {
if (otherRecipientCheckbox.checked) {
otherRecipientBlock.style.display = 'block';
toggleRecipientSourceFields();
} else {
otherRecipientBlock.style.display = 'none';
recipientHistoryField.style.display = 'none';
recipientNewFields.style.display = 'none';
}
}
const mode = selectedMode.value;
function toggleRecipientSourceFields() {
const selectedSource = document.querySelector('input[name="recipient_source"]:checked');
if (!selectedSource) return;
const source = selectedSource.value;
// Скрываем все поля
recipientHistoryField.style.display = 'none';
recipientNewFields.style.display = 'none';
// Показываем нужные поля
if (mode === 'history') {
if (source === 'history') {
recipientHistoryField.style.display = 'block';
} else if (mode === 'new') {
} else if (source === 'new') {
recipientNewFields.style.display = 'block';
}
// Для 'customer' ничего не показываем
}
recipientModeRadios.forEach(radio => {
radio.addEventListener('change', toggleRecipientFields);
// Обработчики событий
if (otherRecipientCheckbox) {
otherRecipientCheckbox.addEventListener('change', toggleOtherRecipientBlock);
// Инициализация при загрузке
toggleOtherRecipientBlock();
}
recipientSourceRadios.forEach(radio => {
radio.addEventListener('change', toggleRecipientSourceFields);
});
toggleRecipientFields();