Compare commits
74 Commits
2f8a78cfa7
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 9a7c0728f0 | |||
| 67ad0e50ee | |||
| 32bc0d2c39 | |||
| f140469a56 | |||
| d947f4eee7 | |||
| 5700314b10 | |||
| b24a0d9f21 | |||
| 034be20a5a | |||
| f75e861bb8 | |||
| 5a66d492c8 | |||
| 6cd0a945de | |||
| 41e6c33683 | |||
| bf399996b8 | |||
| 2bc70968c3 | |||
| 38fbf36731 | |||
| 9c91a99189 | |||
| 1eec8b1cd5 | |||
| 977ee91fee | |||
| fce8d9eb6e | |||
| 5070913346 | |||
| 87f6484258 | |||
| 14c1a4f804 | |||
| adbbd7539b | |||
| 5ec5ee48d4 | |||
| 3aac83474b | |||
| 4a624d5fef | |||
| 9ddf54f398 | |||
| 84cfc5cd47 | |||
| 59f7a7c520 | |||
| 22e300394b | |||
| 01873be15d | |||
| 036b9d1634 | |||
| 391d48640b | |||
| 07a9de040f | |||
| 622c544182 | |||
| ffc5f4cfc1 | |||
| e138a28475 | |||
| 2dc36b3d01 | |||
| 1e4b7598ae | |||
| 2620eea779 | |||
| 1071f3cacc | |||
| 6b327fa7e0 | |||
| 0938878e67 | |||
| 9cd3796527 | |||
| 271ac66098 | |||
| 0b5db0c2e6 | |||
| 4b384ef359 | |||
| d76fd2e7b2 | |||
| 0b35b80ee7 | |||
| 229fb18440 | |||
| d87c602f5a | |||
| 2778796118 | |||
| 392471ff06 | |||
| b188f5c2df | |||
| 1b749ebe63 | |||
| 017fa4b744 | |||
| 961cfcb9cd | |||
| b6206ebe09 | |||
| e3949d249f | |||
| e10f2c413b | |||
| 1d4bbf6a6d | |||
| b31961f939 | |||
| 1400514fd3 | |||
| 0d882781da | |||
| ab1e8ebd18 | |||
| d182a7b16d | |||
| c4e7efc3b1 | |||
| 3205f5a2ce | |||
| 5ca474a133 | |||
| aac47afcb9 | |||
| b88ec3997e | |||
| 3006207812 | |||
| c0401176a9 | |||
| 0060f746c8 |
@@ -75,6 +75,11 @@ class CustomUser(AbstractBaseUser):
|
|||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.email
|
return self.email
|
||||||
|
|
||||||
|
@property
|
||||||
|
def display_name(self):
|
||||||
|
"""Отображаемое имя пользователя: имя если есть, иначе email"""
|
||||||
|
return self.name or self.email
|
||||||
|
|
||||||
def has_perm(self, perm, obj=None):
|
def has_perm(self, perm, obj=None):
|
||||||
"""
|
"""
|
||||||
Проверка разрешения через authentication backends.
|
Проверка разрешения через authentication backends.
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
{% extends "system_settings/base_settings.html" %}
|
{% extends "system_settings/base_settings.html" %}
|
||||||
|
{% load inventory_filters %}
|
||||||
|
|
||||||
{% block title %}{% if is_edit %}Редактирование скидки{% else %}Создание скидки{% endif %}{% endblock %}
|
{% block title %}{% if is_edit %}Редактирование скидки{% else %}Создание скидки{% endif %}{% endblock %}
|
||||||
|
|
||||||
@@ -33,13 +34,13 @@
|
|||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<label for="id_name" class="form-label">Название * <span class="text-muted small">(макс. 200 символов)</span></label>
|
<label for="id_name" class="form-label">Название * <span class="text-muted small">(макс. 200 символов)</span></label>
|
||||||
<input type="text" class="form-control" id="id_name" name="name"
|
<input type="text" class="form-control" id="id_name" name="name"
|
||||||
value="{% if form.name.value %}{{ form.name.value }}{% endif %}"
|
value="{{ form.name.value|default_if_none:'' }}"
|
||||||
maxlength="200" required>
|
maxlength="200" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<label for="id_priority" class="form-label">Приоритет</label>
|
<label for="id_priority" class="form-label">Приоритет</label>
|
||||||
<input type="number" class="form-control" id="id_priority" name="priority"
|
<input type="number" class="form-control" id="id_priority" name="priority"
|
||||||
value="{% if form.priority.value %}{{ form.priority.value }}{% else %}0{% endif %}"
|
value="{{ form.priority.value|default_if_none:0 }}"
|
||||||
min="0">
|
min="0">
|
||||||
<div class="form-text">Выше = применяется раньше</div>
|
<div class="form-text">Выше = применяется раньше</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -47,7 +48,7 @@
|
|||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_description" class="form-label">Описание</label>
|
<label for="id_description" class="form-label">Описание</label>
|
||||||
<textarea class="form-control" id="id_description" name="description" rows="2">{{ form.description.value }}</textarea>
|
<textarea class="form-control" id="id_description" name="description" rows="2">{{ form.description.value|default_if_none:'' }}</textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Параметры скидки -->
|
<!-- Параметры скидки -->
|
||||||
@@ -57,23 +58,28 @@
|
|||||||
<label for="id_discount_type" class="form-label">Тип скидки *</label>
|
<label for="id_discount_type" class="form-label">Тип скидки *</label>
|
||||||
<select class="form-select" id="id_discount_type" name="discount_type" required>
|
<select class="form-select" id="id_discount_type" name="discount_type" required>
|
||||||
<option value="">Выберите...</option>
|
<option value="">Выберите...</option>
|
||||||
<option value="percentage" {% if form.discount_type.value == 'percentage' %}selected{% endif %}>Процент</option>
|
<option value="percentage"
|
||||||
<option value="fixed_amount" {% if form.discount_type.value == 'fixed_amount' %}selected{% endif %}>Фиксированная сумма (руб.)</option>
|
{% if form.discount_type.value == 'percentage' %}selected{% endif %}>Процент</option>
|
||||||
|
<option value="fixed_amount"
|
||||||
|
{% if form.discount_type.value == 'fixed_amount' %}selected{% endif %}>Фиксированная сумма (руб.)</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<label for="id_value" class="form-label">Значение *</label>
|
<label for="id_value" class="form-label">Значение *</label>
|
||||||
<input type="number" class="form-control" id="id_value" name="value"
|
<input type="number" class="form-control" id="id_value" name="value"
|
||||||
value="{% if form.value.value %}{{ form.value.value }}{% endif %}"
|
value="{{ form.value.value|format_decimal:2|default_if_none:'' }}"
|
||||||
step="0.01" min="0" required>
|
step="0.01" min="0" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<label for="id_scope" class="form-label">Область действия *</label>
|
<label for="id_scope" class="form-label">Область действия *</label>
|
||||||
<select class="form-select" id="id_scope" name="scope" required>
|
<select class="form-select" id="id_scope" name="scope" required>
|
||||||
<option value="">Выберите...</option>
|
<option value="">Выберите...</option>
|
||||||
<option value="order" {% if form.scope.value == 'order' %}selected{% endif %}>На весь заказ</option>
|
<option value="order"
|
||||||
<option value="product" {% if form.scope.value == 'product' %}selected{% endif %}>На конкретные товары</option>
|
{% if form.scope.value == 'order' %}selected{% endif %}>На весь заказ</option>
|
||||||
<option value="category" {% if form.scope.value == 'category' %}selected{% endif %}>На категории товаров</option>
|
<option value="product"
|
||||||
|
{% if form.scope.value == 'product' %}selected{% endif %}>На конкретные товары</option>
|
||||||
|
<option value="category"
|
||||||
|
{% if form.scope.value == 'category' %}selected{% endif %}>На категории товаров</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -92,7 +98,7 @@
|
|||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<div class="form-check form-switch mt-4">
|
<div class="form-check form-switch mt-4">
|
||||||
<input class="form-check-input" type="checkbox" id="id_is_active" name="is_active"
|
<input class="form-check-input" type="checkbox" id="id_is_active" name="is_active"
|
||||||
{% if form.is_active.value is None or form.is_active.value %}checked{% endif %}>
|
{% if form.is_active.value %}checked{% endif %}>
|
||||||
<label class="form-check-label" for="id_is_active">
|
<label class="form-check-label" for="id_is_active">
|
||||||
Активна
|
Активна
|
||||||
</label>
|
</label>
|
||||||
@@ -104,13 +110,16 @@
|
|||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_combine_mode" class="form-label">Режим объединения с другими скидками</label>
|
<label for="id_combine_mode" class="form-label">Режим объединения с другими скидками</label>
|
||||||
<select class="form-select" id="id_combine_mode" name="combine_mode">
|
<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 value="max_only"
|
||||||
|
{% if form.combine_mode.value == 'max_only' or not form.combine_mode.value %}selected{% endif %}>
|
||||||
🏆 Только максимум (применяется лучшая скидка)
|
🏆 Только максимум (применяется лучшая скидка)
|
||||||
</option>
|
</option>
|
||||||
<option value="stack" {% if form.combine_mode.value == 'stack' %}selected{% endif %}>
|
<option value="stack"
|
||||||
|
{% if form.combine_mode.value == 'stack' %}selected{% endif %}>
|
||||||
📚 Складывать (суммировать с другими)
|
📚 Складывать (суммировать с другими)
|
||||||
</option>
|
</option>
|
||||||
<option value="exclusive" {% if form.combine_mode.value == 'exclusive' %}selected{% endif %}>
|
<option value="exclusive"
|
||||||
|
{% if form.combine_mode.value == 'exclusive' %}selected{% endif %}>
|
||||||
🚫 Исключающая (отменяет остальные скидки)
|
🚫 Исключающая (отменяет остальные скидки)
|
||||||
</option>
|
</option>
|
||||||
</select>
|
</select>
|
||||||
@@ -123,14 +132,14 @@
|
|||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<label for="id_min_order_amount" class="form-label">Мин. сумма заказа</label>
|
<label for="id_min_order_amount" class="form-label">Мин. сумма заказа</label>
|
||||||
<input type="number" class="form-control" id="id_min_order_amount" name="min_order_amount"
|
<input type="number" class="form-control" id="id_min_order_amount" name="min_order_amount"
|
||||||
value="{% if form.min_order_amount.value %}{{ form.min_order_amount.value }}{% endif %}"
|
value="{{ form.min_order_amount.value|format_decimal:2|default_if_none:'' }}"
|
||||||
step="0.01" min="0">
|
step="0.01" min="0">
|
||||||
<div class="form-text">Для скидок на заказ</div>
|
<div class="form-text">Для скидок на заказ</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<label for="id_max_usage_count" class="form-label">Макс. использований</label>
|
<label for="id_max_usage_count" class="form-label">Макс. использований</label>
|
||||||
<input type="number" class="form-control" id="id_max_usage_count" name="max_usage_count"
|
<input type="number" class="form-control" id="id_max_usage_count" name="max_usage_count"
|
||||||
value="{% if form.max_usage_count.value %}{{ form.max_usage_count.value }}{% endif %}"
|
value="{{ form.max_usage_count.value|default_if_none:'' }}"
|
||||||
min="1">
|
min="1">
|
||||||
<div class="form-text">Оставьте пустым для безлимитного использования</div>
|
<div class="form-text">Оставьте пустым для безлимитного использования</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -140,12 +149,12 @@
|
|||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<label for="id_start_date" class="form-label">Дата начала</label>
|
<label for="id_start_date" class="form-label">Дата начала</label>
|
||||||
<input type="datetime-local" class="form-control" id="id_start_date" name="start_date"
|
<input type="datetime-local" class="form-control" id="id_start_date" name="start_date"
|
||||||
value="{% if form.start_date.value %}{{ form.start_date.value|date:'Y-m-d\TH:i' }}{% endif %}">
|
value="{{ form.start_date.value|date:'Y-m-d\TH:i'|default_if_none:'' }}">
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<label for="id_end_date" class="form-label">Дата окончания</label>
|
<label for="id_end_date" class="form-label">Дата окончания</label>
|
||||||
<input type="datetime-local" class="form-control" id="id_end_date" name="end_date"
|
<input type="datetime-local" class="form-control" id="id_end_date" name="end_date"
|
||||||
value="{% if form.end_date.value %}{{ form.end_date.value|date:'Y-m-d\TH:i' }}{% endif %}">
|
value="{{ form.end_date.value|date:'Y-m-d\TH:i'|default_if_none:'' }}">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -174,7 +183,6 @@
|
|||||||
{% if not all_categories %}
|
{% if not all_categories %}
|
||||||
<option value="" disabled>Нет доступных категорий</option>
|
<option value="" disabled>Нет доступных категорий</option>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
%}
|
|
||||||
</select>
|
</select>
|
||||||
<div class="form-text">Удерживайте Ctrl для выбора нескольких категорий</div>
|
<div class="form-text">Удерживайте Ctrl для выбора нескольких категорий</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -204,4 +212,46 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
// Заменяем запятые на точки в числовых полях при загрузке страницы
|
||||||
|
const numberInputs = document.querySelectorAll('input[type="number"]');
|
||||||
|
numberInputs.forEach(function(input) {
|
||||||
|
if (input.value && input.value.includes(',')) {
|
||||||
|
// Сохраняем оригинальное значение с запятой для отображения
|
||||||
|
const displayValue = input.value;
|
||||||
|
const actualValue = displayValue.replace(',', '.');
|
||||||
|
|
||||||
|
// Устанавливаем значение с точкой для корректной работы HTML5 поля
|
||||||
|
input.value = actualValue;
|
||||||
|
|
||||||
|
// При фокусе возвращаем запятую для удобства пользователя
|
||||||
|
input.addEventListener('focus', function() {
|
||||||
|
if (input.value && input.value.includes('.')) {
|
||||||
|
input.value = input.value.replace('.', ',');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// При потере фокуса возвращаем точку для корректной отправки
|
||||||
|
input.addEventListener('blur', function() {
|
||||||
|
if (input.value && input.value.includes(',')) {
|
||||||
|
input.value = input.value.replace(',', '.');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Также обрабатываем отправку формы для замены запятых на точки
|
||||||
|
const form = document.querySelector('form');
|
||||||
|
form.addEventListener('submit', function() {
|
||||||
|
const numberInputs = document.querySelectorAll('input[type="number"]');
|
||||||
|
numberInputs.forEach(function(input) {
|
||||||
|
if (input.value && input.value.includes(',')) {
|
||||||
|
input.value = input.value.replace(',', '.');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2026-01-23 15:04
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('integrations', '0009_alter_glmintegration_model_name_and_more'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='openrouterintegration',
|
||||||
|
name='model_name',
|
||||||
|
field=models.CharField(blank=True, default='', help_text='Название используемой модели OpenRouter (загружается автоматически)', max_length=200, verbose_name='Название модели'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -10,14 +10,6 @@ def validate_temperature(value):
|
|||||||
raise ValidationError('Температура должна быть в диапазоне 0.0-2.0')
|
raise ValidationError('Температура должна быть в диапазоне 0.0-2.0')
|
||||||
|
|
||||||
|
|
||||||
# Список доступных моделей OpenRouter (бесплатные)
|
|
||||||
OPENROUTER_MODEL_CHOICES = [
|
|
||||||
('xiaomi/mimo-v2-flash:free', 'Xiaomi MIMO v2 Flash (Бесплатная)'),
|
|
||||||
('mistralai/devstral-2512:free', 'Mistral Devstral 2512 (Бесплатная)'),
|
|
||||||
('z-ai/glm-4.5-air:free', 'Z.AI GLM-4.5 Air (Бесплатная)'),
|
|
||||||
('qwen/qwen3-coder:free', 'Qwen 3 Coder (Бесплатная)'),
|
|
||||||
]
|
|
||||||
|
|
||||||
# Предустановленные значения температуры
|
# Предустановленные значения температуры
|
||||||
OPENROUTER_TEMPERATURE_CHOICES = [
|
OPENROUTER_TEMPERATURE_CHOICES = [
|
||||||
(0.1, '0.1 - Очень консервативно'),
|
(0.1, '0.1 - Очень консервативно'),
|
||||||
@@ -59,11 +51,11 @@ class OpenRouterIntegration(AIIntegration):
|
|||||||
)
|
)
|
||||||
|
|
||||||
model_name = models.CharField(
|
model_name = models.CharField(
|
||||||
max_length=100,
|
max_length=200,
|
||||||
default="xiaomi/mimo-v2-flash:free",
|
default="",
|
||||||
choices=OPENROUTER_MODEL_CHOICES,
|
blank=True,
|
||||||
verbose_name="Название модели",
|
verbose_name="Название модели",
|
||||||
help_text="Название используемой модели OpenRouter"
|
help_text="Название используемой модели OpenRouter (загружается автоматически)"
|
||||||
)
|
)
|
||||||
|
|
||||||
temperature = models.FloatField(
|
temperature = models.FloatField(
|
||||||
|
|||||||
@@ -3,28 +3,45 @@ from ..base import BaseIntegrationService
|
|||||||
from .config import get_openrouter_config
|
from .config import get_openrouter_config
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
import locale
|
import traceback
|
||||||
|
|
||||||
# Патч для исправления проблемы с кодировкой в httpx на Windows
|
# Патч для исправления проблемы с кодировкой в httpx на Windows
|
||||||
# Устанавливаем кодировку по умолчанию для Python
|
# Устанавливаем кодировку по умолчанию для Python
|
||||||
if sys.platform == 'win32':
|
if sys.platform == 'win32':
|
||||||
try:
|
try:
|
||||||
import httpx._models
|
import httpx._models
|
||||||
original_normalize_header_value = httpx._models._normalize_header_value
|
|
||||||
|
# Сохраняем оригинальную функцию, если она есть
|
||||||
|
_original_normalize_header_value = getattr(httpx._models, '_normalize_header_value', None)
|
||||||
|
|
||||||
def patched_normalize_header_value(value, encoding):
|
def patched_normalize_header_value(value, encoding):
|
||||||
"""Патч для использования UTF-8 вместо ASCII для заголовков"""
|
"""Патч для использования UTF-8 вместо ASCII для заголовков"""
|
||||||
# Если значение уже bytes, возвращаем его как есть
|
try:
|
||||||
if isinstance(value, bytes):
|
# Если значение уже bytes, возвращаем его как есть
|
||||||
return value
|
if isinstance(value, bytes):
|
||||||
# Всегда используем UTF-8 вместо ASCII
|
return value
|
||||||
encoding = encoding or 'utf-8'
|
|
||||||
if encoding.lower() == 'ascii':
|
# Если значение не строка и не байты, приводим к строке
|
||||||
encoding = 'utf-8'
|
if not isinstance(value, str):
|
||||||
return value.encode(encoding)
|
value = str(value)
|
||||||
|
|
||||||
|
# Всегда используем UTF-8 вместо ASCII
|
||||||
|
encoding = encoding or 'utf-8'
|
||||||
|
if encoding.lower() == 'ascii':
|
||||||
|
encoding = 'utf-8'
|
||||||
|
|
||||||
|
return value.encode(encoding)
|
||||||
|
except Exception as e:
|
||||||
|
# В случае ошибки логируем и пробуем максимально безопасный вариант
|
||||||
|
logging.getLogger(__name__).error(f"Error in patched_normalize_header_value: {e}. Value: {repr(value)}")
|
||||||
|
if isinstance(value, str):
|
||||||
|
return value.encode('utf-8', errors='ignore')
|
||||||
|
return b''
|
||||||
|
|
||||||
httpx._models._normalize_header_value = patched_normalize_header_value
|
httpx._models._normalize_header_value = patched_normalize_header_value
|
||||||
logging.getLogger(__name__).info("Applied patch for httpx header encoding on Windows")
|
logging.getLogger(__name__).info("Applied robust patch for httpx header encoding on Windows")
|
||||||
|
except ImportError:
|
||||||
|
logging.getLogger(__name__).warning("httpx module not found, patch skipped")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.getLogger(__name__).warning(f"Failed to apply httpx patch: {e}")
|
logging.getLogger(__name__).warning(f"Failed to apply httpx patch: {e}")
|
||||||
|
|
||||||
@@ -148,8 +165,10 @@ class OpenRouterIntegrationService(BaseIntegrationService):
|
|||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Ошибка генерации текста с помощью OpenRouter: {str(e)}")
|
error_msg = str(e)
|
||||||
return False, f"Ошибка генерации: {str(e)}", None
|
logger.error(f"Ошибка генерации текста с помощью OpenRouter: {error_msg}")
|
||||||
|
logger.error(traceback.format_exc())
|
||||||
|
return False, f"Ошибка генерации: {error_msg}", None
|
||||||
|
|
||||||
def generate_code(self,
|
def generate_code(self,
|
||||||
prompt: str,
|
prompt: str,
|
||||||
@@ -196,5 +215,7 @@ class OpenRouterIntegrationService(BaseIntegrationService):
|
|||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Ошибка генерации кода с помощью OpenRouter: {str(e)}")
|
error_msg = str(e)
|
||||||
return False, f"Ошибка генерации кода: {str(e)}", None
|
logger.error(f"Ошибка генерации кода с помощью OpenRouter: {error_msg}")
|
||||||
|
logger.error(traceback.format_exc())
|
||||||
|
return False, f"Ошибка генерации кода: {error_msg}", None
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import requests
|
||||||
from typing import Tuple
|
from typing import Tuple
|
||||||
from .base import MarketplaceService
|
from .base import MarketplaceService
|
||||||
|
|
||||||
@@ -5,16 +6,58 @@ from .base import MarketplaceService
|
|||||||
class WooCommerceService(MarketplaceService):
|
class WooCommerceService(MarketplaceService):
|
||||||
"""Сервис для работы с WooCommerce API"""
|
"""Сервис для работы с WooCommerce API"""
|
||||||
|
|
||||||
|
def _get_api_url(self) -> str:
|
||||||
|
"""Получить базовый URL для WooCommerce REST API"""
|
||||||
|
base = self.config.store_url.rstrip('/')
|
||||||
|
# WooCommerce REST API v3 endpoint
|
||||||
|
return f"{base}/wp-json/wc/v3/"
|
||||||
|
|
||||||
|
def _get_auth(self) -> tuple:
|
||||||
|
"""Получить кортеж для Basic Auth (consumer_key, consumer_secret)"""
|
||||||
|
return (self.config.consumer_key or '', self.config.consumer_secret or '')
|
||||||
|
|
||||||
def test_connection(self) -> Tuple[bool, str]:
|
def test_connection(self) -> Tuple[bool, str]:
|
||||||
"""Проверить соединение с WooCommerce API"""
|
"""
|
||||||
|
Проверить соединение с WooCommerce API.
|
||||||
|
|
||||||
|
Использует endpoint /wp-json/wc/v3/ для проверки.
|
||||||
|
Аутентификация через HTTP Basic Auth.
|
||||||
|
"""
|
||||||
if not self.config.store_url:
|
if not self.config.store_url:
|
||||||
return False, 'Не указан URL магазина'
|
return False, 'Не указан URL магазина'
|
||||||
|
|
||||||
if not self.config.consumer_key or not self.config.consumer_secret:
|
if not self.config.consumer_key or not self.config.consumer_secret:
|
||||||
return False, 'Не указаны ключи API'
|
return False, 'Не указаны ключи API'
|
||||||
|
|
||||||
# TODO: реализовать проверку соединения с WooCommerce API
|
url = self._get_api_url()
|
||||||
return True, 'Соединение успешно (заглушка)'
|
|
||||||
|
try:
|
||||||
|
# Пытаемся получить список товаров (limit=1) для проверки авторизации
|
||||||
|
# Это более надёжный способ проверки, чем просто обращение к корню API
|
||||||
|
response = requests.get(
|
||||||
|
f"{url}products",
|
||||||
|
params={'per_page': 1},
|
||||||
|
auth=self._get_auth(),
|
||||||
|
timeout=15
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
return True, 'Соединение установлено успешно'
|
||||||
|
elif response.status_code == 401:
|
||||||
|
return False, 'Неверные ключи API (Consumer Key/Secret)'
|
||||||
|
elif response.status_code == 403:
|
||||||
|
return False, 'Доступ запрещён. Проверьте права API ключа'
|
||||||
|
elif response.status_code == 404:
|
||||||
|
return False, 'WooCommerce REST API не найден. Проверьте, что WooCommerce установлен и активирован'
|
||||||
|
else:
|
||||||
|
return False, f'Ошибка соединения: HTTP {response.status_code}'
|
||||||
|
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
return False, 'Таймаут соединения (15 сек)'
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
|
return False, 'Не удалось подключиться к серверу. Проверьте URL магазина'
|
||||||
|
except Exception as e:
|
||||||
|
return False, f'Ошибка: {str(e)}'
|
||||||
|
|
||||||
def sync(self) -> Tuple[bool, str]:
|
def sync(self) -> Tuple[bool, str]:
|
||||||
"""Выполнить синхронизацию с WooCommerce"""
|
"""Выполнить синхронизацию с WooCommerce"""
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from .views import (
|
|||||||
get_integration_form_data,
|
get_integration_form_data,
|
||||||
test_integration_connection,
|
test_integration_connection,
|
||||||
RecommerceBatchSyncView,
|
RecommerceBatchSyncView,
|
||||||
|
get_openrouter_models,
|
||||||
)
|
)
|
||||||
|
|
||||||
app_name = 'integrations'
|
app_name = 'integrations'
|
||||||
@@ -22,4 +23,7 @@ urlpatterns = [
|
|||||||
|
|
||||||
# Синхронизация
|
# Синхронизация
|
||||||
path("recommerce/sync/", RecommerceBatchSyncView.as_view(), name="recommerce_sync"),
|
path("recommerce/sync/", RecommerceBatchSyncView.as_view(), name="recommerce_sync"),
|
||||||
|
|
||||||
|
# OpenRouter модели
|
||||||
|
path("openrouter/models/", get_openrouter_models, name="openrouter_models"),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from django.views.generic import TemplateView
|
from django.views.generic import TemplateView
|
||||||
from django.http import JsonResponse
|
from django.http import JsonResponse
|
||||||
from django.views.decorators.http import require_POST
|
from django.views.decorators.http import require_POST, require_GET
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
from user_roles.mixins import OwnerRequiredMixin
|
from user_roles.mixins import OwnerRequiredMixin
|
||||||
from .models import RecommerceIntegration, WooCommerceIntegration, GLMIntegration, OpenRouterIntegration
|
from .models import RecommerceIntegration, WooCommerceIntegration, GLMIntegration, OpenRouterIntegration
|
||||||
@@ -170,8 +173,8 @@ def get_integration_service(integration_id: str, instance):
|
|||||||
from .services.marketplaces.recommerce import RecommerceService
|
from .services.marketplaces.recommerce import RecommerceService
|
||||||
return RecommerceService(instance)
|
return RecommerceService(instance)
|
||||||
elif integration_id == 'woocommerce':
|
elif integration_id == 'woocommerce':
|
||||||
# TODO: WooCommerceService
|
from .services.marketplaces.woocommerce import WooCommerceService
|
||||||
return None
|
return WooCommerceService(instance)
|
||||||
elif integration_id == 'glm':
|
elif integration_id == 'glm':
|
||||||
from .services.ai_services.glm_service import GLMIntegrationService
|
from .services.ai_services.glm_service import GLMIntegrationService
|
||||||
return GLMIntegrationService(instance)
|
return GLMIntegrationService(instance)
|
||||||
@@ -181,6 +184,44 @@ def get_integration_service(integration_id: str, instance):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@require_GET
|
||||||
|
def get_openrouter_models(request):
|
||||||
|
"""
|
||||||
|
GET /settings/integrations/openrouter/models/
|
||||||
|
Возвращает список моделей OpenRouter (бесплатные сверху)
|
||||||
|
"""
|
||||||
|
import requests
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.get('https://openrouter.ai/api/v1/models', timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
|
||||||
|
models = data.get('data', [])
|
||||||
|
|
||||||
|
# Разделить на бесплатные и платные
|
||||||
|
free_models = []
|
||||||
|
paid_models = []
|
||||||
|
|
||||||
|
for model in models:
|
||||||
|
model_id = model.get('id', '')
|
||||||
|
model_name = model.get('name', model_id)
|
||||||
|
|
||||||
|
if ':free' in model_id:
|
||||||
|
free_models.append({'id': model_id, 'name': f"{model_name} (Бесплатная)"})
|
||||||
|
else:
|
||||||
|
paid_models.append({'id': model_id, 'name': model_name})
|
||||||
|
|
||||||
|
# Бесплатные сверху
|
||||||
|
all_models = free_models + paid_models
|
||||||
|
|
||||||
|
return JsonResponse({'models': all_models})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error fetching OpenRouter models: {e}")
|
||||||
|
return JsonResponse({'error': str(e)}, status=500)
|
||||||
|
|
||||||
|
|
||||||
class RecommerceBatchSyncView(TemplateView):
|
class RecommerceBatchSyncView(TemplateView):
|
||||||
"""
|
"""
|
||||||
API View для запуска массовой синхронизации с Recommerce.
|
API View для запуска массовой синхронизации с Recommerce.
|
||||||
@@ -363,7 +404,46 @@ def get_form_fields_meta(model):
|
|||||||
'label': getattr(field, 'verbose_name', field_name),
|
'label': getattr(field, 'verbose_name', field_name),
|
||||||
'help_text': getattr(field, 'help_text', ''),
|
'help_text': getattr(field, 'help_text', ''),
|
||||||
'required': not getattr(field, 'blank', True),
|
'required': not getattr(field, 'blank', True),
|
||||||
'type': 'text', # default
|
'type': 'password' if field_name == 'api_key' else 'text',
|
||||||
|
}
|
||||||
|
fields.append(field_info)
|
||||||
|
|
||||||
|
elif field_name == 'temperature':
|
||||||
|
field = model._meta.get_field(field_name)
|
||||||
|
field_info = {
|
||||||
|
'name': field_name,
|
||||||
|
'label': getattr(field, 'verbose_name', field_name),
|
||||||
|
'help_text': getattr(field, 'help_text', ''),
|
||||||
|
'required': not getattr(field, 'blank', True),
|
||||||
|
'type': 'select',
|
||||||
|
'choices': getattr(field, 'choices', [])
|
||||||
|
}
|
||||||
|
fields.append(field_info)
|
||||||
|
|
||||||
|
elif field_name == 'model_name':
|
||||||
|
field = model._meta.get_field(field_name)
|
||||||
|
field_info = {
|
||||||
|
'name': field_name,
|
||||||
|
'label': getattr(field, 'verbose_name', field_name),
|
||||||
|
'help_text': getattr(field, 'help_text', ''),
|
||||||
|
'required': not getattr(field, 'blank', True),
|
||||||
|
'type': 'select',
|
||||||
|
'dynamic_choices': True,
|
||||||
|
'choices_url': '/settings/integrations/openrouter/models/'
|
||||||
|
}
|
||||||
|
fields.append(field_info)
|
||||||
|
# Для WooCommerce показываем только базовые поля для подключения
|
||||||
|
elif model.__name__ == 'WooCommerceIntegration':
|
||||||
|
basic_fields = ['store_url', 'consumer_key', 'consumer_secret']
|
||||||
|
for field_name in editable_fields:
|
||||||
|
if field_name in basic_fields:
|
||||||
|
field = model._meta.get_field(field_name)
|
||||||
|
field_info = {
|
||||||
|
'name': field_name,
|
||||||
|
'label': getattr(field, 'verbose_name', field_name),
|
||||||
|
'help_text': getattr(field, 'help_text', ''),
|
||||||
|
'required': not getattr(field, 'blank', True),
|
||||||
|
'type': 'text',
|
||||||
}
|
}
|
||||||
|
|
||||||
# Определить тип поля
|
# Определить тип поля
|
||||||
@@ -371,21 +451,9 @@ def get_form_fields_meta(model):
|
|||||||
field_info['type'] = 'checkbox'
|
field_info['type'] = 'checkbox'
|
||||||
elif 'URLField' in field.__class__.__name__:
|
elif 'URLField' in field.__class__.__name__:
|
||||||
field_info['type'] = 'url'
|
field_info['type'] = 'url'
|
||||||
elif 'secret' in field_name.lower() or 'token' in field_name.lower() or 'key' in field_name.lower():
|
elif 'secret' in field_name.lower() or 'key' in field_name.lower():
|
||||||
field_info['type'] = 'password'
|
field_info['type'] = 'password'
|
||||||
|
|
||||||
fields.append(field_info)
|
|
||||||
elif field_name in ['model_name', 'temperature']:
|
|
||||||
field = model._meta.get_field(field_name)
|
|
||||||
field_info = {
|
|
||||||
'name': field_name,
|
|
||||||
'label': getattr(field, 'verbose_name', field_name),
|
|
||||||
'help_text': getattr(field, 'help_text', ''),
|
|
||||||
'required': not getattr(field, 'blank', True),
|
|
||||||
'type': 'select', # dropdown
|
|
||||||
'choices': getattr(field, 'choices', [])
|
|
||||||
}
|
|
||||||
|
|
||||||
fields.append(field_info)
|
fields.append(field_info)
|
||||||
else:
|
else:
|
||||||
# Для других интеграций - все редактируемые поля
|
# Для других интеграций - все редактируемые поля
|
||||||
|
|||||||
@@ -667,7 +667,16 @@ class ShowcaseItem(models.Model):
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
self.status = 'in_cart'
|
self.status = 'in_cart'
|
||||||
self.locked_by_user = user
|
|
||||||
|
# Проверяем тип пользователя - locked_by_user только для CustomUser
|
||||||
|
from accounts.models import CustomUser
|
||||||
|
if isinstance(user, CustomUser):
|
||||||
|
self.locked_by_user = user
|
||||||
|
else:
|
||||||
|
# Для PlatformAdmin и других типов пользователей поле оставляем пустым
|
||||||
|
# Блокировка будет работать через cart_session_id
|
||||||
|
self.locked_by_user = None
|
||||||
|
|
||||||
self.cart_lock_expires_at = timezone.now() + timedelta(minutes=duration_minutes)
|
self.cart_lock_expires_at = timezone.now() + timedelta(minutes=duration_minutes)
|
||||||
self.cart_session_id = session_id
|
self.cart_session_id = session_id
|
||||||
self.save(update_fields=['status', 'locked_by_user', 'cart_lock_expires_at', 'cart_session_id', 'updated_at'])
|
self.save(update_fields=['status', 'locked_by_user', 'cart_lock_expires_at', 'cart_session_id', 'updated_at'])
|
||||||
|
|||||||
@@ -35,8 +35,34 @@ class SaleProcessor:
|
|||||||
"""
|
"""
|
||||||
# Определяем цену продажи из заказа или из товара
|
# Определяем цену продажи из заказа или из товара
|
||||||
if order and reservation.order_item:
|
if order and reservation.order_item:
|
||||||
# Цена из OrderItem
|
item = reservation.order_item
|
||||||
sale_price = reservation.order_item.price
|
# Цена за единицу с учётом всех скидок (позиция + заказ)
|
||||||
|
item_subtotal = Decimal(str(item.price)) * Decimal(str(item.quantity))
|
||||||
|
|
||||||
|
# Скидка на позицию
|
||||||
|
item_discount = Decimal(str(item.discount_amount)) if item.discount_amount else Decimal('0')
|
||||||
|
|
||||||
|
# Скидка на заказ (распределяется пропорционально доле позиции в заказе)
|
||||||
|
# Вычисляем как разницу между subtotal и total_amount (так как discount_amount может быть 0)
|
||||||
|
order_total = order.subtotal if hasattr(order, 'subtotal') else Decimal('0')
|
||||||
|
# Скидка = subtotal - (total_amount - delivery) (вычитаем доставку, если есть)
|
||||||
|
delivery_cost = Decimal(str(order.delivery.cost)) if hasattr(order, 'delivery') and order.delivery else Decimal('0')
|
||||||
|
order_discount = (order_total - (Decimal(str(order.total_amount)) - delivery_cost)) if order_total > 0 else Decimal('0')
|
||||||
|
|
||||||
|
total_discount = item_discount + order_discount
|
||||||
|
if total_discount and item.quantity > 0:
|
||||||
|
# Распределяем общую скидку пропорционально доле позиции
|
||||||
|
item_order_discount = order_discount * (item_subtotal / order_total) if order_total > 0 else Decimal('0')
|
||||||
|
total_discount = item_discount + item_order_discount
|
||||||
|
price_with_discount = (item_subtotal - total_discount) / Decimal(str(item.quantity))
|
||||||
|
else:
|
||||||
|
price_with_discount = Decimal(str(item.price))
|
||||||
|
|
||||||
|
# Пересчитываем цену в базовые единицы
|
||||||
|
if item.sales_unit and item.conversion_factor_snapshot:
|
||||||
|
sale_price = price_with_discount * item.conversion_factor_snapshot
|
||||||
|
else:
|
||||||
|
sale_price = price_with_discount
|
||||||
else:
|
else:
|
||||||
# Цена из товара
|
# Цена из товара
|
||||||
sale_price = reservation.product.actual_price or Decimal('0')
|
sale_price = reservation.product.actual_price or Decimal('0')
|
||||||
|
|||||||
@@ -162,8 +162,6 @@ class ShowcaseManager:
|
|||||||
Raises:
|
Raises:
|
||||||
IntegrityError: если экземпляр уже был продан (защита на уровне БД)
|
IntegrityError: если экземпляр уже был продан (защита на уровне БД)
|
||||||
"""
|
"""
|
||||||
from inventory.services.sale_processor import SaleProcessor
|
|
||||||
|
|
||||||
sold_count = 0
|
sold_count = 0
|
||||||
order = order_item.order
|
order = order_item.order
|
||||||
|
|
||||||
@@ -207,17 +205,9 @@ class ShowcaseManager:
|
|||||||
|
|
||||||
# Сначала устанавливаем order_item для правильного определения цены
|
# Сначала устанавливаем order_item для правильного определения цены
|
||||||
reservation.order_item = order_item
|
reservation.order_item = order_item
|
||||||
reservation.save()
|
# ВАЖНО: Мы НЕ создаём продажу (Sale) здесь и НЕ меняем статус на 'converted_to_sale'.
|
||||||
|
# Это сделает сигнал create_sale_on_order_completion автоматически.
|
||||||
# Теперь создаём продажу с правильной ценой из OrderItem
|
# Таким образом обеспечивается единая точка создания продаж для всех типов товаров.
|
||||||
SaleProcessor.create_sale_from_reservation(
|
|
||||||
reservation=reservation,
|
|
||||||
order=order
|
|
||||||
)
|
|
||||||
|
|
||||||
# Обновляем статус резерва
|
|
||||||
reservation.status = 'converted_to_sale'
|
|
||||||
reservation.converted_at = timezone.now()
|
|
||||||
reservation.save()
|
reservation.save()
|
||||||
|
|
||||||
sold_count += 1
|
sold_count += 1
|
||||||
@@ -666,6 +656,113 @@ class ShowcaseManager:
|
|||||||
'message': f'Ошибка разбора: {str(e)}'
|
'message': f'Ошибка разбора: {str(e)}'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def write_off_from_showcase(showcase_item, reason='spoilage', notes=None, created_by=None):
|
||||||
|
"""
|
||||||
|
Списывает экземпляр витринного комплекта:
|
||||||
|
1. Создаёт документ списания с компонентами комплекта
|
||||||
|
2. Преобразует резервы комплекта в позиции документа списания
|
||||||
|
3. Помечает экземпляр как разобранный
|
||||||
|
|
||||||
|
Args:
|
||||||
|
showcase_item: ShowcaseItem - экземпляр для списания
|
||||||
|
reason: str - причина списания (spoilage по умолчанию)
|
||||||
|
notes: str - примечания
|
||||||
|
created_by: User - пользователь
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: {
|
||||||
|
'success': bool,
|
||||||
|
'document_id': int,
|
||||||
|
'document_number': str,
|
||||||
|
'items_count': int,
|
||||||
|
'message': str,
|
||||||
|
'error': str (при ошибке)
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
from inventory.services.writeoff_document_service import WriteOffDocumentService
|
||||||
|
|
||||||
|
# Проверка статуса
|
||||||
|
if showcase_item.status == 'sold':
|
||||||
|
return {
|
||||||
|
'success': False,
|
||||||
|
'document_id': None,
|
||||||
|
'message': 'Нельзя списать проданный экземпляр'
|
||||||
|
}
|
||||||
|
|
||||||
|
if showcase_item.status == 'dismantled':
|
||||||
|
return {
|
||||||
|
'success': False,
|
||||||
|
'document_id': None,
|
||||||
|
'message': 'Экземпляр уже разобран'
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
with transaction.atomic():
|
||||||
|
warehouse = showcase_item.showcase.warehouse
|
||||||
|
product_kit = showcase_item.product_kit
|
||||||
|
|
||||||
|
# Создаём документ списания (черновик)
|
||||||
|
document = WriteOffDocumentService.create_document(
|
||||||
|
warehouse=warehouse,
|
||||||
|
date=timezone.now().date(),
|
||||||
|
notes=f'Списание витринного комплекта: {product_kit.name}',
|
||||||
|
created_by=created_by
|
||||||
|
)
|
||||||
|
|
||||||
|
# Получаем резервы этого экземпляра
|
||||||
|
reservations = Reservation.objects.filter(
|
||||||
|
showcase_item=showcase_item,
|
||||||
|
status='reserved'
|
||||||
|
).select_related('product')
|
||||||
|
|
||||||
|
items_count = 0
|
||||||
|
|
||||||
|
for reservation in reservations:
|
||||||
|
# Добавляем позицию в документ списания
|
||||||
|
# Используем add_item без создания резерва (меняем статус существующего)
|
||||||
|
from inventory.models import WriteOffDocumentItem
|
||||||
|
|
||||||
|
item = WriteOffDocumentItem.objects.create(
|
||||||
|
document=document,
|
||||||
|
product=reservation.product,
|
||||||
|
quantity=reservation.quantity,
|
||||||
|
reason=reason,
|
||||||
|
notes=notes
|
||||||
|
)
|
||||||
|
|
||||||
|
# Привязываем существующий резерв к позиции документа
|
||||||
|
reservation.writeoff_document_item = item
|
||||||
|
reservation.status = 'converted_to_writeoff'
|
||||||
|
reservation.converted_at = timezone.now()
|
||||||
|
reservation.save(update_fields=['writeoff_document_item', 'status', 'converted_at'])
|
||||||
|
|
||||||
|
items_count += 1
|
||||||
|
|
||||||
|
# Помечаем экземпляр как разобранный
|
||||||
|
showcase_item.status = 'dismantled'
|
||||||
|
showcase_item.save(update_fields=['status'])
|
||||||
|
|
||||||
|
# Помечаем шаблон комплекта как снятый
|
||||||
|
if product_kit.status != 'discontinued':
|
||||||
|
product_kit.status = 'discontinued'
|
||||||
|
product_kit.save(update_fields=['status'])
|
||||||
|
|
||||||
|
return {
|
||||||
|
'success': True,
|
||||||
|
'document_id': document.id,
|
||||||
|
'document_number': document.document_number,
|
||||||
|
'items_count': items_count,
|
||||||
|
'message': f'Создан документ {document.document_number} с {items_count} позициями'
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
'success': False,
|
||||||
|
'document_id': None,
|
||||||
|
'message': f'Ошибка списания: {str(e)}'
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_showcase_items_for_pos(showcase=None):
|
def get_showcase_items_for_pos(showcase=None):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
Подключаются при создании, изменении и удалении заказов.
|
Подключаются при создании, изменении и удалении заказов.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import threading
|
||||||
from django.db.models.signals import post_save, pre_delete, post_delete, pre_save
|
from django.db.models.signals import post_save, pre_delete, post_delete, pre_save
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
@@ -19,6 +20,26 @@ from inventory.services import SaleProcessor
|
|||||||
from inventory.services.batch_manager import StockBatchManager
|
from inventory.services.batch_manager import StockBatchManager
|
||||||
# InventoryProcessor больше не используется в сигналах - обработка вызывается явно через view
|
# InventoryProcessor больше не используется в сигналах - обработка вызывается явно через view
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Thread-local storage для временных флагов управления сигналами
|
||||||
|
# ============================================================================
|
||||||
|
_skip_sale_creation = threading.local()
|
||||||
|
|
||||||
|
|
||||||
|
def skip_sale_creation():
|
||||||
|
"""Установить флаг для пропуска создания Sale в сигнале."""
|
||||||
|
_skip_sale_creation.value = True
|
||||||
|
|
||||||
|
|
||||||
|
def reset_sale_creation():
|
||||||
|
"""Сбросить флаг пропуска создания Sale."""
|
||||||
|
_skip_sale_creation.value = False
|
||||||
|
|
||||||
|
|
||||||
|
def is_skip_sale_creation():
|
||||||
|
"""Проверить, установлен ли флаг пропуска создания Sale."""
|
||||||
|
return getattr(_skip_sale_creation, 'value', False)
|
||||||
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# pre_save сигнал для сохранения предыдущего статуса Order
|
# pre_save сигнал для сохранения предыдущего статуса Order
|
||||||
@@ -201,9 +222,14 @@ def reserve_stock_on_item_create(sender, instance, created, **kwargs):
|
|||||||
|
|
||||||
for kit_item in instance.kit_snapshot.items.select_related('original_product'):
|
for kit_item in instance.kit_snapshot.items.select_related('original_product'):
|
||||||
if kit_item.original_product:
|
if kit_item.original_product:
|
||||||
# Суммируем количество: qty компонента * qty комплектов в заказе
|
# Рассчитываем количество одного компонента в базовых единицах
|
||||||
|
component_qty_base = kit_item.quantity
|
||||||
|
if kit_item.conversion_factor and kit_item.conversion_factor > 0:
|
||||||
|
component_qty_base = kit_item.quantity / kit_item.conversion_factor
|
||||||
|
|
||||||
|
# Суммируем количество: qty компонента (base) * qty комплектов в заказе
|
||||||
product_quantities[kit_item.original_product_id] += (
|
product_quantities[kit_item.original_product_id] += (
|
||||||
kit_item.quantity * Decimal(str(instance.quantity))
|
component_qty_base * Decimal(str(instance.quantity))
|
||||||
)
|
)
|
||||||
|
|
||||||
# Создаём по одному резерву на каждый уникальный товар
|
# Создаём по одному резерву на каждый уникальный товар
|
||||||
@@ -278,10 +304,22 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
3. Для каждого товара создаем Sale (автоматический FIFO-список)
|
3. Для каждого товара создаем Sale (автоматический FIFO-список)
|
||||||
4. ТОЛЬКО после успешного создания Sale обновляем резервы на 'converted_to_sale'
|
4. ТОЛЬКО после успешного создания Sale обновляем резервы на 'converted_to_sale'
|
||||||
5. Обновляем флаг is_returned
|
5. Обновляем флаг is_returned
|
||||||
|
|
||||||
|
ПРИМЕЧАНИЕ: Если у Order установлен атрибут skip_sale_creation=True,
|
||||||
|
создание Sale пропускается (используется в POS для создания Sale после применения скидок).
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# === ПРОВЕРКА: Пропуск создания Sale по флагу ===
|
||||||
|
# Используется в POS checkout, где Sale создаётся явно после применения скидок
|
||||||
|
if is_skip_sale_creation():
|
||||||
|
logger.info(
|
||||||
|
f"ℹ️ Заказ {instance.order_number}: skip_sale_creation=True (thread-local), "
|
||||||
|
f"пропускаем автоматическое создание Sale"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
if created:
|
if created:
|
||||||
return # Только для обновлений
|
return # Только для обновлений
|
||||||
|
|
||||||
@@ -325,16 +363,22 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
if not is_positive_end:
|
if not is_positive_end:
|
||||||
return # Только для положительных финальных статусов (completed и т.п.)
|
return # Только для положительных финальных статусов (completed и т.п.)
|
||||||
|
|
||||||
|
# === ЗАЩИТА ОТ ПРЕЖДЕВРЕМЕННОГО СОЗДАНИЯ SALE ===
|
||||||
|
# Проверяем, есть ли уже Sale для этого заказа
|
||||||
|
if Sale.objects.filter(order=instance).exists():
|
||||||
|
logger.info(f"Заказ {instance.order_number}: Sale уже существуют, пропускаем")
|
||||||
|
update_is_returned_flag(instance)
|
||||||
|
return
|
||||||
|
|
||||||
# === ЗАЩИТА ОТ RACE CONDITION: Проверяем предыдущий статус ===
|
# === ЗАЩИТА ОТ RACE CONDITION: Проверяем предыдущий статус ===
|
||||||
# Если уже были в completed и снова переходим в completed (например completed → draft → completed),
|
# Если уже были в completed и снова переходим в completed (например completed → draft → completed),
|
||||||
# проверяем наличие Sale чтобы избежать дублирования
|
# проверяем наличие Sale чтобы избежать дублирования
|
||||||
previous_status = getattr(instance, '_previous_status', None)
|
previous_status = getattr(instance, '_previous_status', None)
|
||||||
if previous_status and previous_status.is_positive_end:
|
if previous_status and previous_status.is_positive_end:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"🔄 Заказ {instance.order_number}: повторный переход в положительный статус "
|
f"Заказ {instance.order_number}: повторный переход в положительный статус "
|
||||||
f"({previous_status.name} → {instance.status.name}). Проверяем Sale..."
|
f"({previous_status.name} → {instance.status.name}). Проверяем Sale..."
|
||||||
)
|
)
|
||||||
# Проверяем есть ли уже Sale
|
|
||||||
if Sale.objects.filter(order=instance).exists():
|
if Sale.objects.filter(order=instance).exists():
|
||||||
logger.info(
|
logger.info(
|
||||||
f"✓ Заказ {instance.order_number}: Sale уже существуют, пропускаем создание"
|
f"✓ Заказ {instance.order_number}: Sale уже существуют, пропускаем создание"
|
||||||
@@ -342,15 +386,6 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
update_is_returned_flag(instance)
|
update_is_returned_flag(instance)
|
||||||
return
|
return
|
||||||
|
|
||||||
# Защита от повторного списания: проверяем, не созданы ли уже Sale для этого заказа
|
|
||||||
if Sale.objects.filter(order=instance).exists():
|
|
||||||
# Продажи уже созданы — просто обновляем флаг is_returned и выходим
|
|
||||||
logger.info(
|
|
||||||
f"✓ Заказ {instance.order_number}: Sale уже существуют (проверка до создания)"
|
|
||||||
)
|
|
||||||
update_is_returned_flag(instance)
|
|
||||||
return
|
|
||||||
|
|
||||||
# Проверяем наличие резервов для этого заказа
|
# Проверяем наличие резервов для этого заказа
|
||||||
# Ищем резервы в статусах 'reserved' (новые) и 'released' (после отката)
|
# Ищем резервы в статусах 'reserved' (новые) и 'released' (после отката)
|
||||||
# Исключаем уже обработанные 'converted_to_sale'
|
# Исключаем уже обработанные 'converted_to_sale'
|
||||||
@@ -419,12 +454,65 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# === РАСЧЕТ ЦЕНЫ ===
|
||||||
|
# Рассчитываем фактическую стоимость продажи всего комплекта с учетом скидок
|
||||||
|
# 1. Базовая стоимость позиции
|
||||||
|
item_subtotal = Decimal(str(item.price)) * Decimal(str(item.quantity))
|
||||||
|
|
||||||
|
# 2. Скидки
|
||||||
|
item_discount = Decimal(str(item.discount_amount)) if item.discount_amount is not None else Decimal('0')
|
||||||
|
|
||||||
|
# Скидка на заказ (распределенная)
|
||||||
|
instance.refresh_from_db()
|
||||||
|
order_total = instance.subtotal if hasattr(instance, 'subtotal') else Decimal('0')
|
||||||
|
delivery_cost = Decimal(str(instance.delivery.cost)) if hasattr(instance, 'delivery') and instance.delivery else Decimal('0')
|
||||||
|
order_discount_amount = (order_total - (Decimal(str(instance.total_amount)) - delivery_cost)) if order_total > 0 else Decimal('0')
|
||||||
|
|
||||||
|
if order_total > 0 and order_discount_amount > 0:
|
||||||
|
item_order_discount = order_discount_amount * (item_subtotal / order_total)
|
||||||
|
else:
|
||||||
|
item_order_discount = Decimal('0')
|
||||||
|
|
||||||
|
kit_net_total = item_subtotal - item_discount - item_order_discount
|
||||||
|
if kit_net_total < 0:
|
||||||
|
kit_net_total = Decimal('0')
|
||||||
|
|
||||||
|
# 3. Суммарная каталожная стоимость всех компонентов (для пропорции)
|
||||||
|
total_catalog_price = Decimal('0')
|
||||||
|
for reservation in kit_reservations:
|
||||||
|
qty = reservation.quantity_base or reservation.quantity
|
||||||
|
price = reservation.product.actual_price or Decimal('0')
|
||||||
|
total_catalog_price += price * qty
|
||||||
|
|
||||||
|
# 4. Коэффициент распределения
|
||||||
|
if total_catalog_price > 0:
|
||||||
|
ratio = kit_net_total / total_catalog_price
|
||||||
|
else:
|
||||||
|
# Если каталожная цена 0, распределяем просто по количеству или 0
|
||||||
|
ratio = Decimal('0')
|
||||||
|
|
||||||
# Создаем Sale для каждого компонента комплекта
|
# Создаем Sale для каждого компонента комплекта
|
||||||
for reservation in kit_reservations:
|
for reservation in kit_reservations:
|
||||||
try:
|
try:
|
||||||
# Рассчитываем цену продажи компонента пропорционально цене комплекта
|
# Рассчитываем цену продажи компонента пропорционально
|
||||||
# Используем actual_price компонента как цену продажи
|
catalog_price = reservation.product.actual_price or Decimal('0')
|
||||||
component_sale_price = reservation.product.actual_price
|
|
||||||
|
if ratio > 0:
|
||||||
|
# Распределяем реальную выручку
|
||||||
|
component_sale_price = catalog_price * ratio
|
||||||
|
else:
|
||||||
|
# Если выручка 0 или каталожные цены 0
|
||||||
|
if total_catalog_price == 0 and kit_net_total > 0:
|
||||||
|
# Крайний случай: товаров на 0 руб, а продали за деньги (услуга?)
|
||||||
|
# Распределяем равномерно
|
||||||
|
count = kit_reservations.count()
|
||||||
|
component_qty = reservation.quantity_base or reservation.quantity
|
||||||
|
if count > 0 and component_qty > 0:
|
||||||
|
component_sale_price = (kit_net_total / count) / component_qty
|
||||||
|
else:
|
||||||
|
component_sale_price = Decimal('0')
|
||||||
|
else:
|
||||||
|
component_sale_price = Decimal('0')
|
||||||
|
|
||||||
sale = SaleProcessor.create_sale(
|
sale = SaleProcessor.create_sale(
|
||||||
product=reservation.product,
|
product=reservation.product,
|
||||||
@@ -437,7 +525,8 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
sales_created.append(sale)
|
sales_created.append(sale)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"✓ Sale создан для компонента комплекта '{kit.name}': "
|
f"✓ Sale создан для компонента комплекта '{kit.name}': "
|
||||||
f"{reservation.product.name} - {reservation.quantity_base or reservation.quantity} шт. (базовых единиц)"
|
f"{reservation.product.name} - {reservation.quantity_base or reservation.quantity} шт. "
|
||||||
|
f"(цена: {component_sale_price})"
|
||||||
)
|
)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
logger.error(
|
logger.error(
|
||||||
@@ -480,12 +569,60 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
f"Используем quantity_in_base_units: {sale_quantity}"
|
f"Используем quantity_in_base_units: {sale_quantity}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Цена за единицу с учётом всех скидок (позиция + заказ)
|
||||||
|
item_subtotal = Decimal(str(item.price)) * Decimal(str(item.quantity))
|
||||||
|
|
||||||
|
# Скидка на позицию
|
||||||
|
item_discount = Decimal(str(item.discount_amount)) if item.discount_amount is not None else Decimal('0')
|
||||||
|
|
||||||
|
# Скидка на заказ (распределяется пропорционально доле позиции в заказе)
|
||||||
|
# ВАЖНО: Обновляем Order из БД, чтобы получить актуальный total_amount после применения скидок
|
||||||
|
instance.refresh_from_db()
|
||||||
|
order_total = instance.subtotal if hasattr(instance, 'subtotal') else Decimal('0')
|
||||||
|
# Скидка = subtotal - (total_amount - delivery) (вычитаем доставку, если есть)
|
||||||
|
delivery_cost = Decimal(str(instance.delivery.cost)) if hasattr(instance, 'delivery') and instance.delivery else Decimal('0')
|
||||||
|
order_discount_amount = (order_total - (Decimal(str(instance.total_amount)) - delivery_cost)) if order_total > 0 else Decimal('0')
|
||||||
|
|
||||||
|
if order_total > 0 and order_discount_amount > 0:
|
||||||
|
# Пропорциональная часть скидки заказа для этой позиции
|
||||||
|
item_order_discount = order_discount_amount * (item_subtotal / order_total)
|
||||||
|
else:
|
||||||
|
item_order_discount = Decimal('0')
|
||||||
|
|
||||||
|
total_discount = item_discount + item_order_discount
|
||||||
|
|
||||||
|
if total_discount and item.quantity > 0:
|
||||||
|
price_with_discount = (item_subtotal - total_discount) / Decimal(str(item.quantity))
|
||||||
|
else:
|
||||||
|
price_with_discount = Decimal(str(item.price))
|
||||||
|
|
||||||
|
# Пересчитываем цену в базовые единицы
|
||||||
|
if item.sales_unit and item.conversion_factor_snapshot:
|
||||||
|
base_price = price_with_discount * item.conversion_factor_snapshot
|
||||||
|
else:
|
||||||
|
base_price = price_with_discount
|
||||||
|
|
||||||
|
# LOGGING DEBUG INFO
|
||||||
|
# print(f"DEBUG SALE PRICE CALCULATION for Item #{item.id} ({product.name}):")
|
||||||
|
# print(f" Price: {item.price}, Qty: {item.quantity}, Subtotal: {item_subtotal}")
|
||||||
|
# print(f" Item Discount: {item_discount}, Order Discount Share: {item_order_discount}, Total Discount: {total_discount}")
|
||||||
|
# print(f" Price w/ Discount: {price_with_discount}")
|
||||||
|
# print(f" Sales Unit: {item.sales_unit}, Conversion: {item.conversion_factor_snapshot}")
|
||||||
|
# print(f" FINAL BASE PRICE: {base_price}")
|
||||||
|
# print(f" Sales Unit Object: {item.sales_unit}")
|
||||||
|
# if item.sales_unit:
|
||||||
|
# print(f" Sales Unit Conversion: {item.sales_unit.conversion_factor}")
|
||||||
|
|
||||||
|
logger.info(f"DEBUG SALE PRICE CALCULATION for Item #{item.id} ({product.name}):")
|
||||||
|
logger.info(f" Price: {item.price}, Qty: {item.quantity}, Subtotal: {item_subtotal}")
|
||||||
|
logger.info(f" FINAL BASE PRICE: {base_price}")
|
||||||
|
|
||||||
# Создаем Sale (с автоматическим FIFO-списанием)
|
# Создаем Sale (с автоматическим FIFO-списанием)
|
||||||
sale = SaleProcessor.create_sale(
|
sale = SaleProcessor.create_sale(
|
||||||
product=product,
|
product=product,
|
||||||
warehouse=warehouse,
|
warehouse=warehouse,
|
||||||
quantity=sale_quantity,
|
quantity=sale_quantity,
|
||||||
sale_price=Decimal(str(item.price)),
|
sale_price=base_price,
|
||||||
order=instance,
|
order=instance,
|
||||||
document_number=instance.order_number,
|
document_number=instance.order_number,
|
||||||
sales_unit=item.sales_unit # Передаем sales_unit в Sale
|
sales_unit=item.sales_unit # Передаем sales_unit в Sale
|
||||||
@@ -1801,8 +1938,13 @@ def update_kit_prices_on_product_change(sender, instance, created, **kwargs):
|
|||||||
if created:
|
if created:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Находим все KitItem с этим товаром
|
# Находим все KitItem с этим товаром, исключая временные (витринные) комплекты
|
||||||
kit_items = KitItem.objects.filter(product=instance)
|
# Витринные комплекты имеют зафиксированную цену и не должны обновляться автоматически
|
||||||
|
kit_items = KitItem.objects.filter(
|
||||||
|
product=instance
|
||||||
|
).select_related('kit').exclude(
|
||||||
|
kit__is_temporary=True
|
||||||
|
)
|
||||||
|
|
||||||
if not kit_items.exists():
|
if not kit_items.exists():
|
||||||
return # Товар не используется в комплектах
|
return # Товар не используется в комплектах
|
||||||
|
|||||||
@@ -394,14 +394,21 @@
|
|||||||
const emptyMessage = document.getElementById('empty-lines-message');
|
const emptyMessage = document.getElementById('empty-lines-message');
|
||||||
if (emptyMessage) emptyMessage.remove();
|
if (emptyMessage) emptyMessage.remove();
|
||||||
|
|
||||||
// Добавляем новую строку
|
// Добавляем новую строку в начало таблицы
|
||||||
const newRow = self.createLineRow(data.line);
|
const newRow = self.createLineRow(data.line);
|
||||||
tbody.appendChild(newRow);
|
tbody.insertBefore(newRow, tbody.firstChild);
|
||||||
|
|
||||||
// Включаем кнопку завершения
|
// Включаем кнопку завершения
|
||||||
const completeBtn = document.getElementById('complete-inventory-btn');
|
const completeBtn = document.getElementById('complete-inventory-btn');
|
||||||
if (completeBtn) completeBtn.disabled = false;
|
if (completeBtn) completeBtn.disabled = false;
|
||||||
|
|
||||||
|
// Фокус на поле ввода количества в новой строке
|
||||||
|
const quantityInput = newRow.querySelector('.quantity-fact-input');
|
||||||
|
if (quantityInput) {
|
||||||
|
quantityInput.focus();
|
||||||
|
quantityInput.select();
|
||||||
|
}
|
||||||
|
|
||||||
this.showNotification('Товар добавлен', 'success');
|
this.showNotification('Товар добавлен', 'success');
|
||||||
} else {
|
} else {
|
||||||
this.showNotification('Ошибка: ' + (data.error || 'Не удалось добавить товар'), 'error');
|
this.showNotification('Ошибка: ' + (data.error || 'Не удалось добавить товар'), 'error');
|
||||||
|
|||||||
@@ -688,7 +688,13 @@
|
|||||||
<td><span class="badge bg-info">{{ doc.get_receipt_type_display }}</span></td>
|
<td><span class="badge bg-info">{{ doc.get_receipt_type_display }}</span></td>
|
||||||
<td class="text-muted-small">{{ doc.date|date:"d.m.Y" }}</td>
|
<td class="text-muted-small">{{ doc.date|date:"d.m.Y" }}</td>
|
||||||
<td>{{ doc.supplier_name|default:"-" }}</td>
|
<td>{{ doc.supplier_name|default:"-" }}</td>
|
||||||
<td class="text-muted-small">{{ doc.created_by.name|default:doc.created_by.email|default:"-" }}</td>
|
<td class="text-muted-small">
|
||||||
|
{% if doc.created_by %}
|
||||||
|
{{ doc.created_by.name|default:doc.created_by.email }}
|
||||||
|
{% else %}
|
||||||
|
-
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
<td class="text-muted-small">
|
<td class="text-muted-small">
|
||||||
{% if doc.confirmed_by %}
|
{% if doc.confirmed_by %}
|
||||||
{{ doc.confirmed_by.name|default:doc.confirmed_by.email }} ({{ doc.confirmed_at|date:"d.m H:i" }})
|
{{ doc.confirmed_by.name|default:doc.confirmed_by.email }} ({{ doc.confirmed_at|date:"d.m H:i" }})
|
||||||
|
|||||||
@@ -20,19 +20,22 @@
|
|||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<!-- Основной контент - одна колонка -->
|
<!-- Основной контент - одна колонка -->
|
||||||
<div class="col-12">
|
<div class="col-12">
|
||||||
<!-- Информация о документе -->
|
<!-- Информация о документе - свернута по умолчанию -->
|
||||||
<div class="card border-0 shadow-sm mb-3">
|
<div class="card border-0 shadow-sm mb-3">
|
||||||
<div class="card-header bg-light py-3 d-flex justify-content-between align-items-center">
|
<div class="card-header bg-light py-2 d-flex justify-content-between align-items-center">
|
||||||
<h5 class="mb-0">
|
<button class="btn btn-outline-primary btn-sm d-flex align-items-center gap-2" type="button" data-bs-toggle="collapse" data-bs-target="#document-info-collapse" aria-expanded="false" aria-controls="document-info-collapse">
|
||||||
<i class="bi bi-file-earmark-plus me-2"></i>{{ document.document_number }}
|
<i class="bi bi-chevron-down" id="document-info-collapse-icon"></i>
|
||||||
{% if document.status == 'draft' %}
|
<span>
|
||||||
<span class="badge bg-warning text-dark ms-2">Черновик</span>
|
<i class="bi bi-file-earmark-plus me-2"></i>{{ document.document_number }}
|
||||||
{% elif document.status == 'confirmed' %}
|
{% if document.status == 'draft' %}
|
||||||
<span class="badge bg-success ms-2">Проведён</span>
|
<span class="badge bg-warning text-dark ms-2">Черновик</span>
|
||||||
{% elif document.status == 'cancelled' %}
|
{% elif document.status == 'confirmed' %}
|
||||||
<span class="badge bg-secondary ms-2">Отменён</span>
|
<span class="badge bg-success ms-2">Проведён</span>
|
||||||
{% endif %}
|
{% elif document.status == 'cancelled' %}
|
||||||
</h5>
|
<span class="badge bg-secondary ms-2">Отменён</span>
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
{% if document.can_edit %}
|
{% if document.can_edit %}
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
<form method="post" action="{% url 'inventory:incoming-confirm' document.pk %}" class="d-inline">
|
<form method="post" action="{% url 'inventory:incoming-confirm' document.pk %}" class="d-inline">
|
||||||
@@ -50,65 +53,67 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="collapse" id="document-info-collapse">
|
||||||
<div class="row mb-3">
|
<div class="card-body">
|
||||||
<div class="col-md-3">
|
<div class="row mb-3">
|
||||||
<p class="text-muted small mb-1">Склад</p>
|
<div class="col-md-3">
|
||||||
<p class="fw-semibold">{{ document.warehouse.name }}</p>
|
<p class="text-muted small mb-1">Склад</p>
|
||||||
|
<p class="fw-semibold">{{ document.warehouse.name }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<p class="text-muted small mb-1">Дата документа</p>
|
||||||
|
<p class="fw-semibold">{{ document.date|date:"d.m.Y" }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<p class="text-muted small mb-1">Тип поступления</p>
|
||||||
|
<p class="fw-semibold">{{ document.get_receipt_type_display }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<p class="text-muted small mb-1">Создан</p>
|
||||||
|
<p class="fw-semibold">{{ document.created_at|date:"d.m.Y H:i" }}</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-3">
|
|
||||||
<p class="text-muted small mb-1">Дата документа</p>
|
|
||||||
<p class="fw-semibold">{{ document.date|date:"d.m.Y" }}</p>
|
|
||||||
</div>
|
|
||||||
<div class="col-md-3">
|
|
||||||
<p class="text-muted small mb-1">Тип поступления</p>
|
|
||||||
<p class="fw-semibold">{{ document.get_receipt_type_display }}</p>
|
|
||||||
</div>
|
|
||||||
<div class="col-md-3">
|
|
||||||
<p class="text-muted small mb-1">Создан</p>
|
|
||||||
<p class="fw-semibold">{{ document.created_at|date:"d.m.Y H:i" }}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{% if document.supplier_name %}
|
{% if document.supplier_name %}
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<p class="text-muted small mb-1">Поставщик</p>
|
<p class="text-muted small mb-1">Поставщик</p>
|
||||||
<p class="fw-semibold">{{ document.supplier_name }}</p>
|
<p class="fw-semibold">{{ document.supplier_name }}</p>
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% if document.notes %}
|
|
||||||
<div class="mb-3">
|
|
||||||
<p class="text-muted small mb-1">Примечания</p>
|
|
||||||
<p>{{ document.notes }}</p>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
{% if document.confirmed_at %}
|
|
||||||
<div class="row">
|
|
||||||
<div class="col-md-6">
|
|
||||||
<p class="text-muted small mb-1">Проведён</p>
|
|
||||||
<p class="fw-semibold">{{ document.confirmed_at|date:"d.m.Y H:i" }}</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-6">
|
{% endif %}
|
||||||
<p class="text-muted small mb-1">Провёл</p>
|
|
||||||
<p class="fw-semibold">{% if document.confirmed_by %}{{ document.confirmed_by.name|default:document.confirmed_by.email }}{% else %}-{% endif %}</p>
|
{% if document.notes %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<p class="text-muted small mb-1">Примечания</p>
|
||||||
|
<p>{{ document.notes }}</p>
|
||||||
</div>
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if document.confirmed_at %}
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-6">
|
||||||
|
<p class="text-muted small mb-1">Проведён</p>
|
||||||
|
<p class="fw-semibold">{{ document.confirmed_at|date:"d.m.Y H:i" }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<p class="text-muted small mb-1">Провёл</p>
|
||||||
|
<p class="fw-semibold">{% if document.confirmed_by %}{{ document.confirmed_by.name|default:document.confirmed_by.email }}{% else %}-{% endif %}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Добавление позиции -->
|
<!-- Добавление позиции -->
|
||||||
{% if document.can_edit %}
|
{% if document.can_edit %}
|
||||||
<div class="card border-0 shadow-sm mb-3">
|
<div class="card border-0 shadow-sm mb-3">
|
||||||
<div class="card-header bg-light py-3">
|
<div class="card-header bg-light py-1">
|
||||||
<h6 class="mb-0"><i class="bi bi-plus-square me-2"></i>Добавить позицию в документ</h6>
|
<h6 class="mb-0"><i class="bi bi-plus-square me-2"></i>Добавить позицию в документ</h6>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body p-2">
|
||||||
<!-- Компонент поиска товаров -->
|
<!-- Компонент поиска товаров - компактный -->
|
||||||
<div class="mb-3">
|
<div class="mb-2">
|
||||||
{% include 'products/components/product_search_picker.html' with container_id='incoming-picker' title='Найти товар для поступления' warehouse_id=document.warehouse.id filter_in_stock_only=False skip_stock_filter=True categories=categories tags=tags add_button_text='Выбрать товар' content_height='250px' %}
|
{% include 'products/components/product_search_picker.html' with container_id='incoming-picker' title='Найти товар...' warehouse_id=document.warehouse.id filter_in_stock_only=False skip_stock_filter=True categories=categories tags=tags add_button_text='Выбрать' content_height='150px' %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Информация о выбранном товаре -->
|
<!-- Информация о выбранном товаре -->
|
||||||
@@ -188,6 +193,7 @@
|
|||||||
<th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Закупочная цена</th>
|
<th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Закупочная цена</th>
|
||||||
<th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Сумма</th>
|
<th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Сумма</th>
|
||||||
<th scope="col" class="px-3 py-2">Примечания</th>
|
<th scope="col" class="px-3 py-2">Примечания</th>
|
||||||
|
<th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Текущая цена продажи</th>
|
||||||
{% if document.can_edit %}
|
{% if document.can_edit %}
|
||||||
<th scope="col" class="px-3 py-2" style="width: 100px;"></th>
|
<th scope="col" class="px-3 py-2" style="width: 100px;"></th>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -200,19 +206,35 @@
|
|||||||
<a href="{% url 'products:product-detail' item.product.id %}">{{ item.product.name }}</a>
|
<a href="{% url 'products:product-detail' item.product.id %}">{{ item.product.name }}</a>
|
||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-2 text-end" style="width: 120px;">
|
<td class="px-3 py-2 text-end" style="width: 120px;">
|
||||||
<span class="item-quantity-display">{{ item.quantity|smart_quantity }}</span>
|
|
||||||
{% if document.can_edit %}
|
{% if document.can_edit %}
|
||||||
<input type="number" class="form-control form-control-sm item-quantity-input"
|
<span class="editable-quantity"
|
||||||
value="{{ item.quantity|stringformat:'g' }}" step="0.001" min="0.001"
|
data-item-id="{{ item.id }}"
|
||||||
style="display: none; width: 100px; text-align: right; margin-left: auto;">
|
data-current-value="{{ item.quantity }}"
|
||||||
|
title="Количество (клик для редактирования)"
|
||||||
|
style="cursor: pointer;">
|
||||||
|
{{ item.quantity|smart_quantity }}
|
||||||
|
</span>
|
||||||
|
<input type="number" class="form-control form-control-sm item-quantity-input"
|
||||||
|
value="{{ item.quantity|stringformat:'g' }}" step="0.001" min="0.001"
|
||||||
|
style="display: none; width: 100px; text-align: right; margin-left: auto;">
|
||||||
|
{% else %}
|
||||||
|
<span>{{ item.quantity|smart_quantity }}</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-2 text-end" style="width: 120px;">
|
<td class="px-3 py-2 text-end" style="width: 120px;">
|
||||||
<span class="item-cost-price-display">{{ item.cost_price|floatformat:2 }}</span>
|
|
||||||
{% if document.can_edit %}
|
{% if document.can_edit %}
|
||||||
<input type="number" class="form-control form-control-sm item-cost-price-input"
|
<span class="editable-cost-price"
|
||||||
value="{{ item.cost_price|stringformat:'g' }}" step="0.01" min="0"
|
data-item-id="{{ item.id }}"
|
||||||
style="display: none; width: 100px; text-align: right; margin-left: auto;">
|
data-current-value="{{ item.cost_price }}"
|
||||||
|
title="Закупочная цена (клик для редактирования)"
|
||||||
|
style="cursor: pointer;">
|
||||||
|
{{ item.cost_price|floatformat:2 }}
|
||||||
|
</span>
|
||||||
|
<input type="number" class="form-control form-control-sm item-cost-price-input"
|
||||||
|
value="{{ item.cost_price|stringformat:'g' }}" step="0.01" min="0"
|
||||||
|
style="display: none; width: 100px; text-align: right; margin-left: auto;">
|
||||||
|
{% else %}
|
||||||
|
<span>{{ item.cost_price|floatformat:2 }}</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-2 text-end" style="width: 120px;">
|
<td class="px-3 py-2 text-end" style="width: 120px;">
|
||||||
@@ -226,26 +248,49 @@
|
|||||||
style="display: none;">
|
style="display: none;">
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
|
<td class="px-3 py-2 text-end" style="width: 120px;">
|
||||||
|
{% if item.product.sale_price %}
|
||||||
|
<div class="text-decoration-line-through text-muted small">{{ item.product.price|floatformat:2 }} руб.</div>
|
||||||
|
{% if user.is_superuser or user.tenant_role.role.code == 'owner' or user.tenant_role.role.code == 'manager' %}
|
||||||
|
<strong class="text-danger editable-price"
|
||||||
|
data-product-id="{{ item.product.pk }}"
|
||||||
|
data-field="sale_price"
|
||||||
|
data-current-value="{{ item.product.sale_price }}"
|
||||||
|
title="Цена со скидкой (клик для редактирования)"
|
||||||
|
style="cursor: pointer;">
|
||||||
|
{{ item.product.sale_price|floatformat:2 }} руб.
|
||||||
|
</strong>
|
||||||
|
{% else %}
|
||||||
|
<strong class="text-danger">
|
||||||
|
{{ item.product.sale_price|floatformat:2 }} руб.
|
||||||
|
</strong>
|
||||||
|
{% endif %}
|
||||||
|
{% else %}
|
||||||
|
{% if user.is_superuser or user.tenant_role.role.code == 'owner' or user.tenant_role.role.code == 'manager' %}
|
||||||
|
<strong class="editable-price"
|
||||||
|
data-product-id="{{ item.product.pk }}"
|
||||||
|
data-field="price"
|
||||||
|
data-current-value="{{ item.product.price }}"
|
||||||
|
title="Цена продажи (клик для редактирования)"
|
||||||
|
style="cursor: pointer;">
|
||||||
|
{{ item.product.price|floatformat:2 }} руб.
|
||||||
|
</strong>
|
||||||
|
{% else %}
|
||||||
|
<strong>
|
||||||
|
{{ item.product.price|floatformat:2 }} руб.
|
||||||
|
</strong>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
{% if document.can_edit %}
|
{% if document.can_edit %}
|
||||||
<td class="px-3 py-2 text-end" style="width: 100px;">
|
<td class="px-3 py-2 text-end" style="width: 100px;">
|
||||||
<div class="btn-group btn-group-sm item-action-buttons">
|
<div class="btn-group btn-group-sm">
|
||||||
<button type="button" class="btn btn-outline-primary btn-edit-item" title="Редактировать">
|
|
||||||
<i class="bi bi-pencil"></i>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-outline-danger"
|
<button type="button" class="btn btn-outline-danger"
|
||||||
onclick="if(confirm('Удалить позицию?')) document.getElementById('delete-form-{{ item.id }}').submit();"
|
onclick="if(confirm('Удалить позицию?')) document.getElementById('delete-form-{{ item.id }}').submit();"
|
||||||
title="Удалить">
|
title="Удалить">
|
||||||
<i class="bi bi-trash"></i>
|
<i class="bi bi-trash"></i>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="btn-group btn-group-sm item-edit-buttons" style="display: none;">
|
|
||||||
<button type="button" class="btn btn-success btn-save-item" title="Сохранить">
|
|
||||||
<i class="bi bi-check-lg"></i>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-secondary btn-cancel-edit" title="Отменить">
|
|
||||||
<i class="bi bi-x-lg"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<form id="delete-form-{{ item.id }}" method="post"
|
<form id="delete-form-{{ item.id }}" method="post"
|
||||||
action="{% url 'inventory:incoming-remove-item' document.pk item.pk %}"
|
action="{% url 'inventory:incoming-remove-item' document.pk item.pk %}"
|
||||||
style="display: none;">
|
style="display: none;">
|
||||||
@@ -256,7 +301,7 @@
|
|||||||
</tr>
|
</tr>
|
||||||
{% empty %}
|
{% empty %}
|
||||||
<tr>
|
<tr>
|
||||||
<td colspan="{% if document.can_edit %}6{% else %}5{% endif %}" class="px-3 py-4 text-center text-muted">
|
<td colspan="{% if document.can_edit %}7{% else %}6{% endif %}" class="px-3 py-4 text-center text-muted">
|
||||||
<i class="bi bi-inbox fs-3 d-block mb-2"></i>
|
<i class="bi bi-inbox fs-3 d-block mb-2"></i>
|
||||||
Позиций пока нет
|
Позиций пока нет
|
||||||
</td>
|
</td>
|
||||||
@@ -268,7 +313,7 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<td class="px-3 py-2 fw-semibold">Итого:</td>
|
<td class="px-3 py-2 fw-semibold">Итого:</td>
|
||||||
<td class="px-3 py-2 fw-semibold text-end">{{ document.total_quantity|smart_quantity }}</td>
|
<td class="px-3 py-2 fw-semibold text-end">{{ document.total_quantity|smart_quantity }}</td>
|
||||||
<td colspan="2" class="px-3 py-2 fw-semibold text-end">{{ document.total_cost|floatformat:2 }}</td>
|
<td colspan="3" class="px-3 py-2 fw-semibold text-end">{{ document.total_cost|floatformat:2 }}</td>
|
||||||
<td colspan="{% if document.can_edit %}2{% else %}1{% endif %}"></td>
|
<td colspan="{% if document.can_edit %}2{% else %}1{% endif %}"></td>
|
||||||
</tr>
|
</tr>
|
||||||
</tfoot>
|
</tfoot>
|
||||||
@@ -283,6 +328,7 @@
|
|||||||
|
|
||||||
<!-- JS для компонента поиска -->
|
<!-- JS для компонента поиска -->
|
||||||
<script src="{% static 'products/js/product-search-picker.js' %}?v=3"></script>
|
<script src="{% static 'products/js/product-search-picker.js' %}?v=3"></script>
|
||||||
|
<script src="{% static 'products/js/inline-price-edit.js' %}?v=1.5"></script>
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
// Элементы формы
|
// Элементы формы
|
||||||
@@ -307,6 +353,22 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Анимация для иконки сворачивания/разворачивания информации о документе
|
||||||
|
const documentInfoCollapse = document.getElementById('document-info-collapse');
|
||||||
|
const documentInfoCollapseIcon = document.getElementById('document-info-collapse-icon');
|
||||||
|
|
||||||
|
if (documentInfoCollapse && documentInfoCollapseIcon) {
|
||||||
|
documentInfoCollapse.addEventListener('show.bs.collapse', function() {
|
||||||
|
documentInfoCollapseIcon.classList.remove('bi-chevron-down');
|
||||||
|
documentInfoCollapseIcon.classList.add('bi-chevron-up');
|
||||||
|
});
|
||||||
|
|
||||||
|
documentInfoCollapse.addEventListener('hide.bs.collapse', function() {
|
||||||
|
documentInfoCollapseIcon.classList.remove('bi-chevron-up');
|
||||||
|
documentInfoCollapseIcon.classList.add('bi-chevron-down');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Функция выбора товара
|
// Функция выбора товара
|
||||||
function selectProduct(product) {
|
function selectProduct(product) {
|
||||||
const productId = String(product.id).replace('product_', '');
|
const productId = String(product.id).replace('product_', '');
|
||||||
@@ -372,158 +434,328 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
clearSelectedBtn.addEventListener('click', clearSelectedProduct);
|
clearSelectedBtn.addEventListener('click', clearSelectedProduct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// ============================================
|
// ============================================
|
||||||
// Inline редактирование позиций в таблице
|
// Inline редактирование количества и цены
|
||||||
// ============================================
|
// ============================================
|
||||||
|
|
||||||
// Хранилище оригинальных значений при редактировании
|
function initInlineQuantityEdit() {
|
||||||
const originalValues = {};
|
// Проверяем, есть ли на странице редактируемые количества
|
||||||
|
const editableQuantities = document.querySelectorAll('.editable-quantity');
|
||||||
|
if (editableQuantities.length === 0) {
|
||||||
|
return; // Нет элементов для редактирования
|
||||||
|
}
|
||||||
|
|
||||||
// Обработчики для кнопок редактирования
|
// Обработчик клика на редактируемое количество
|
||||||
document.querySelectorAll('.btn-edit-item').forEach(btn => {
|
document.addEventListener('click', function(e) {
|
||||||
btn.addEventListener('click', function() {
|
const quantitySpan = e.target.closest('.editable-quantity');
|
||||||
const row = this.closest('tr');
|
if (!quantitySpan) return;
|
||||||
const itemId = row.dataset.itemId;
|
|
||||||
|
|
||||||
// Сохраняем оригинальные значения
|
// Предотвращаем повторное срабатывание, если уже редактируем
|
||||||
originalValues[itemId] = {
|
if (quantitySpan.querySelector('input')) return;
|
||||||
quantity: row.querySelector('.item-quantity-input').value,
|
|
||||||
cost_price: row.querySelector('.item-cost-price-input').value,
|
const itemId = quantitySpan.dataset.itemId;
|
||||||
notes: row.querySelector('.item-notes-input').value
|
const currentValue = quantitySpan.dataset.currentValue;
|
||||||
|
|
||||||
|
// Сохраняем оригинальный HTML
|
||||||
|
const originalHTML = quantitySpan.innerHTML;
|
||||||
|
|
||||||
|
// Создаем input для редактирования
|
||||||
|
const input = document.createElement('input');
|
||||||
|
input.type = 'number';
|
||||||
|
input.className = 'form-control form-control-sm';
|
||||||
|
input.style.width = '100px';
|
||||||
|
input.style.textAlign = 'right';
|
||||||
|
input.value = parseFloat(currentValue).toFixed(3);
|
||||||
|
input.step = '0.001';
|
||||||
|
input.min = '0.001';
|
||||||
|
input.placeholder = 'Количество';
|
||||||
|
|
||||||
|
// Заменяем содержимое на input
|
||||||
|
quantitySpan.innerHTML = '';
|
||||||
|
quantitySpan.appendChild(input);
|
||||||
|
input.focus();
|
||||||
|
input.select();
|
||||||
|
|
||||||
|
// Функция сохранения
|
||||||
|
const saveQuantity = async () => {
|
||||||
|
let newValue = input.value.trim();
|
||||||
|
|
||||||
|
// Валидация
|
||||||
|
if (!newValue || parseFloat(newValue) <= 0) {
|
||||||
|
alert('Количество должно быть больше нуля');
|
||||||
|
quantitySpan.innerHTML = originalHTML;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем, изменилось ли значение
|
||||||
|
if (parseFloat(newValue) === parseFloat(currentValue)) {
|
||||||
|
// Значение не изменилось
|
||||||
|
quantitySpan.innerHTML = originalHTML;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Показываем загрузку
|
||||||
|
input.disabled = true;
|
||||||
|
input.style.opacity = '0.5';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Получаем текущие значения других полей
|
||||||
|
const row = quantitySpan.closest('tr');
|
||||||
|
const costPrice = row.querySelector('.item-cost-price-input').value;
|
||||||
|
const notes = row.querySelector('.item-notes-input').value;
|
||||||
|
|
||||||
|
const response = await fetch(`/inventory/incoming-documents/{{ document.pk }}/update-item/${itemId}/`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
|
||||||
|
},
|
||||||
|
body: new URLSearchParams({
|
||||||
|
quantity: newValue,
|
||||||
|
cost_price: costPrice,
|
||||||
|
notes: notes
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
// Обновляем отображение
|
||||||
|
let formattedQty = parseFloat(newValue);
|
||||||
|
if (formattedQty === Math.floor(formattedQty)) {
|
||||||
|
formattedQty = Math.floor(formattedQty).toString();
|
||||||
|
} else {
|
||||||
|
formattedQty = formattedQty.toString().replace('.', ',');
|
||||||
|
}
|
||||||
|
quantitySpan.textContent = formattedQty;
|
||||||
|
quantitySpan.dataset.currentValue = newValue;
|
||||||
|
|
||||||
|
// Пересчитываем сумму
|
||||||
|
const totalCost = (parseFloat(newValue) * parseFloat(costPrice)).toFixed(2);
|
||||||
|
row.querySelector('td:nth-child(4) strong').textContent = totalCost;
|
||||||
|
|
||||||
|
// Обновляем итого
|
||||||
|
updateTotals();
|
||||||
|
} else {
|
||||||
|
alert(data.error || 'Ошибка при обновлении количества');
|
||||||
|
quantitySpan.innerHTML = originalHTML;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error);
|
||||||
|
alert('Ошибка сети при обновлении количества');
|
||||||
|
quantitySpan.innerHTML = originalHTML;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Переключаем в режим редактирования
|
// Функция отмены
|
||||||
toggleEditMode(row, true);
|
const cancelEdit = () => {
|
||||||
});
|
quantitySpan.innerHTML = originalHTML;
|
||||||
});
|
};
|
||||||
|
|
||||||
// Обработчики для кнопок сохранения
|
// Enter - сохранить
|
||||||
document.querySelectorAll('.btn-save-item').forEach(btn => {
|
input.addEventListener('keydown', function(e) {
|
||||||
btn.addEventListener('click', function() {
|
if (e.key === 'Enter') {
|
||||||
const row = this.closest('tr');
|
e.preventDefault();
|
||||||
const itemId = row.dataset.itemId;
|
saveQuantity();
|
||||||
saveItemChanges(itemId, row);
|
} else if (e.key === 'Escape') {
|
||||||
});
|
e.preventDefault();
|
||||||
});
|
cancelEdit();
|
||||||
|
|
||||||
// Обработчики для кнопок отмены
|
|
||||||
document.querySelectorAll('.btn-cancel-edit').forEach(btn => {
|
|
||||||
btn.addEventListener('click', function() {
|
|
||||||
const row = this.closest('tr');
|
|
||||||
const itemId = row.dataset.itemId;
|
|
||||||
|
|
||||||
// Восстанавливаем оригинальные значения
|
|
||||||
if (originalValues[itemId]) {
|
|
||||||
row.querySelector('.item-quantity-input').value = originalValues[itemId].quantity;
|
|
||||||
row.querySelector('.item-cost-price-input').value = originalValues[itemId].cost_price;
|
|
||||||
row.querySelector('.item-notes-input').value = originalValues[itemId].notes;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Выходим из режима редактирования
|
|
||||||
toggleEditMode(row, false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Переключение режима редактирования строки
|
|
||||||
*/
|
|
||||||
function toggleEditMode(row, isEditing) {
|
|
||||||
// Переключаем видимость полей отображения/ввода
|
|
||||||
row.querySelectorAll('.item-quantity-display, .item-cost-price-display, .item-notes-display').forEach(el => {
|
|
||||||
el.style.display = isEditing ? 'none' : '';
|
|
||||||
});
|
|
||||||
row.querySelectorAll('.item-quantity-input, .item-cost-price-input, .item-notes-input').forEach(el => {
|
|
||||||
el.style.display = isEditing ? '' : 'none';
|
|
||||||
});
|
|
||||||
|
|
||||||
// Переключаем видимость кнопок
|
|
||||||
row.querySelector('.item-action-buttons').style.display = isEditing ? 'none' : '';
|
|
||||||
row.querySelector('.item-edit-buttons').style.display = isEditing ? '' : 'none';
|
|
||||||
|
|
||||||
// Фокус на поле количества при входе в режим редактирования
|
|
||||||
if (isEditing) {
|
|
||||||
const qtyInput = row.querySelector('.item-quantity-input');
|
|
||||||
if (qtyInput) {
|
|
||||||
qtyInput.focus();
|
|
||||||
qtyInput.select();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Сохранение изменений позиции
|
|
||||||
*/
|
|
||||||
function saveItemChanges(itemId, row) {
|
|
||||||
const quantity = row.querySelector('.item-quantity-input').value;
|
|
||||||
const costPrice = row.querySelector('.item-cost-price-input').value;
|
|
||||||
const notes = row.querySelector('.item-notes-input').value;
|
|
||||||
|
|
||||||
// Валидация
|
|
||||||
if (!quantity || parseFloat(quantity) <= 0) {
|
|
||||||
alert('Количество должно быть больше нуля');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!costPrice || parseFloat(costPrice) < 0) {
|
|
||||||
alert('Закупочная цена не может быть отрицательной');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Отправляем на сервер
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('quantity', quantity);
|
|
||||||
formData.append('cost_price', costPrice);
|
|
||||||
formData.append('notes', notes);
|
|
||||||
formData.append('csrfmiddlewaretoken', document.querySelector('[name=csrfmiddlewaretoken]').value);
|
|
||||||
|
|
||||||
// Блокируем кнопки во время сохранения
|
|
||||||
const saveBtn = row.querySelector('.btn-save-item');
|
|
||||||
const cancelBtn = row.querySelector('.btn-cancel-edit');
|
|
||||||
saveBtn.disabled = true;
|
|
||||||
cancelBtn.disabled = true;
|
|
||||||
saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span>';
|
|
||||||
|
|
||||||
fetch(`/inventory/incoming-documents/{{ document.pk }}/update-item/${itemId}/`, {
|
|
||||||
method: 'POST',
|
|
||||||
body: formData,
|
|
||||||
headers: {
|
|
||||||
'X-Requested-With': 'XMLHttpRequest'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(data => {
|
|
||||||
if (data.success) {
|
|
||||||
// Обновляем отображение
|
|
||||||
let formattedQty = parseFloat(quantity);
|
|
||||||
if (formattedQty === Math.floor(formattedQty)) {
|
|
||||||
formattedQty = Math.floor(formattedQty).toString();
|
|
||||||
} else {
|
|
||||||
formattedQty = formattedQty.toString().replace('.', ',');
|
|
||||||
}
|
}
|
||||||
row.querySelector('.item-quantity-display').textContent = formattedQty;
|
});
|
||||||
row.querySelector('.item-cost-price-display').textContent = parseFloat(costPrice).toFixed(2);
|
|
||||||
row.querySelector('.item-notes-display').textContent = notes || '-';
|
|
||||||
|
|
||||||
// Пересчитываем сумму
|
// Потеря фокуса - сохранить
|
||||||
const totalCost = (parseFloat(quantity) * parseFloat(costPrice)).toFixed(2);
|
input.addEventListener('blur', function() {
|
||||||
row.querySelector('td:nth-child(4) strong').textContent = totalCost;
|
setTimeout(saveQuantity, 100);
|
||||||
|
});
|
||||||
// Выходим из режима редактирования
|
|
||||||
toggleEditMode(row, false);
|
|
||||||
} else {
|
|
||||||
alert('Ошибка: ' + data.error);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => {
|
|
||||||
console.error('Error:', error);
|
|
||||||
alert('Произошла ошибка при сохранении');
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
saveBtn.disabled = false;
|
|
||||||
cancelBtn.disabled = false;
|
|
||||||
saveBtn.innerHTML = '<i class="bi bi-check-lg"></i>';
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function initInlineCostPriceEdit() {
|
||||||
|
// Проверяем, есть ли на странице редактируемые цены
|
||||||
|
const editableCostPrices = document.querySelectorAll('.editable-cost-price');
|
||||||
|
if (editableCostPrices.length === 0) {
|
||||||
|
return; // Нет элементов для редактирования
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обработчик клика на редактируемую цену
|
||||||
|
document.addEventListener('click', function(e) {
|
||||||
|
const costPriceSpan = e.target.closest('.editable-cost-price');
|
||||||
|
if (!costPriceSpan) return;
|
||||||
|
|
||||||
|
// Предотвращаем повторное срабатывание, если уже редактируем
|
||||||
|
if (costPriceSpan.querySelector('input')) return;
|
||||||
|
|
||||||
|
const itemId = costPriceSpan.dataset.itemId;
|
||||||
|
const currentValue = costPriceSpan.dataset.currentValue;
|
||||||
|
|
||||||
|
// Сохраняем оригинальный HTML
|
||||||
|
const originalHTML = costPriceSpan.innerHTML;
|
||||||
|
|
||||||
|
// Создаем input для редактирования
|
||||||
|
const input = document.createElement('input');
|
||||||
|
input.type = 'number';
|
||||||
|
input.className = 'form-control form-control-sm';
|
||||||
|
input.style.width = '100px';
|
||||||
|
input.style.textAlign = 'right';
|
||||||
|
input.value = parseFloat(currentValue).toFixed(2);
|
||||||
|
input.step = '0.01';
|
||||||
|
input.min = '0';
|
||||||
|
input.placeholder = 'Цена';
|
||||||
|
|
||||||
|
// Заменяем содержимое на input
|
||||||
|
costPriceSpan.innerHTML = '';
|
||||||
|
costPriceSpan.appendChild(input);
|
||||||
|
input.focus();
|
||||||
|
input.select();
|
||||||
|
|
||||||
|
// Функция сохранения
|
||||||
|
const saveCostPrice = async () => {
|
||||||
|
let newValue = input.value.trim();
|
||||||
|
|
||||||
|
// Валидация
|
||||||
|
if (!newValue || parseFloat(newValue) < 0) {
|
||||||
|
alert('Закупочная цена не может быть отрицательной');
|
||||||
|
costPriceSpan.innerHTML = originalHTML;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем, изменилось ли значение
|
||||||
|
if (parseFloat(newValue) === parseFloat(currentValue)) {
|
||||||
|
// Значение не изменилось
|
||||||
|
costPriceSpan.innerHTML = originalHTML;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Показываем загрузку
|
||||||
|
input.disabled = true;
|
||||||
|
input.style.opacity = '0.5';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Получаем текущие значения других полей
|
||||||
|
const row = costPriceSpan.closest('tr');
|
||||||
|
const quantity = row.querySelector('.item-quantity-input').value;
|
||||||
|
const notes = row.querySelector('.item-notes-input').value;
|
||||||
|
|
||||||
|
const response = await fetch(`/inventory/incoming-documents/{{ document.pk }}/update-item/${itemId}/`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
|
||||||
|
},
|
||||||
|
body: new URLSearchParams({
|
||||||
|
quantity: quantity,
|
||||||
|
cost_price: newValue,
|
||||||
|
notes: notes
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
// Обновляем отображение
|
||||||
|
const formattedPrice = parseFloat(newValue).toFixed(2);
|
||||||
|
costPriceSpan.textContent = formattedPrice;
|
||||||
|
costPriceSpan.dataset.currentValue = newValue;
|
||||||
|
|
||||||
|
// Пересчитываем сумму
|
||||||
|
const totalCost = (parseFloat(quantity) * parseFloat(newValue)).toFixed(2);
|
||||||
|
row.querySelector('td:nth-child(4) strong').textContent = totalCost;
|
||||||
|
|
||||||
|
// Обновляем итого
|
||||||
|
updateTotals();
|
||||||
|
} else {
|
||||||
|
alert(data.error || 'Ошибка при обновлении цены');
|
||||||
|
costPriceSpan.innerHTML = originalHTML;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error);
|
||||||
|
alert('Ошибка сети при обновлении цены');
|
||||||
|
costPriceSpan.innerHTML = originalHTML;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Функция отмены
|
||||||
|
const cancelEdit = () => {
|
||||||
|
costPriceSpan.innerHTML = originalHTML;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Enter - сохранить
|
||||||
|
input.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
saveCostPrice();
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.preventDefault();
|
||||||
|
cancelEdit();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Потеря фокуса - сохранить
|
||||||
|
input.addEventListener('blur', function() {
|
||||||
|
setTimeout(saveCostPrice, 100);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Функция обновления итоговых сумм
|
||||||
|
function updateTotals() {
|
||||||
|
// Можно реализовать пересчет итогов, если нужно
|
||||||
|
// Пока оставим как есть, так как сервер возвращает обновленные данные
|
||||||
|
}
|
||||||
|
|
||||||
|
// Инициализация inline редактирования
|
||||||
|
initInlineQuantityEdit();
|
||||||
|
initInlineCostPriceEdit();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
/* Стили для редактируемых цен */
|
||||||
|
.editable-price {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editable-price:hover {
|
||||||
|
color: #0d6efd !important;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.price-edit-container {
|
||||||
|
min-height: 2.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Стили для редактируемого количества */
|
||||||
|
.editable-quantity {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editable-quantity:hover {
|
||||||
|
color: #0d6efd !important;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Стили для редактируемой цены */
|
||||||
|
.editable-cost-price {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editable-cost-price:hover {
|
||||||
|
color: #0d6efd !important;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|||||||
@@ -19,52 +19,76 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
|
<!-- Информация об инвентаризации - свернута по умолчанию -->
|
||||||
<div class="row mb-4">
|
<div class="row mb-4">
|
||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<h5>Информация</h5>
|
<button class="btn btn-outline-primary btn-sm d-flex align-items-center gap-2 mb-2" type="button" data-bs-toggle="collapse" data-bs-target="#inventory-info-collapse" aria-expanded="false" aria-controls="inventory-info-collapse">
|
||||||
<table class="table table-borderless">
|
<i class="bi bi-chevron-down" id="info-collapse-icon"></i>
|
||||||
{% if inventory.document_number %}
|
<span>Информация</span>
|
||||||
<tr>
|
</button>
|
||||||
<th>Номер документа:</th>
|
<div class="collapse" id="inventory-info-collapse">
|
||||||
<td><strong>{{ inventory.document_number }}</strong></td>
|
<table class="table table-borderless">
|
||||||
</tr>
|
{% if inventory.document_number %}
|
||||||
{% endif %}
|
<tr>
|
||||||
<tr>
|
<th>Номер документа:</th>
|
||||||
<th>Склад:</th>
|
<td><strong>{{ inventory.document_number }}</strong></td>
|
||||||
<td><strong>{{ inventory.warehouse.name }}</strong></td>
|
</tr>
|
||||||
</tr>
|
{% endif %}
|
||||||
<tr>
|
<tr>
|
||||||
<th>Статус:</th>
|
<th>Склад:</th>
|
||||||
<td>
|
<td><strong>{{ inventory.warehouse.name }}</strong></td>
|
||||||
{% if inventory.status == 'draft' %}
|
</tr>
|
||||||
<span class="badge bg-secondary fs-6 px-3 py-2">
|
<tr>
|
||||||
<i class="bi bi-file-earmark"></i> Черновик
|
<th>Статус:</th>
|
||||||
</span>
|
<td>
|
||||||
{% elif inventory.status == 'processing' %}
|
{% if inventory.status == 'draft' %}
|
||||||
<span class="badge bg-warning text-dark fs-6 px-3 py-2">
|
<span class="badge bg-secondary fs-6 px-3 py-2">
|
||||||
<i class="bi bi-hourglass-split"></i> В обработке
|
<i class="bi bi-file-earmark"></i> Черновик
|
||||||
</span>
|
</span>
|
||||||
{% else %}
|
{% elif inventory.status == 'processing' %}
|
||||||
<span class="badge bg-success fs-6 px-3 py-2">
|
<span class="badge bg-warning text-dark fs-6 px-3 py-2">
|
||||||
<i class="bi bi-check-circle-fill"></i> Завершена
|
<i class="bi bi-hourglass-split"></i> В обработке
|
||||||
</span>
|
</span>
|
||||||
{% endif %}
|
{% else %}
|
||||||
</td>
|
<span class="badge bg-success fs-6 px-3 py-2">
|
||||||
</tr>
|
<i class="bi bi-check-circle-fill"></i> Завершена
|
||||||
<tr>
|
</span>
|
||||||
<th>Дата:</th>
|
{% endif %}
|
||||||
<td>{{ inventory.date|date:"d.m.Y H:i" }}</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% if inventory.conducted_by %}
|
<tr>
|
||||||
<tr>
|
<th>Дата:</th>
|
||||||
<th>Провёл:</th>
|
<td>{{ inventory.date|date:"d.m.Y H:i" }}</td>
|
||||||
<td>{{ inventory.conducted_by }}</td>
|
</tr>
|
||||||
</tr>
|
{% if inventory.conducted_by %}
|
||||||
{% endif %}
|
<tr>
|
||||||
</table>
|
<th>Провёл:</th>
|
||||||
|
<td>{{ inventory.conducted_by }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endif %}
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Добавляем простую анимацию для иконки при сворачивании/разворачивании
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
const collapseElement = document.getElementById('inventory-info-collapse');
|
||||||
|
const collapseIcon = document.getElementById('info-collapse-icon');
|
||||||
|
|
||||||
|
collapseElement.addEventListener('show.bs.collapse', function() {
|
||||||
|
collapseIcon.classList.remove('bi-chevron-down');
|
||||||
|
collapseIcon.classList.add('bi-chevron-up');
|
||||||
|
});
|
||||||
|
|
||||||
|
collapseElement.addEventListener('hide.bs.collapse', function() {
|
||||||
|
collapseIcon.classList.remove('bi-chevron-up');
|
||||||
|
collapseIcon.classList.add('bi-chevron-down');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
{% if inventory.status == 'completed' %}
|
{% if inventory.status == 'completed' %}
|
||||||
<!-- Информация о созданных документах -->
|
<!-- Информация о созданных документах -->
|
||||||
<div class="alert alert-info mb-4">
|
<div class="alert alert-info mb-4">
|
||||||
@@ -100,14 +124,14 @@
|
|||||||
|
|
||||||
<h5>Строки инвентаризации</h5>
|
<h5>Строки инвентаризации</h5>
|
||||||
|
|
||||||
<!-- Компонент поиска товаров (только если не завершена) -->
|
<!-- Компонент поиска товаров - открыт по умолчанию, компактный -->
|
||||||
{% if inventory.status != 'completed' %}
|
{% if inventory.status != 'completed' %}
|
||||||
<div class="card border-primary mb-4" id="product-search-section">
|
<div class="card border-primary mb-4" id="product-search-section">
|
||||||
<div class="card-header bg-light">
|
<div class="card-header bg-light py-1">
|
||||||
<h6 class="mb-0"><i class="bi bi-plus-square me-2"></i>Добавить товар в инвентаризацию</h6>
|
<h6 class="mb-0"><i class="bi bi-plus-square me-2"></i>Добавить товар в инвентаризацию</h6>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body p-2">
|
||||||
{% include 'products/components/product_search_picker.html' with container_id='inventory-product-picker' title='Поиск товара для инвентаризации...' warehouse_id=inventory.warehouse.id filter_in_stock_only=False categories=categories tags=tags add_button_text='Добавить товар' content_height='250px' %}
|
{% include 'products/components/product_search_picker.html' with container_id='inventory-product-picker' title='Поиск товара...' warehouse_id=inventory.warehouse.id filter_in_stock_only=False categories=categories tags=tags add_button_text='Добавить' content_height='150px' skip_stock_filter=True %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -288,11 +312,15 @@
|
|||||||
<script src="{% static 'inventory/js/inventory_detail.js' %}" onerror="console.error('Failed to load inventory_detail.js');"></script>
|
<script src="{% static 'inventory/js/inventory_detail.js' %}" onerror="console.error('Failed to load inventory_detail.js');"></script>
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
console.log('DOM loaded, initializing inventory components...');
|
||||||
|
|
||||||
// Проверка загрузки ProductSearchPicker
|
// Проверка загрузки ProductSearchPicker
|
||||||
if (typeof ProductSearchPicker === 'undefined') {
|
if (typeof ProductSearchPicker === 'undefined') {
|
||||||
console.error('ProductSearchPicker is not defined. Check if product-search-picker.js loaded correctly.');
|
console.error('ProductSearchPicker is not defined. Check if product-search-picker.js loaded correctly.');
|
||||||
console.error('Script URL: {% static "products/js/product-search-picker.js" %}');
|
console.error('Script URL: {% static "products/js/product-search-picker.js" %}');
|
||||||
return;
|
return;
|
||||||
|
} else {
|
||||||
|
console.log('ProductSearchPicker is available');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Инициализация компонента поиска товаров
|
// Инициализация компонента поиска товаров
|
||||||
@@ -303,8 +331,15 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('Initializing ProductSearchPicker for inventory...');
|
||||||
const picker = ProductSearchPicker.init('#inventory-product-picker', {
|
const picker = ProductSearchPicker.init('#inventory-product-picker', {
|
||||||
|
apiUrl: '{% url "products:api-search-products-variants" %}', // Явно указываем URL API
|
||||||
|
excludeKits: true, // Исключаем комплекты из поиска
|
||||||
|
onSelect: function(product, instance) {
|
||||||
|
console.log('Product selected:', product);
|
||||||
|
},
|
||||||
onAddSelected: function(product, instance) {
|
onAddSelected: function(product, instance) {
|
||||||
|
console.log('Adding selected product to inventory:', product);
|
||||||
if (product) {
|
if (product) {
|
||||||
addInventoryLine(product.id);
|
addInventoryLine(product.id);
|
||||||
instance.clearSelection();
|
instance.clearSelection();
|
||||||
@@ -314,17 +349,24 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
if (!picker) {
|
if (!picker) {
|
||||||
console.error('Failed to initialize ProductSearchPicker');
|
console.error('Failed to initialize ProductSearchPicker');
|
||||||
|
} else {
|
||||||
|
console.log('ProductSearchPicker initialized successfully');
|
||||||
}
|
}
|
||||||
|
{% else %}
|
||||||
|
console.log('Inventory is completed, skipping product picker initialization');
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
// Инициализация обработчиков
|
// Инициализация обработчиков
|
||||||
const inventoryId = {{ inventory.pk }};
|
const inventoryId = {{ inventory.pk }};
|
||||||
|
console.log('Initializing inventory detail handlers for ID:', inventoryId);
|
||||||
window.inventoryDetailHandlers = initInventoryDetailHandlers(inventoryId, {
|
window.inventoryDetailHandlers = initInventoryDetailHandlers(inventoryId, {
|
||||||
addLineUrl: '{% url "inventory:inventory-line-add" inventory.pk %}',
|
addLineUrl: '{% url "inventory:inventory-line-add" inventory.pk %}',
|
||||||
updateLineUrl: '{% url "inventory:inventory-line-update" inventory.pk 999 %}',
|
updateLineUrl: '{% url "inventory:inventory-line-update" inventory.pk 999 %}',
|
||||||
deleteLineUrl: '{% url "inventory:inventory-line-delete" inventory.pk 999 %}',
|
deleteLineUrl: '{% url "inventory:inventory-line-delete" inventory.pk 999 %}',
|
||||||
completeUrl: '{% url "inventory:inventory-complete" inventory.pk %}'
|
completeUrl: '{% url "inventory:inventory-complete" inventory.pk %}'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log('Inventory detail handlers initialized');
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -74,10 +74,12 @@
|
|||||||
{% for item in items %}
|
{% for item in items %}
|
||||||
<tr>
|
<tr>
|
||||||
<td class="px-3 py-2">
|
<td class="px-3 py-2">
|
||||||
<a href="{% url 'products:product-detail' item.product.id %}">{{ item.product.name }}</a>
|
<a href="{% url 'products:product-detail' item.product.id %}">{{
|
||||||
|
item.product.name }}</a>
|
||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-2" style="text-align: right;">{{ item.quantity }}</td>
|
<td class="px-3 py-2" style="text-align: right;">{{ item.quantity }}</td>
|
||||||
<td class="px-3 py-2" style="text-align: right;">{{ item.batch.cost_price }} ₽/ед.</td>
|
<td class="px-3 py-2" style="text-align: right;">{{ item.batch.cost_price }} ₽/ед.
|
||||||
|
</td>
|
||||||
<td class="px-3 py-2">
|
<td class="px-3 py-2">
|
||||||
<span class="badge bg-secondary">{{ item.batch.id }}</span>
|
<span class="badge bg-secondary">{{ item.batch.id }}</span>
|
||||||
</td>
|
</td>
|
||||||
@@ -132,9 +134,11 @@
|
|||||||
<a href="{% url 'inventory:transfer-list' %}" class="btn btn-outline-secondary btn-sm">
|
<a href="{% url 'inventory:transfer-list' %}" class="btn btn-outline-secondary btn-sm">
|
||||||
<i class="bi bi-arrow-left me-1"></i>Вернуться к списку
|
<i class="bi bi-arrow-left me-1"></i>Вернуться к списку
|
||||||
</a>
|
</a>
|
||||||
|
<!--
|
||||||
<a href="{% url 'inventory:transfer-delete' transfer_document.id %}" class="btn btn-outline-danger btn-sm">
|
<a href="{% url 'inventory:transfer-delete' transfer_document.id %}" class="btn btn-outline-danger btn-sm">
|
||||||
<i class="bi bi-trash me-1"></i>Удалить
|
<i class="bi bi-trash me-1"></i>Удалить
|
||||||
</a>
|
</a>
|
||||||
|
-->
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -143,13 +147,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.breadcrumb-sm {
|
.breadcrumb-sm {
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
padding: 0.5rem 0;
|
padding: 0.5rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.table-hover tbody tr:hover {
|
.table-hover tbody tr:hover {
|
||||||
background-color: #f8f9fa;
|
background-color: #f8f9fa;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -39,9 +39,11 @@
|
|||||||
<a href="{% url 'inventory:transfer-detail' t.pk %}" class="btn btn-sm btn-outline-info" title="Просмотр">
|
<a href="{% url 'inventory:transfer-detail' t.pk %}" class="btn btn-sm btn-outline-info" title="Просмотр">
|
||||||
<i class="bi bi-eye"></i>
|
<i class="bi bi-eye"></i>
|
||||||
</a>
|
</a>
|
||||||
|
<!--
|
||||||
<a href="{% url 'inventory:transfer-delete' t.pk %}" class="btn btn-sm btn-outline-danger" title="Удалить">
|
<a href="{% url 'inventory:transfer-delete' t.pk %}" class="btn btn-sm btn-outline-danger" title="Удалить">
|
||||||
<i class="bi bi-trash"></i>
|
<i class="bi bi-trash"></i>
|
||||||
</a>
|
</a>
|
||||||
|
-->
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|||||||
@@ -1066,10 +1066,6 @@ class OrderStatusTransitionCriticalTest(TestCase):
|
|||||||
order.save()
|
order.save()
|
||||||
order.refresh_from_db()
|
order.refresh_from_db()
|
||||||
|
|
||||||
# Проверяем, что прошли через draft (автоматический промежуточный переход)
|
|
||||||
history = order.history.all()
|
|
||||||
self.assertGreaterEqual(history.count(), 2, "[STEP 7] Должна быть история переходов")
|
|
||||||
|
|
||||||
# Проверки после автоматического перехода
|
# Проверки после автоматического перехода
|
||||||
self._assert_stock_state(
|
self._assert_stock_state(
|
||||||
available=Decimal('90.00'),
|
available=Decimal('90.00'),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
Отладочные view для суперюзеров.
|
Отладочные view для owner и manager.
|
||||||
Для мониторинга работы системы инвентаризации.
|
Для мониторинга работы системы инвентаризации.
|
||||||
"""
|
"""
|
||||||
from django.contrib.auth.decorators import login_required, user_passes_test
|
from django.contrib.auth.decorators import login_required, user_passes_test
|
||||||
@@ -15,16 +15,16 @@ from products.models import Product
|
|||||||
from inventory.models import Warehouse
|
from inventory.models import Warehouse
|
||||||
|
|
||||||
|
|
||||||
def is_superuser(user):
|
def is_owner_or_manager(user):
|
||||||
"""Проверка что пользователь - суперюзер."""
|
"""Проверка что пользователь - owner или manager."""
|
||||||
return user.is_superuser
|
return user.is_owner or user.is_manager
|
||||||
|
|
||||||
|
|
||||||
@login_required
|
@login_required
|
||||||
@user_passes_test(is_superuser)
|
@user_passes_test(is_owner_or_manager)
|
||||||
def debug_inventory_page(request):
|
def debug_inventory_page(request):
|
||||||
"""
|
"""
|
||||||
Отладочная страница для суперюзеров.
|
Отладочная страница для owner и manager.
|
||||||
Показывает полную картину по инвентаризации: партии, остатки, резервы, продажи.
|
Показывает полную картину по инвентаризации: партии, остатки, резервы, продажи.
|
||||||
"""
|
"""
|
||||||
# Получаем параметры фильтров
|
# Получаем параметры фильтров
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
|
|||||||
# Initialize environment variables
|
# Initialize environment variables
|
||||||
env = environ.Env(
|
env = environ.Env(
|
||||||
# Set casting and default values
|
# Set casting and default values
|
||||||
DEBUG=(bool, False), # Security: default False
|
DEBUG=(bool, True), # Debug mode enabled
|
||||||
SECRET_KEY=(str, 'django-insecure-default-key-change-in-production'),
|
SECRET_KEY=(str, 'django-insecure-default-key-change-in-production'),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -631,3 +631,5 @@ if not DEBUG and not ENCRYPTION_KEY:
|
|||||||
"ENCRYPTION_KEY not set! Encrypted fields will fail. "
|
"ENCRYPTION_KEY not set! Encrypted fields will fail. "
|
||||||
"Generate with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
|
"Generate with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -101,11 +101,19 @@ class OrderFilter(django_filters.FilterSet):
|
|||||||
widget=forms.Select(attrs={'class': 'form-select'})
|
widget=forms.Select(attrs={'class': 'form-select'})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Фильтр: показывать все заказы, включая завершённые и отменённые
|
||||||
|
show_all_orders = django_filters.BooleanFilter(
|
||||||
|
method='filter_show_all_orders',
|
||||||
|
label='Включая завершённые',
|
||||||
|
widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
|
||||||
|
)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Order
|
model = Order
|
||||||
fields = ['search', 'status', 'delivery_type', 'payment_status',
|
fields = ['search', 'status', 'delivery_type', 'payment_status',
|
||||||
'delivery_date_after', 'delivery_date_before',
|
'delivery_date_after', 'delivery_date_before',
|
||||||
'created_at_after', 'created_at_before']
|
'created_at_after', 'created_at_before',
|
||||||
|
'show_all_orders']
|
||||||
|
|
||||||
def filter_search(self, queryset, name, value):
|
def filter_search(self, queryset, name, value):
|
||||||
"""
|
"""
|
||||||
@@ -134,3 +142,18 @@ class OrderFilter(django_filters.FilterSet):
|
|||||||
elif value == 'pickup':
|
elif value == 'pickup':
|
||||||
return queryset.filter(delivery__delivery_type=Delivery.DELIVERY_TYPE_PICKUP)
|
return queryset.filter(delivery__delivery_type=Delivery.DELIVERY_TYPE_PICKUP)
|
||||||
return queryset
|
return queryset
|
||||||
|
|
||||||
|
def filter_show_all_orders(self, queryset, name, value):
|
||||||
|
"""
|
||||||
|
Фильтр для показа всех заказов.
|
||||||
|
- Если False или не передан: только активные заказы
|
||||||
|
(статусы с is_positive_end=False И is_negative_end=False)
|
||||||
|
- Если True: все заказы без ограничений
|
||||||
|
"""
|
||||||
|
if not value:
|
||||||
|
# Активные заказы = НЕ (is_positive_end OR is_negative_end)
|
||||||
|
return queryset.filter(
|
||||||
|
Q(status__isnull=True) |
|
||||||
|
(Q(status__is_positive_end=False) & Q(status__is_negative_end=False))
|
||||||
|
)
|
||||||
|
return queryset
|
||||||
|
|||||||
@@ -425,7 +425,8 @@ class OrderForm(forms.ModelForm):
|
|||||||
|
|
||||||
has_address = (
|
has_address = (
|
||||||
(address_mode == 'history' and address_from_history) or
|
(address_mode == 'history' and address_from_history) or
|
||||||
(address_mode == 'new' and address_street)
|
(address_mode == 'new' and address_street) or
|
||||||
|
address_mode == 'empty' # Разрешаем "Без адреса (заполнить позже)"
|
||||||
)
|
)
|
||||||
|
|
||||||
if not has_address:
|
if not has_address:
|
||||||
@@ -461,11 +462,15 @@ class OrderItemForm(forms.ModelForm):
|
|||||||
widget=forms.TextInput(attrs={'class': 'form-control', 'step': '0.01', 'min': '0'})
|
widget=forms.TextInput(attrs={'class': 'form-control', 'step': '0.01', 'min': '0'})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Поле DELETE, которое автоматически добавляется в inline формсете
|
||||||
|
DELETE = forms.BooleanField(required=False, widget=forms.HiddenInput())
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = OrderItem
|
model = OrderItem
|
||||||
fields = ['product', 'product_kit', 'sales_unit', 'quantity', 'price', 'is_custom_price', 'is_from_showcase']
|
fields = ['id', 'product', 'product_kit', 'sales_unit', 'quantity', 'price', 'is_custom_price', 'is_from_showcase']
|
||||||
# ВАЖНО: НЕ включаем 'id' в fields - это предотвращает ошибку валидации
|
# ВАЖНО: Теперь включаем 'id' в fields для правильной работы inline формсета
|
||||||
widgets = {
|
widgets = {
|
||||||
|
'id': forms.HiddenInput(), # Скрываем поле id, но оставляем его для формсета
|
||||||
'quantity': forms.NumberInput(attrs={'min': 1}),
|
'quantity': forms.NumberInput(attrs={'min': 1}),
|
||||||
# Скрываем поля product и product_kit - они будут заполняться через JS
|
# Скрываем поля product и product_kit - они будут заполняться через JS
|
||||||
'product': forms.HiddenInput(),
|
'product': forms.HiddenInput(),
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2026-01-21 07:27
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('orders', '0003_order_summary'),
|
||||||
|
('products', '0001_add_sales_unit_to_kititem'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='kititemsnapshot',
|
||||||
|
name='conversion_factor',
|
||||||
|
field=models.DecimalField(blank=True, decimal_places=6, help_text='Сколько единиц продажи в 1 базовой единице товара', max_digits=15, null=True, verbose_name='Коэффициент конверсии'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='kititemsnapshot',
|
||||||
|
name='original_sales_unit',
|
||||||
|
field=models.ForeignKey(blank=True, help_text='Единица продажи на момент создания снимка', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='kit_item_snapshots', to='products.productsalesunit', verbose_name='Единица продажи'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -168,7 +168,8 @@ class Delivery(models.Model):
|
|||||||
'time_to': 'Время окончания доставки не может быть раньше времени начала'
|
'time_to': 'Время окончания доставки не может быть раньше времени начала'
|
||||||
})
|
})
|
||||||
|
|
||||||
def save(self, *args, **kwargs):
|
def save(self, *args, validate=True, **kwargs):
|
||||||
"""Переопределение save для вызова валидации"""
|
"""Переопределение save для вызова валидации"""
|
||||||
self.full_clean()
|
if validate:
|
||||||
|
self.full_clean()
|
||||||
super().save(*args, **kwargs)
|
super().save(*args, **kwargs)
|
||||||
|
|||||||
@@ -140,6 +140,25 @@ class KitItemSnapshot(models.Model):
|
|||||||
verbose_name="Группа вариантов"
|
verbose_name="Группа вариантов"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
original_sales_unit = models.ForeignKey(
|
||||||
|
'products.ProductSalesUnit',
|
||||||
|
on_delete=models.SET_NULL,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
related_name='kit_item_snapshots',
|
||||||
|
verbose_name="Единица продажи",
|
||||||
|
help_text="Единица продажи на момент создания снимка"
|
||||||
|
)
|
||||||
|
|
||||||
|
conversion_factor = models.DecimalField(
|
||||||
|
max_digits=15,
|
||||||
|
decimal_places=6,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name="Коэффициент конверсии",
|
||||||
|
help_text="Сколько единиц продажи в 1 базовой единице товара"
|
||||||
|
)
|
||||||
|
|
||||||
quantity = models.DecimalField(
|
quantity = models.DecimalField(
|
||||||
max_digits=10,
|
max_digits=10,
|
||||||
decimal_places=3,
|
decimal_places=3,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
{% extends 'base.html' %}
|
{% extends 'base.html' %}
|
||||||
|
{% load inventory_filters %}
|
||||||
|
|
||||||
{% block title %}Заказ {{ order.order_number }}{% endblock %}
|
{% block title %}Заказ {{ order.order_number }}{% endblock %}
|
||||||
|
|
||||||
@@ -337,7 +338,7 @@
|
|||||||
<!-- Кнопка "Применить максимум" -->
|
<!-- Кнопка "Применить максимум" -->
|
||||||
<form method="post" action="{% url 'orders:apply-wallet' order.order_number %}" class="mb-2">
|
<form method="post" action="{% url 'orders:apply-wallet' order.order_number %}" class="mb-2">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<input type="hidden" name="wallet_amount" value="{% if order.customer.wallet_balance < order.amount_due %}{{ order.customer.wallet_balance|floatformat:2 }}{% else %}{{ order.amount_due|floatformat:2 }}{% endif %}">
|
<input type="hidden" name="wallet_amount" value="{% if order.customer.wallet_balance < order.amount_due %}{{ order.customer.wallet_balance|format_decimal:2 }}{% else %}{{ order.amount_due|format_decimal:2 }}{% endif %}">
|
||||||
<button type="submit" class="btn btn-success w-100">
|
<button type="submit" class="btn btn-success w-100">
|
||||||
<i class="bi bi-wallet2"></i> Применить максимум
|
<i class="bi bi-wallet2"></i> Применить максимум
|
||||||
</button>
|
</button>
|
||||||
@@ -351,7 +352,7 @@
|
|||||||
type="number"
|
type="number"
|
||||||
step="0.01"
|
step="0.01"
|
||||||
min="0"
|
min="0"
|
||||||
max="{% if order.customer.wallet_balance < order.amount_due %}{{ order.customer.wallet_balance|floatformat:2 }}{% else %}{{ order.amount_due|floatformat:2 }}{% endif %}"
|
max="{% if order.customer.wallet_balance < order.amount_due %}{{ order.customer.wallet_balance|format_decimal:2 }}{% else %}{{ order.amount_due|format_decimal:2 }}{% endif %}"
|
||||||
name="wallet_amount"
|
name="wallet_amount"
|
||||||
class="form-control"
|
class="form-control"
|
||||||
placeholder="Сумма"
|
placeholder="Сумма"
|
||||||
|
|||||||
@@ -1542,6 +1542,22 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Убедимся, что все поля имеют правильные имена и ID
|
||||||
|
const fields = newForm.querySelectorAll('[name]');
|
||||||
|
fields.forEach(field => {
|
||||||
|
const name = field.getAttribute('name');
|
||||||
|
if (name && name.includes('__prefix__')) {
|
||||||
|
const newName = name.replace(/__prefix__/g, formCount);
|
||||||
|
field.setAttribute('name', newName);
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = field.getAttribute('id');
|
||||||
|
if (id && id.includes('__prefix__')) {
|
||||||
|
const newId = id.replace(/__prefix__/g, formCount);
|
||||||
|
field.setAttribute('id', newId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
updateTotalDisplay();
|
updateTotalDisplay();
|
||||||
|
|
||||||
return newForm;
|
return newForm;
|
||||||
@@ -1560,6 +1576,10 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
// Сохранённая форма - помечаем на удаление
|
// Сохранённая форма - помечаем на удаление
|
||||||
console.log('[removeForm] Помечаем сохранённую форму на удаление (ID:', idField.value, ')');
|
console.log('[removeForm] Помечаем сохранённую форму на удаление (ID:', idField.value, ')');
|
||||||
deleteCheckbox.checked = true;
|
deleteCheckbox.checked = true;
|
||||||
|
// Также добавляем скрытое поле, чтобы гарантировать удаление
|
||||||
|
if (!deleteCheckbox.value) {
|
||||||
|
deleteCheckbox.value = 'on';
|
||||||
|
}
|
||||||
form.classList.add('deleted');
|
form.classList.add('deleted');
|
||||||
form.style.display = 'none';
|
form.style.display = 'none';
|
||||||
updateTotalDisplay();
|
updateTotalDisplay();
|
||||||
@@ -1587,8 +1607,11 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
console.log(`[removeForm] Пересчёт индексов для ${remainingForms.length} оставшихся форм...`);
|
console.log(`[removeForm] Пересчёт индексов для ${remainingForms.length} оставшихся форм...`);
|
||||||
|
|
||||||
remainingForms.forEach((currentForm, newIndex) => {
|
remainingForms.forEach((currentForm, newIndex) => {
|
||||||
// Находим все поля с name="items-N-..."
|
// Обновляем data-атрибут индекса формы
|
||||||
const fields = currentForm.querySelectorAll('[name^="items-"]');
|
currentForm.setAttribute('data-form-index', newIndex);
|
||||||
|
|
||||||
|
// Находим все поля с name="items-N-..." и select элементы
|
||||||
|
const fields = currentForm.querySelectorAll('[name^="items-"], select[name^="items-"]');
|
||||||
fields.forEach(field => {
|
fields.forEach(field => {
|
||||||
const name = field.getAttribute('name');
|
const name = field.getAttribute('name');
|
||||||
// Меняем индекс: items-СТАРЫЙ-поле → items-НОВЫЙ-поле
|
// Меняем индекс: items-СТАРЫЙ-поле → items-НОВЫЙ-поле
|
||||||
@@ -1602,6 +1625,41 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
const newId = field.id.replace(/^id_items-\d+/, `id_items-${newIndex}`);
|
const newId = field.id.replace(/^id_items-\d+/, `id_items-${newIndex}`);
|
||||||
field.setAttribute('id', newId);
|
field.setAttribute('id', newId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Обновляем for атрибут у label, если есть
|
||||||
|
const label = document.querySelector(`label[for="${field.id}"]`);
|
||||||
|
if (label) {
|
||||||
|
label.setAttribute('for', newId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обновляем data-атрибут у select2 элементов
|
||||||
|
if (field.classList.contains('select2-order-item')) {
|
||||||
|
field.setAttribute('data-form-index', newIndex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Обновляем select элементы, если есть
|
||||||
|
const selects = currentForm.querySelectorAll('select');
|
||||||
|
selects.forEach(select => {
|
||||||
|
const name = select.getAttribute('name');
|
||||||
|
if (name && name.startsWith('items-')) {
|
||||||
|
const newName = name.replace(/^items-\d+/, `items-${newIndex}`);
|
||||||
|
if (name !== newName) {
|
||||||
|
select.setAttribute('name', newName);
|
||||||
|
|
||||||
|
// Обновляем ID тоже (для связи с label)
|
||||||
|
if (select.id) {
|
||||||
|
const newId = select.id.replace(/^id_items-\d+/, `id_items-${newIndex}`);
|
||||||
|
select.setAttribute('id', newId);
|
||||||
|
|
||||||
|
// Обновляем for атрибут у label, если есть
|
||||||
|
const label = document.querySelector(`label[for="${select.id}"]`);
|
||||||
|
if (label) {
|
||||||
|
label.setAttribute('for', newId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1656,6 +1714,17 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
// Валидация перед отправкой
|
// Валидация перед отправкой
|
||||||
document.getElementById('order-form').addEventListener('submit', function(e) {
|
document.getElementById('order-form').addEventListener('submit', function(e) {
|
||||||
|
// Убедимся, что все удаленные формы действительно отмечены для удаления
|
||||||
|
const deletedForms = document.querySelectorAll('.order-item-form.deleted');
|
||||||
|
deletedForms.forEach(form => {
|
||||||
|
const deleteCheckbox = form.querySelector('input[name$="-DELETE"]');
|
||||||
|
if (deleteCheckbox) {
|
||||||
|
deleteCheckbox.checked = true;
|
||||||
|
// Убедимся, что значение установлено
|
||||||
|
deleteCheckbox.value = 'on';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Заказ можно сохранить без товаров
|
// Заказ можно сохранить без товаров
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1808,7 +1877,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
// Функция заполнения формы данными комплекта
|
// Функция заполнения формы данными комплекта
|
||||||
function fillFormWithKit(form, kitData) {
|
function fillFormWithKit(form, kitData) {
|
||||||
if (!kitData || !kitData.kit_id || !kitData.kit_name || !kitData.kit_price) {
|
if (!kitData || !kitData.kit_id || !kitData.kit_name || kitData.kit_price === undefined) {
|
||||||
console.error('Invalid kit data:', kitData);
|
console.error('Invalid kit data:', kitData);
|
||||||
alert('Ошибка: неверные данные комплекта');
|
alert('Ошибка: неверные данные комплекта');
|
||||||
return;
|
return;
|
||||||
@@ -1819,6 +1888,11 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
const quantityInput = form.querySelector('[name$="-quantity"]');
|
const quantityInput = form.querySelector('[name$="-quantity"]');
|
||||||
const priceInput = form.querySelector('[name$="-price"]');
|
const priceInput = form.querySelector('[name$="-price"]');
|
||||||
|
|
||||||
|
// ВАЖНО: Находим скрытые поля для product и product_kit
|
||||||
|
const productField = form.querySelector('[name$="-product"]');
|
||||||
|
const kitField = form.querySelector('[name$="-product_kit"]');
|
||||||
|
const isCustomPriceField = form.querySelector('[name$="-is_custom_price"]');
|
||||||
|
|
||||||
if (!kitSelect) {
|
if (!kitSelect) {
|
||||||
console.error('Kit select not found in form');
|
console.error('Kit select not found in form');
|
||||||
return;
|
return;
|
||||||
@@ -1826,7 +1900,17 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
// Используем Select2 API для добавления опции
|
// Используем Select2 API для добавления опции
|
||||||
const newOption = new Option(kitData.kit_name, `kit_${kitData.kit_id}`, true, true);
|
const newOption = new Option(kitData.kit_name, `kit_${kitData.kit_id}`, true, true);
|
||||||
$(kitSelect).append(newOption);
|
$(kitSelect).append(newOption).trigger('change');
|
||||||
|
|
||||||
|
// КЛЮЧЕВОЕ ИСПРАВЛЕНИЕ: Устанавливаем скрытые поля напрямую
|
||||||
|
// Это комплект, поэтому очищаем product и устанавливаем product_kit
|
||||||
|
if (productField) productField.value = '';
|
||||||
|
if (kitField) kitField.value = kitData.kit_id;
|
||||||
|
|
||||||
|
console.log('[fillFormWithKit] Установлены скрытые поля:', {
|
||||||
|
product: productField ? productField.value : 'not found',
|
||||||
|
product_kit: kitField ? kitField.value : 'not found'
|
||||||
|
});
|
||||||
|
|
||||||
// Устанавливаем количество и цену
|
// Устанавливаем количество и цену
|
||||||
if (quantityInput) quantityInput.value = '1';
|
if (quantityInput) quantityInput.value = '1';
|
||||||
@@ -1835,6 +1919,22 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
priceInput.dataset.originalPrice = kitData.kit_price;
|
priceInput.dataset.originalPrice = kitData.kit_price;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Сбрасываем флаг кастомной цены
|
||||||
|
if (isCustomPriceField) {
|
||||||
|
isCustomPriceField.value = 'false';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Скрываем единицы продажи для комплектов (у комплектов их нет)
|
||||||
|
const salesUnitContainer = form.querySelector('.sales-unit-container');
|
||||||
|
if (salesUnitContainer) {
|
||||||
|
salesUnitContainer.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обновляем сумму товаров
|
||||||
|
if (typeof window.updateOrderItemsTotal === 'function') {
|
||||||
|
window.updateOrderItemsTotal();
|
||||||
|
}
|
||||||
|
|
||||||
// Явно вызываем событие select2:select для запуска автосохранения
|
// Явно вызываем событие select2:select для запуска автосохранения
|
||||||
$(kitSelect).trigger('select2:select', {
|
$(kitSelect).trigger('select2:select', {
|
||||||
params: {
|
params: {
|
||||||
|
|||||||
@@ -10,24 +10,21 @@
|
|||||||
max-width: 280px;
|
max-width: 280px;
|
||||||
}
|
}
|
||||||
.order-summary-text {
|
.order-summary-text {
|
||||||
display: -webkit-box;
|
|
||||||
-webkit-box-orient: vertical;
|
|
||||||
-webkit-line-clamp: 3;
|
|
||||||
overflow: hidden;
|
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
color: #212529;
|
color: #212529;
|
||||||
}
|
}
|
||||||
.order-summary-text:hover {
|
.table td {
|
||||||
color: #0d6efd;
|
vertical-align: middle;
|
||||||
}
|
}
|
||||||
.order-summary-text.expanded {
|
.table tbody tr {
|
||||||
-webkit-line-clamp: unset;
|
border-bottom: 2px solid #dee2e6;
|
||||||
max-height: none;
|
}
|
||||||
position: relative;
|
.table tbody tr:last-child {
|
||||||
z-index: 10;
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
.table tbody tr[data-edit-url] {
|
||||||
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -44,7 +41,7 @@
|
|||||||
</h5>
|
</h5>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<form method="get">
|
<form method="get" id="order-filter-form">
|
||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<!-- Поиск -->
|
<!-- Поиск -->
|
||||||
<div class="col-md-3">
|
<div class="col-md-3">
|
||||||
@@ -89,6 +86,19 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Тумблер "Включая завершённые" -->
|
||||||
|
<div class="row mt-3">
|
||||||
|
<div class="col-12">
|
||||||
|
<div class="form-check form-switch">
|
||||||
|
<input type="checkbox" name="show_all_orders" class="form-check-input" id="id_show_all_orders"
|
||||||
|
{% if request.GET.show_all_orders %}checked{% endif %}>
|
||||||
|
<label class="form-check-label" for="id_show_all_orders">
|
||||||
|
Включая завершённые
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Календарный фильтр по дате доставки (вторая строка) -->
|
<!-- Календарный фильтр по дате доставки (вторая строка) -->
|
||||||
<div class="row mt-3">
|
<div class="row mt-3">
|
||||||
<div class="col-12">
|
<div class="col-12">
|
||||||
@@ -118,7 +128,6 @@
|
|||||||
<table class="table table-hover">
|
<table class="table table-hover">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Номер</th>
|
|
||||||
<th>Дата</th>
|
<th>Дата</th>
|
||||||
<th>Время</th>
|
<th>Время</th>
|
||||||
<th>Тип</th>
|
<th>Тип</th>
|
||||||
@@ -127,16 +136,13 @@
|
|||||||
<th>Сумма</th>
|
<th>Сумма</th>
|
||||||
<th>Оплата</th>
|
<th>Оплата</th>
|
||||||
<th>Действия</th>
|
<th>Действия</th>
|
||||||
|
<th>Номер заказа</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for order in page_obj %}
|
{% for order in page_obj %}
|
||||||
<tr {% if order.status and order.status.is_negative_end and order.amount_paid > 0 %}class="table-warning"{% endif %}>
|
<tr {% if order.status and order.status.is_negative_end and order.amount_paid > 0 %}class="table-warning"{% endif %}
|
||||||
<td>
|
data-edit-url="{% url 'orders:order-update' order.order_number %}">
|
||||||
<a href="{% url 'orders:order-detail' order.order_number %}" class="text-decoration-none">
|
|
||||||
<strong>{{ order.order_number }}</strong>
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td>
|
<td>
|
||||||
{% if order.delivery_date %}
|
{% if order.delivery_date %}
|
||||||
{{ order.delivery_date|date:"d.m.Y" }}
|
{{ order.delivery_date|date:"d.m.Y" }}
|
||||||
@@ -160,7 +166,7 @@
|
|||||||
</td>
|
</td>
|
||||||
<td class="order-summary-cell">
|
<td class="order-summary-cell">
|
||||||
{% if order.summary %}
|
{% if order.summary %}
|
||||||
<div class="order-summary-text" title="Клик для раскрытия/сворачивания">{{ order.summary|safe }}</div>
|
<div class="order-summary-text">{{ order.summary|safe }}</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<span class="text-muted">—</span>
|
<span class="text-muted">—</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -215,6 +221,11 @@
|
|||||||
<i class="bi bi-pencil"></i>
|
<i class="bi bi-pencil"></i>
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="{% url 'orders:order-detail' order.order_number %}" class="text-decoration-none">
|
||||||
|
<strong>{{ order.order_number }}</strong>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -381,12 +392,24 @@
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Toggle для раскрытия/сворачивания резюме заказа
|
// Двойной клик на строку для перехода к редактированию
|
||||||
document.querySelectorAll('.order-summary-text').forEach(function(el) {
|
document.querySelectorAll('tbody tr[data-edit-url]').forEach(function(row) {
|
||||||
el.addEventListener('click', function() {
|
row.addEventListener('dblclick', function() {
|
||||||
this.classList.toggle('expanded');
|
const editUrl = this.dataset.editUrl;
|
||||||
|
if (editUrl) {
|
||||||
|
window.location.href = editUrl;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Тумблер "Включая завершённые" - автоматическая отправка формы
|
||||||
|
const showAllOrdersSwitch = document.getElementById('id_show_all_orders');
|
||||||
|
const filterForm = document.getElementById('order-filter-form');
|
||||||
|
if (showAllOrdersSwitch && filterForm) {
|
||||||
|
showAllOrdersSwitch.addEventListener('change', function() {
|
||||||
|
filterForm.submit();
|
||||||
|
});
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -16,11 +16,18 @@ from inventory.models import Reservation
|
|||||||
import json
|
import json
|
||||||
|
|
||||||
|
|
||||||
|
from django.utils import timezone # Added for default date filter
|
||||||
|
|
||||||
def order_list(request):
|
def order_list(request):
|
||||||
"""
|
"""
|
||||||
Список всех заказов с фильтрацией и поиском
|
Список всех заказов с фильтрацией и поиском
|
||||||
Использует django-filter для фильтрации данных
|
Использует django-filter для фильтрации данных
|
||||||
"""
|
"""
|
||||||
|
# Если параметров нет вообще (первый заход), редиректим на "Сегодня"
|
||||||
|
if not request.GET:
|
||||||
|
today = timezone.localdate().isoformat()
|
||||||
|
return redirect(f'{request.path}?delivery_date_after={today}&delivery_date_before={today}')
|
||||||
|
|
||||||
# Базовый queryset с оптимизацией запросов
|
# Базовый queryset с оптимизацией запросов
|
||||||
orders = Order.objects.select_related(
|
orders = Order.objects.select_related(
|
||||||
'customer', 'delivery', 'delivery__address', 'delivery__pickup_warehouse', 'status' # Добавлен 'status' для избежания N+1
|
'customer', 'delivery', 'delivery__address', 'delivery__pickup_warehouse', 'status' # Добавлен 'status' для избежания N+1
|
||||||
@@ -68,26 +75,7 @@ def order_create(request):
|
|||||||
draft_items = []
|
draft_items = []
|
||||||
|
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
# Логирование POST-данных для отладки
|
|
||||||
print("\n=== POST DATA ===")
|
|
||||||
print(f"items-TOTAL_FORMS: {request.POST.get('items-TOTAL_FORMS')}")
|
|
||||||
print(f"items-INITIAL_FORMS: {request.POST.get('items-INITIAL_FORMS')}")
|
|
||||||
print(f"items-MIN_NUM_FORMS: {request.POST.get('items-MIN_NUM_FORMS')}")
|
|
||||||
print(f"items-MAX_NUM_FORMS: {request.POST.get('items-MAX_NUM_FORMS')}")
|
|
||||||
|
|
||||||
# Показываем все формы товаров
|
|
||||||
total_forms = int(request.POST.get('items-TOTAL_FORMS', 0))
|
|
||||||
for i in range(total_forms):
|
|
||||||
product = request.POST.get(f'items-{i}-product', '')
|
|
||||||
kit = request.POST.get(f'items-{i}-product_kit', '')
|
|
||||||
quantity = request.POST.get(f'items-{i}-quantity', '')
|
|
||||||
price = request.POST.get(f'items-{i}-price', '')
|
|
||||||
print(f"\nForm {i}:")
|
|
||||||
print(f" product: {product or '(пусто)'}")
|
|
||||||
print(f" kit: {kit or '(пусто)'}")
|
|
||||||
print(f" quantity: {quantity or '(пусто)'}")
|
|
||||||
print(f" price: {price or '(пусто)'}")
|
|
||||||
print("=== END POST DATA ===\n")
|
|
||||||
|
|
||||||
form = OrderForm(request.POST)
|
form = OrderForm(request.POST)
|
||||||
formset = OrderItemFormSet(request.POST)
|
formset = OrderItemFormSet(request.POST)
|
||||||
@@ -110,7 +98,11 @@ def order_create(request):
|
|||||||
order.recipient = None
|
order.recipient = None
|
||||||
|
|
||||||
# Статус берём из формы (в том числе может быть "Черновик")
|
# Статус берём из формы (в том числе может быть "Черновик")
|
||||||
order.modified_by = request.user
|
from accounts.models import CustomUser
|
||||||
|
if isinstance(request.user, CustomUser):
|
||||||
|
order.modified_by = request.user
|
||||||
|
else:
|
||||||
|
order.modified_by = None
|
||||||
|
|
||||||
# Сохраняем заказ в БД (теперь у него есть pk)
|
# Сохраняем заказ в БД (теперь у него есть pk)
|
||||||
order.save()
|
order.save()
|
||||||
@@ -175,13 +167,61 @@ def order_create(request):
|
|||||||
# Проверяем, является ли заказ черновиком
|
# Проверяем, является ли заказ черновиком
|
||||||
is_draft = order.status and order.status.code == 'draft'
|
is_draft = order.status and order.status.code == 'draft'
|
||||||
|
|
||||||
# Получаем данные из формы (уже провалидированы)
|
# ВАЖНО: Поля доставки НЕ включены в Meta.fields формы OrderForm,
|
||||||
delivery_type = form.cleaned_data.get('delivery_type')
|
# поэтому они не попадают в form.cleaned_data!
|
||||||
delivery_date = form.cleaned_data.get('delivery_date')
|
# Читаем их напрямую из request.POST и обрабатываем вручную
|
||||||
time_from = form.cleaned_data.get('time_from')
|
|
||||||
time_to = form.cleaned_data.get('time_to')
|
# Получаем данные доставки из POST
|
||||||
delivery_cost = form.cleaned_data.get('delivery_cost', Decimal('0'))
|
delivery_type = request.POST.get('delivery_type', None)
|
||||||
pickup_warehouse = form.cleaned_data.get('pickup_warehouse')
|
|
||||||
|
# Обрабатываем дату доставки
|
||||||
|
delivery_date_str = request.POST.get('delivery_date', None)
|
||||||
|
delivery_date = None
|
||||||
|
if delivery_date_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
delivery_date = datetime.strptime(delivery_date_str, '%Y-%m-%d').date()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Обрабатываем время
|
||||||
|
time_from_str = request.POST.get('time_from', None)
|
||||||
|
time_from = None
|
||||||
|
if time_from_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
time_from = datetime.strptime(time_from_str, '%H:%M').time()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
time_to_str = request.POST.get('time_to', None)
|
||||||
|
time_to = None
|
||||||
|
if time_to_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
time_to = datetime.strptime(time_to_str, '%H:%M').time()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Обрабатываем стоимость доставки
|
||||||
|
delivery_cost_str = request.POST.get('delivery_cost', '0')
|
||||||
|
delivery_cost = Decimal('0')
|
||||||
|
if delivery_cost_str:
|
||||||
|
try:
|
||||||
|
delivery_cost = Decimal(delivery_cost_str.replace(',', '.'))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
delivery_cost = Decimal('0')
|
||||||
|
|
||||||
|
# Обрабатываем склад самовывоза
|
||||||
|
pickup_warehouse_id = request.POST.get('pickup_warehouse', None)
|
||||||
|
pickup_warehouse = None
|
||||||
|
if pickup_warehouse_id:
|
||||||
|
try:
|
||||||
|
from inventory.models import Warehouse
|
||||||
|
pickup_warehouse = Warehouse.objects.get(pk=pickup_warehouse_id)
|
||||||
|
except (Warehouse.DoesNotExist, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
# Обрабатываем адрес для курьерской доставки (даже для черновиков, если указан)
|
# Обрабатываем адрес для курьерской доставки (даже для черновиков, если указан)
|
||||||
address = None
|
address = None
|
||||||
@@ -323,6 +363,10 @@ def order_update(request, order_number):
|
|||||||
form = OrderForm(request.POST, instance=order)
|
form = OrderForm(request.POST, instance=order)
|
||||||
formset = OrderItemFormSet(request.POST, instance=order)
|
formset = OrderItemFormSet(request.POST, instance=order)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if form.is_valid() and formset.is_valid():
|
if form.is_valid() and formset.is_valid():
|
||||||
try:
|
try:
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
@@ -334,24 +378,83 @@ def order_update(request, order_number):
|
|||||||
# Сохраняем получателя: если новый - создаем, если существующий - обновляем
|
# Сохраняем получателя: если новый - создаем, если существующий - обновляем
|
||||||
recipient.save() # Django автоматически определит create или update
|
recipient.save() # Django автоматически определит create или update
|
||||||
order.recipient = recipient
|
order.recipient = recipient
|
||||||
else:
|
|
||||||
# Если покупатель является получателем
|
# Если покупатель является получателем
|
||||||
order.recipient = None
|
order.recipient = None
|
||||||
|
|
||||||
order.modified_by = request.user
|
from accounts.models import CustomUser
|
||||||
|
if isinstance(request.user, CustomUser):
|
||||||
|
order.modified_by = request.user
|
||||||
|
else:
|
||||||
|
# Если это админ платформы, не перезаписываем поле (оставляем как есть)
|
||||||
|
pass
|
||||||
|
|
||||||
order.save()
|
order.save()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
formset.save()
|
formset.save()
|
||||||
|
|
||||||
# Проверяем, является ли заказ черновиком
|
# Проверяем, является ли заказ черновиком
|
||||||
is_draft = order.status and order.status.code == 'draft'
|
is_draft = order.status and order.status.code == 'draft'
|
||||||
|
|
||||||
# Получаем данные из формы (уже провалидированы)
|
# ВАЖНО: Поля доставки НЕ включены в Meta.fields формы OrderForm,
|
||||||
delivery_type = form.cleaned_data.get('delivery_type')
|
# поэтому они не попадают в form.cleaned_data!
|
||||||
delivery_date = form.cleaned_data.get('delivery_date')
|
# Читаем их напрямую из request.POST и обрабатываем вручную
|
||||||
time_from = form.cleaned_data.get('time_from')
|
|
||||||
time_to = form.cleaned_data.get('time_to')
|
# Получаем данные доставки из POST
|
||||||
delivery_cost = form.cleaned_data.get('delivery_cost', Decimal('0'))
|
delivery_type = request.POST.get('delivery_type', None)
|
||||||
pickup_warehouse = form.cleaned_data.get('pickup_warehouse')
|
|
||||||
|
# Обрабатываем дату доставки
|
||||||
|
delivery_date_str = request.POST.get('delivery_date', None)
|
||||||
|
delivery_date = None
|
||||||
|
if delivery_date_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
delivery_date = datetime.strptime(delivery_date_str, '%Y-%m-%d').date()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Обрабатываем время
|
||||||
|
time_from_str = request.POST.get('time_from', None)
|
||||||
|
time_from = None
|
||||||
|
if time_from_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
time_from = datetime.strptime(time_from_str, '%H:%M').time()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
print(f"[DEBUG] Error parsing time_from: {time_from_str}")
|
||||||
|
|
||||||
|
time_to_str = request.POST.get('time_to', None)
|
||||||
|
time_to = None
|
||||||
|
if time_to_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
time_to = datetime.strptime(time_to_str, '%H:%M').time()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Обрабатываем стоимость доставки
|
||||||
|
delivery_cost_str = request.POST.get('delivery_cost', '0')
|
||||||
|
delivery_cost = Decimal('0')
|
||||||
|
if delivery_cost_str:
|
||||||
|
try:
|
||||||
|
delivery_cost = Decimal(delivery_cost_str.replace(',', '.'))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
delivery_cost = Decimal('0')
|
||||||
|
|
||||||
|
# Обрабатываем склад самовывоза
|
||||||
|
pickup_warehouse_id = request.POST.get('pickup_warehouse', None)
|
||||||
|
pickup_warehouse = None
|
||||||
|
if pickup_warehouse_id:
|
||||||
|
try:
|
||||||
|
from inventory.models import Warehouse
|
||||||
|
pickup_warehouse = Warehouse.objects.get(pk=pickup_warehouse_id)
|
||||||
|
except (Warehouse.DoesNotExist, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Обрабатываем адрес для курьерской доставки (даже для черновиков, если указан)
|
# Обрабатываем адрес для курьерской доставки (даже для черновиков, если указан)
|
||||||
address = None
|
address = None
|
||||||
@@ -366,7 +469,7 @@ def order_update(request, order_number):
|
|||||||
if is_draft:
|
if is_draft:
|
||||||
# Для черновиков создаем Delivery, если есть хотя бы адрес или данные доставки
|
# Для черновиков создаем Delivery, если есть хотя бы адрес или данные доставки
|
||||||
if address or delivery_type or pickup_warehouse or delivery_date:
|
if address or delivery_type or pickup_warehouse or delivery_date:
|
||||||
Delivery.objects.update_or_create(
|
delivery_obj, created = Delivery.objects.update_or_create(
|
||||||
order=order,
|
order=order,
|
||||||
defaults={
|
defaults={
|
||||||
'delivery_type': delivery_type or Delivery.DELIVERY_TYPE_COURIER,
|
'delivery_type': delivery_type or Delivery.DELIVERY_TYPE_COURIER,
|
||||||
@@ -378,8 +481,9 @@ def order_update(request, order_number):
|
|||||||
'cost': delivery_cost if delivery_cost else Decimal('0')
|
'cost': delivery_cost if delivery_cost else Decimal('0')
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
elif hasattr(order, 'delivery'):
|
elif hasattr(order, 'delivery'):
|
||||||
# Если заказ стал черновиком и нет данных доставки, удаляем Delivery
|
|
||||||
order.delivery.delete()
|
order.delivery.delete()
|
||||||
else:
|
else:
|
||||||
# Для не-черновиков проверяем обязательные поля
|
# Для не-черновиков проверяем обязательные поля
|
||||||
@@ -409,6 +513,7 @@ def order_update(request, order_number):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# Пересчитываем итоговую стоимость
|
# Пересчитываем итоговую стоимость
|
||||||
order.calculate_total()
|
order.calculate_total()
|
||||||
order.update_payment_status()
|
order.update_payment_status()
|
||||||
@@ -429,17 +534,7 @@ def order_update(request, order_number):
|
|||||||
# Транзакция откатилась, статус НЕ изменился
|
# Транзакция откатилась, статус НЕ изменился
|
||||||
messages.error(request, f'Ошибка при сохранении заказа: {e}')
|
messages.error(request, f'Ошибка при сохранении заказа: {e}')
|
||||||
else:
|
else:
|
||||||
# Логируем ошибки для отладки
|
|
||||||
print("\n=== ОШИБКИ ВАЛИДАЦИИ ФОРМЫ ===")
|
|
||||||
if not form.is_valid():
|
|
||||||
print(f"OrderForm errors: {form.errors}")
|
|
||||||
if not formset.is_valid():
|
|
||||||
print(f"OrderItemFormSet errors: {formset.errors}")
|
|
||||||
print(f"OrderItemFormSet non_form_errors: {formset.non_form_errors()}")
|
|
||||||
for i, item_form in enumerate(formset):
|
|
||||||
if item_form.errors:
|
|
||||||
print(f" Item form {i} errors: {item_form.errors}")
|
|
||||||
print("=== КОНЕЦ ОШИБОК ===\n")
|
|
||||||
messages.error(request, 'Пожалуйста, исправьте ошибки в форме.')
|
messages.error(request, 'Пожалуйста, исправьте ошибки в форме.')
|
||||||
else:
|
else:
|
||||||
form = OrderForm(instance=order)
|
form = OrderForm(instance=order)
|
||||||
|
|||||||
@@ -32,6 +32,14 @@ body {
|
|||||||
flex-grow: 1;
|
flex-grow: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 3 колонки для товаров и категорий на экранах от 400px */
|
||||||
|
@media (min-width: 400px) {
|
||||||
|
.col-custom-3 {
|
||||||
|
flex: 0 0 33.333%;
|
||||||
|
max-width: 33.333%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* 5 колонок для товаров и категорий на экранах от 1100px */
|
/* 5 колонок для товаров и категорий на экранах от 1100px */
|
||||||
@media (min-width: 1100px) {
|
@media (min-width: 1100px) {
|
||||||
.col-lg-custom-5 {
|
.col-lg-custom-5 {
|
||||||
@@ -845,3 +853,62 @@ body {
|
|||||||
margin-top: 90px; /* учитываем поиск и категории */
|
margin-top: 90px; /* учитываем поиск и категории */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
МОБИЛЬНЫЙ DROPDOWN "ЕЩЁ"
|
||||||
|
============================================================ */
|
||||||
|
|
||||||
|
/* Кнопка dropdown */
|
||||||
|
.mobile-cart-actions .dropdown-toggle {
|
||||||
|
min-width: 44px;
|
||||||
|
padding: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Меню dropdown */
|
||||||
|
.mobile-cart-actions .dropdown-menu {
|
||||||
|
min-width: 180px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Пункты меню */
|
||||||
|
.mobile-cart-actions .dropdown-item {
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-cart-actions .dropdown-item i {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
ИНТЕРАКТИВНОСТЬ СТРОКИ КОРЗИНЫ (редактирование товара)
|
||||||
|
============================================================ */
|
||||||
|
|
||||||
|
/* Интерактивность строки корзины при наведении */
|
||||||
|
.cart-item {
|
||||||
|
transition: background-color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-item:hover {
|
||||||
|
background-color: #f8f9fa !important;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding-left: 0.5rem !important;
|
||||||
|
padding-right: 0.5rem !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Исключаем hover для витринных комплектов - они сохраняют свой фон */
|
||||||
|
.cart-item[style*="background-color"]:hover {
|
||||||
|
background-color: #ffe6a0 !important; /* чуть светлее желтого */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Индикатор изменённой цены */
|
||||||
|
.cart-item.price-overridden .item-name-price .text-muted {
|
||||||
|
color: #f59e0b !important;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-item.price-overridden .item-name-price .text-muted::after {
|
||||||
|
content: ' *';
|
||||||
|
color: #f59e0b;
|
||||||
|
}
|
||||||
|
|||||||
213
myproject/pos/static/pos/js/cart-item-editor.js
Normal file
213
myproject/pos/static/pos/js/cart-item-editor.js
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
/**
|
||||||
|
* Модуль редактирования товара в корзине POS-терминала
|
||||||
|
* Отвечает за открытие модалки и сохранение изменений
|
||||||
|
*/
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
let editingCartKey = null;
|
||||||
|
let basePrice = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Округление цены до 2 знаков
|
||||||
|
*/
|
||||||
|
function roundPrice(value) {
|
||||||
|
if (value === null || value === undefined || isNaN(value)) return '0.00';
|
||||||
|
return (Number(value)).toFixed(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Открытие модалки редактирования
|
||||||
|
* @param {string} cartKey - ключ товара в корзине
|
||||||
|
*/
|
||||||
|
function openModal(cartKey) {
|
||||||
|
const item = window.cart?.get(cartKey);
|
||||||
|
if (!item) {
|
||||||
|
console.error('CartItemEditor: Item not found for key:', cartKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем наличие модалки
|
||||||
|
const modalEl = document.getElementById('editCartItemModal');
|
||||||
|
if (!modalEl) {
|
||||||
|
console.error('CartItemEditor: Modal element not found!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
editingCartKey = cartKey;
|
||||||
|
basePrice = parseFloat(item.price) || 0;
|
||||||
|
|
||||||
|
// Проверяем, является ли товар витринным комплектом
|
||||||
|
const isShowcaseKit = item.type === 'showcase_kit';
|
||||||
|
|
||||||
|
// Заполнение полей
|
||||||
|
document.getElementById('editModalProductName').textContent = item.name || '—';
|
||||||
|
|
||||||
|
// Используем formatMoney из terminal.js
|
||||||
|
const fmtMoney = typeof formatMoney === 'function' ? formatMoney : (v) => Number(v).toFixed(2);
|
||||||
|
document.getElementById('editModalBasePrice').textContent = fmtMoney(basePrice) + ' руб.';
|
||||||
|
|
||||||
|
document.getElementById('editModalPrice').value = roundPrice(basePrice);
|
||||||
|
document.getElementById('editModalQuantity').value = item.qty || 1;
|
||||||
|
|
||||||
|
// Для витринных комплектов блокируем изменение количества
|
||||||
|
const qtyInput = document.getElementById('editModalQuantity');
|
||||||
|
const qtyHint = document.getElementById('editModalQtyHint');
|
||||||
|
if (isShowcaseKit) {
|
||||||
|
qtyInput.disabled = true;
|
||||||
|
qtyHint.style.display = 'block';
|
||||||
|
} else {
|
||||||
|
qtyInput.disabled = false;
|
||||||
|
qtyHint.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Бейдж единицы измерения
|
||||||
|
const unitBadge = document.getElementById('editModalUnitBadge');
|
||||||
|
if (item.unit_name) {
|
||||||
|
unitBadge.textContent = item.unit_name;
|
||||||
|
unitBadge.style.display = 'inline-block';
|
||||||
|
} else {
|
||||||
|
unitBadge.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
updateTotal();
|
||||||
|
|
||||||
|
// Показ модалки
|
||||||
|
const modal = new bootstrap.Modal(modalEl);
|
||||||
|
modal.show();
|
||||||
|
|
||||||
|
console.log('CartItemEditor: Modal opened for', item.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Обновление суммы в модалке
|
||||||
|
*/
|
||||||
|
function updateTotal() {
|
||||||
|
const price = parseFloat(document.getElementById('editModalPrice').value) || 0;
|
||||||
|
const qty = parseFloat(document.getElementById('editModalQuantity').value) || 0;
|
||||||
|
|
||||||
|
const fmtMoney = typeof formatMoney === 'function' ? formatMoney : (v) => Number(v).toFixed(2);
|
||||||
|
document.getElementById('editModalTotal').textContent = fmtMoney(price * qty) + ' руб.';
|
||||||
|
|
||||||
|
// Индикатор изменения цены
|
||||||
|
const warning = document.getElementById('editModalPriceWarning');
|
||||||
|
if (Math.abs(price - basePrice) > 0.01) {
|
||||||
|
warning.style.display = 'block';
|
||||||
|
} else {
|
||||||
|
warning.style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сохранение изменений
|
||||||
|
*/
|
||||||
|
function saveChanges() {
|
||||||
|
if (!editingCartKey) return;
|
||||||
|
|
||||||
|
const newPrice = parseFloat(document.getElementById('editModalPrice').value) || 0;
|
||||||
|
const newQty = parseFloat(document.getElementById('editModalQuantity').value) || 1;
|
||||||
|
|
||||||
|
const item = window.cart?.get(editingCartKey);
|
||||||
|
if (item) {
|
||||||
|
// Используем roundQuantity из terminal.js
|
||||||
|
const rndQty = typeof roundQuantity === 'function' ? roundQuantity : (v, d) => Math.round(v * Math.pow(10, d)) / Math.pow(10, d);
|
||||||
|
|
||||||
|
const isShowcaseKit = item.type === 'showcase_kit';
|
||||||
|
|
||||||
|
item.price = newPrice;
|
||||||
|
// Для витринных комплектов не меняем количество
|
||||||
|
if (!isShowcaseKit) {
|
||||||
|
item.qty = rndQty(newQty, 3);
|
||||||
|
}
|
||||||
|
item.price_overridden = Math.abs(newPrice - basePrice) > 0.01;
|
||||||
|
|
||||||
|
window.cart.set(editingCartKey, item);
|
||||||
|
|
||||||
|
// Перерисовка корзины
|
||||||
|
if (typeof renderCart === 'function') {
|
||||||
|
renderCart();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сохранение на сервере
|
||||||
|
if (typeof saveCartToServer === 'function') {
|
||||||
|
saveCartToServer();
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('CartItemEditor: Changes saved for', item.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Закрытие модалки
|
||||||
|
const modalEl = document.getElementById('editCartItemModal');
|
||||||
|
const modal = bootstrap.Modal.getInstance(modalEl);
|
||||||
|
if (modal) modal.hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сброс состояния модалки
|
||||||
|
*/
|
||||||
|
function reset() {
|
||||||
|
editingCartKey = null;
|
||||||
|
basePrice = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Инициализация модуля
|
||||||
|
*/
|
||||||
|
function init() {
|
||||||
|
const priceInput = document.getElementById('editModalPrice');
|
||||||
|
const qtyInput = document.getElementById('editModalQuantity');
|
||||||
|
const confirmBtn = document.getElementById('confirmEditCartItem');
|
||||||
|
|
||||||
|
if (!priceInput || !confirmBtn) {
|
||||||
|
console.warn('CartItemEditor: Required elements not found, deferring init...');
|
||||||
|
// Повторная попытка через короткое время
|
||||||
|
setTimeout(init, 100);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('CartItemEditor: Initialized successfully');
|
||||||
|
|
||||||
|
// Обновление суммы при изменении полей
|
||||||
|
priceInput.addEventListener('input', updateTotal);
|
||||||
|
qtyInput.addEventListener('input', updateTotal);
|
||||||
|
|
||||||
|
// Авто-выделение всего текста при фокусе
|
||||||
|
priceInput.addEventListener('focus', function() {
|
||||||
|
this.select();
|
||||||
|
});
|
||||||
|
qtyInput.addEventListener('focus', function() {
|
||||||
|
this.select();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Кнопка сохранения
|
||||||
|
confirmBtn.addEventListener('click', saveChanges);
|
||||||
|
|
||||||
|
// Сброс при закрытии модалки
|
||||||
|
const modalEl = document.getElementById('editCartItemModal');
|
||||||
|
modalEl.addEventListener('hidden.bs.modal', reset);
|
||||||
|
|
||||||
|
// Enter для сохранения
|
||||||
|
priceInput.addEventListener('keypress', function(e) {
|
||||||
|
if (e.key === 'Enter') saveChanges();
|
||||||
|
});
|
||||||
|
qtyInput.addEventListener('keypress', function(e) {
|
||||||
|
if (e.key === 'Enter') saveChanges();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Экспорт функций для использования из terminal.js
|
||||||
|
window.CartItemEditor = {
|
||||||
|
openModal: openModal,
|
||||||
|
init: init
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('CartItemEditor: Module loaded');
|
||||||
|
|
||||||
|
// Автоинициализация при загрузке
|
||||||
|
if (document.readyState === 'loading') {
|
||||||
|
document.addEventListener('DOMContentLoaded', init);
|
||||||
|
} else {
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -12,6 +12,38 @@ function roundQuantity(value, decimals = 3) {
|
|||||||
return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
|
return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Показывает toast уведомление в правом верхнем углу
|
||||||
|
* @param {string} type - 'success' или 'error'
|
||||||
|
* @param {string} message - Текст сообщения
|
||||||
|
*/
|
||||||
|
function showToast(type, message) {
|
||||||
|
const toastId = type === 'success' ? 'orderSuccessToast' : 'orderErrorToast';
|
||||||
|
const messageId = type === 'success' ? 'toastMessage' : 'errorMessage';
|
||||||
|
const bgClass = type === 'success' ? 'bg-success' : 'bg-danger';
|
||||||
|
|
||||||
|
const toastElement = document.getElementById(toastId);
|
||||||
|
const messageElement = document.getElementById(messageId);
|
||||||
|
|
||||||
|
// Устанавливаем сообщение
|
||||||
|
messageElement.textContent = message;
|
||||||
|
|
||||||
|
// Добавляем цвет фона
|
||||||
|
toastElement.classList.add(bgClass, 'text-white');
|
||||||
|
|
||||||
|
// Создаём и показываем toast (автоматически скроется через 5 секунд - стандарт Bootstrap)
|
||||||
|
const toast = new bootstrap.Toast(toastElement, {
|
||||||
|
delay: 5000,
|
||||||
|
autohide: true
|
||||||
|
});
|
||||||
|
toast.show();
|
||||||
|
|
||||||
|
// Убираем класс цвета после скрытия
|
||||||
|
toastElement.addEventListener('hidden.bs.toast', () => {
|
||||||
|
toastElement.classList.remove(bgClass, 'text-white');
|
||||||
|
}, { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
const CATEGORIES = JSON.parse(document.getElementById('categoriesData').textContent);
|
const CATEGORIES = JSON.parse(document.getElementById('categoriesData').textContent);
|
||||||
let ITEMS = []; // Будем загружать через API
|
let ITEMS = []; // Будем загружать через API
|
||||||
let showcaseKits = JSON.parse(document.getElementById('showcaseKitsData').textContent);
|
let showcaseKits = JSON.parse(document.getElementById('showcaseKitsData').textContent);
|
||||||
@@ -19,6 +51,8 @@ let showcaseKits = JSON.parse(document.getElementById('showcaseKitsData').textCo
|
|||||||
let currentCategoryId = null;
|
let currentCategoryId = null;
|
||||||
let isShowcaseView = false;
|
let isShowcaseView = false;
|
||||||
const cart = new Map();
|
const cart = new Map();
|
||||||
|
// Экспорт корзины для использования в других модулях
|
||||||
|
window.cart = cart;
|
||||||
|
|
||||||
// Переменные для пагинации
|
// Переменные для пагинации
|
||||||
let currentPage = 1;
|
let currentPage = 1;
|
||||||
@@ -70,15 +104,15 @@ function saveCartToRedis() {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({ cart: cartObj })
|
body: JSON.stringify({ cart: cartObj })
|
||||||
})
|
})
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (!data.success) {
|
if (!data.success) {
|
||||||
console.error('Ошибка сохранения корзины:', data.error);
|
console.error('Ошибка сохранения корзины:', data.error);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
console.error('Ошибка при сохранении корзины в Redis:', error);
|
console.error('Ошибка при сохранении корзины в Redis:', error);
|
||||||
});
|
});
|
||||||
}, 500); // Debounce 500ms
|
}, 500); // Debounce 500ms
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +130,37 @@ function formatMoney(v) {
|
|||||||
return (Number(v)).toFixed(2);
|
return (Number(v)).toFixed(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Форматирует дату как относительное время в русском языке
|
||||||
|
* @param {string|null} isoDate - ISO дата или null
|
||||||
|
* @returns {string} - "0 дней", "1 день", "2 дня", "5 дней", и т.д.
|
||||||
|
*/
|
||||||
|
function formatDaysAgo(isoDate) {
|
||||||
|
if (!isoDate) return '';
|
||||||
|
|
||||||
|
const created = new Date(isoDate);
|
||||||
|
const now = new Date();
|
||||||
|
const diffMs = now - created;
|
||||||
|
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||||
|
|
||||||
|
// Русские формы множественного числа
|
||||||
|
const lastTwo = diffDays % 100;
|
||||||
|
const lastOne = diffDays % 10;
|
||||||
|
|
||||||
|
let suffix;
|
||||||
|
if (lastTwo >= 11 && lastTwo <= 19) {
|
||||||
|
suffix = 'дней';
|
||||||
|
} else if (lastOne === 1) {
|
||||||
|
suffix = 'день';
|
||||||
|
} else if (lastOne >= 2 && lastOne <= 4) {
|
||||||
|
suffix = 'дня';
|
||||||
|
} else {
|
||||||
|
suffix = 'дней';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${diffDays} ${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
// ===== ФУНКЦИИ ДЛЯ РАБОТЫ С КЛИЕНТОМ =====
|
// ===== ФУНКЦИИ ДЛЯ РАБОТЫ С КЛИЕНТОМ =====
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -127,7 +192,7 @@ function updateCustomerDisplay() {
|
|||||||
// Обновляем видимость кнопок сброса (в корзине и в модалке продажи)
|
// Обновляем видимость кнопок сброса (в корзине и в модалке продажи)
|
||||||
|
|
||||||
[document.getElementById('resetCustomerBtn'),
|
[document.getElementById('resetCustomerBtn'),
|
||||||
document.getElementById('checkoutResetCustomerBtn')].forEach(resetBtn => {
|
document.getElementById('checkoutResetCustomerBtn')].forEach(resetBtn => {
|
||||||
if (resetBtn) {
|
if (resetBtn) {
|
||||||
resetBtn.style.display = isSystemCustomer ? 'none' : 'block';
|
resetBtn.style.display = isSystemCustomer ? 'none' : 'block';
|
||||||
}
|
}
|
||||||
@@ -209,18 +274,18 @@ function selectCustomer(customerId, customerName, walletBalance = 0) {
|
|||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (!data.success) {
|
if (!data.success) {
|
||||||
console.error('Ошибка сохранения клиента:', data.error);
|
console.error('Ошибка сохранения клиента:', data.error);
|
||||||
} else {
|
} else {
|
||||||
// Обновляем баланс из ответа сервера
|
// Обновляем баланс из ответа сервера
|
||||||
selectedCustomer.wallet_balance = data.wallet_balance || 0;
|
selectedCustomer.wallet_balance = data.wallet_balance || 0;
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
console.error('Ошибка при сохранении клиента в Redis:', error);
|
console.error('Ошибка при сохранении клиента в Redis:', error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -239,12 +304,12 @@ function initCustomerSelect2() {
|
|||||||
url: '/customers/api/search/',
|
url: '/customers/api/search/',
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
delay: 300,
|
delay: 300,
|
||||||
data: function(params) {
|
data: function (params) {
|
||||||
return {
|
return {
|
||||||
q: params.term
|
q: params.term
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
processResults: function(data) {
|
processResults: function (data) {
|
||||||
return {
|
return {
|
||||||
results: data.results
|
results: data.results
|
||||||
};
|
};
|
||||||
@@ -256,7 +321,7 @@ function initCustomerSelect2() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Обработка выбора клиента из списка
|
// Обработка выбора клиента из списка
|
||||||
$searchInput.on('select2:select', function(e) {
|
$searchInput.on('select2:select', function (e) {
|
||||||
const data = e.params.data;
|
const data = e.params.data;
|
||||||
|
|
||||||
// Проверяем это не опция "Создать нового клиента"
|
// Проверяем это не опция "Создать нового клиента"
|
||||||
@@ -699,7 +764,7 @@ function renderCategories() {
|
|||||||
|
|
||||||
// Кнопка "Витрина" - первая в ряду
|
// Кнопка "Витрина" - первая в ряду
|
||||||
const showcaseCol = document.createElement('div');
|
const showcaseCol = document.createElement('div');
|
||||||
showcaseCol.className = 'col-6 col-sm-4 col-md-3 col-lg-2';
|
showcaseCol.className = 'col-6 col-custom-3 col-md-3 col-lg-2';
|
||||||
const showcaseCard = document.createElement('div');
|
const showcaseCard = document.createElement('div');
|
||||||
showcaseCard.className = 'card category-card showcase-card' + (isShowcaseView ? ' active' : '');
|
showcaseCard.className = 'card category-card showcase-card' + (isShowcaseView ? ' active' : '');
|
||||||
showcaseCard.style.backgroundColor = '#fff3cd';
|
showcaseCard.style.backgroundColor = '#fff3cd';
|
||||||
@@ -723,7 +788,7 @@ function renderCategories() {
|
|||||||
|
|
||||||
// Кнопка "Все"
|
// Кнопка "Все"
|
||||||
const allCol = document.createElement('div');
|
const allCol = document.createElement('div');
|
||||||
allCol.className = 'col-6 col-sm-4 col-md-3 col-lg-2';
|
allCol.className = 'col-6 col-custom-3 col-md-3 col-lg-2';
|
||||||
const allCard = document.createElement('div');
|
const allCard = document.createElement('div');
|
||||||
allCard.className = 'card category-card' + (currentCategoryId === null && !isShowcaseView ? ' active' : '');
|
allCard.className = 'card category-card' + (currentCategoryId === null && !isShowcaseView ? ' active' : '');
|
||||||
allCard.onclick = async () => {
|
allCard.onclick = async () => {
|
||||||
@@ -747,7 +812,7 @@ function renderCategories() {
|
|||||||
// Категории
|
// Категории
|
||||||
CATEGORIES.forEach(cat => {
|
CATEGORIES.forEach(cat => {
|
||||||
const col = document.createElement('div');
|
const col = document.createElement('div');
|
||||||
col.className = 'col-6 col-sm-4 col-md-3 col-lg-custom-5';
|
col.className = 'col-6 col-custom-3 col-md-3 col-lg-custom-5';
|
||||||
|
|
||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'card category-card' + (currentCategoryId === cat.id && !isShowcaseView ? ' active' : '');
|
card.className = 'card category-card' + (currentCategoryId === cat.id && !isShowcaseView ? ' active' : '');
|
||||||
@@ -802,7 +867,7 @@ function renderProducts() {
|
|||||||
|
|
||||||
filtered.forEach(item => {
|
filtered.forEach(item => {
|
||||||
const col = document.createElement('div');
|
const col = document.createElement('div');
|
||||||
col.className = 'col-6 col-sm-4 col-md-3 col-lg-custom-5';
|
col.className = 'col-6 col-custom-3 col-md-3 col-lg-custom-5';
|
||||||
|
|
||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'card product-card';
|
card.className = 'card product-card';
|
||||||
@@ -857,6 +922,28 @@ function renderProducts() {
|
|||||||
openEditKitModal(item.id);
|
openEditKitModal(item.id);
|
||||||
};
|
};
|
||||||
card.appendChild(editBtn);
|
card.appendChild(editBtn);
|
||||||
|
|
||||||
|
// Индикатор неактуальной цены (красный кружок)
|
||||||
|
if (item.price_outdated) {
|
||||||
|
const outdatedBadge = document.createElement('div');
|
||||||
|
outdatedBadge.className = 'badge bg-danger';
|
||||||
|
outdatedBadge.style.position = 'absolute';
|
||||||
|
outdatedBadge.style.top = '5px';
|
||||||
|
outdatedBadge.style.right = '45px';
|
||||||
|
outdatedBadge.style.zIndex = '10';
|
||||||
|
outdatedBadge.style.width = '18px';
|
||||||
|
outdatedBadge.style.height = '18px';
|
||||||
|
outdatedBadge.style.padding = '0';
|
||||||
|
outdatedBadge.style.borderRadius = '50%';
|
||||||
|
outdatedBadge.style.display = 'flex';
|
||||||
|
outdatedBadge.style.alignItems = 'center';
|
||||||
|
outdatedBadge.style.justifyContent = 'center';
|
||||||
|
outdatedBadge.style.fontSize = '10px';
|
||||||
|
outdatedBadge.style.minWidth = '18px';
|
||||||
|
outdatedBadge.title = 'Цена неактуальна';
|
||||||
|
outdatedBadge.innerHTML = '!';
|
||||||
|
card.appendChild(outdatedBadge);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -887,7 +974,7 @@ function renderProducts() {
|
|||||||
const stock = document.createElement('div');
|
const stock = document.createElement('div');
|
||||||
stock.className = 'product-stock';
|
stock.className = 'product-stock';
|
||||||
|
|
||||||
// Для витринных комплектов показываем название витрины И количество (доступно/всего)
|
// Для витринных комплектов показываем количество (доступно/всего) и дней на витрине
|
||||||
if (item.type === 'showcase_kit') {
|
if (item.type === 'showcase_kit') {
|
||||||
const availableCount = item.available_count || 0;
|
const availableCount = item.available_count || 0;
|
||||||
const totalCount = item.total_count || availableCount;
|
const totalCount = item.total_count || availableCount;
|
||||||
@@ -898,7 +985,14 @@ function renderProducts() {
|
|||||||
let badgeText = totalCount > 1 ? `${availableCount}/${totalCount}` : `${availableCount}`;
|
let badgeText = totalCount > 1 ? `${availableCount}/${totalCount}` : `${availableCount}`;
|
||||||
let cartInfo = inCart > 0 ? ` <span class="badge bg-warning text-dark">🛒${inCart}</span>` : '';
|
let cartInfo = inCart > 0 ? ` <span class="badge bg-warning text-dark">🛒${inCart}</span>` : '';
|
||||||
|
|
||||||
stock.innerHTML = `🌺 ${item.showcase_name} <span class="badge ${badgeClass} ms-1">${badgeText}</span>${cartInfo}`;
|
// Добавляем отображение дней с момента создания как бейдж справа
|
||||||
|
const daysAgo = formatDaysAgo(item.showcase_created_at);
|
||||||
|
const daysBadge = daysAgo ? ` <span class="badge bg-info ms-auto">${daysAgo}</span>` : '';
|
||||||
|
|
||||||
|
stock.innerHTML = `<span class="badge ${badgeClass}" style="font-size: 0.9rem;">${badgeText}</span>${daysBadge}${cartInfo}`;
|
||||||
|
stock.style.display = 'flex';
|
||||||
|
stock.style.justifyContent = 'space-between';
|
||||||
|
stock.style.alignItems = 'center';
|
||||||
stock.style.color = '#856404';
|
stock.style.color = '#856404';
|
||||||
stock.style.fontWeight = 'bold';
|
stock.style.fontWeight = 'bold';
|
||||||
} else if (item.type === 'product' && item.available_qty !== undefined && item.reserved_qty !== undefined) {
|
} else if (item.type === 'product' && item.available_qty !== undefined && item.reserved_qty !== undefined) {
|
||||||
@@ -1270,6 +1364,13 @@ function renderCart() {
|
|||||||
cart.forEach((item, cartKey) => {
|
cart.forEach((item, cartKey) => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'cart-item mb-2';
|
row.className = 'cart-item mb-2';
|
||||||
|
row.style.cursor = 'pointer';
|
||||||
|
row.title = 'Нажмите для редактирования';
|
||||||
|
|
||||||
|
// Индикатор изменённой цены
|
||||||
|
if (item.price_overridden) {
|
||||||
|
row.classList.add('price-overridden');
|
||||||
|
}
|
||||||
|
|
||||||
// СПЕЦИАЛЬНАЯ СТИЛИЗАЦИЯ для витринных комплектов
|
// СПЕЦИАЛЬНАЯ СТИЛИЗАЦИЯ для витринных комплектов
|
||||||
const isShowcaseKit = item.type === 'showcase_kit';
|
const isShowcaseKit = item.type === 'showcase_kit';
|
||||||
@@ -1417,6 +1518,20 @@ function renderCart() {
|
|||||||
row.appendChild(itemTotal);
|
row.appendChild(itemTotal);
|
||||||
row.appendChild(deleteBtn);
|
row.appendChild(deleteBtn);
|
||||||
|
|
||||||
|
// Обработчик клика для редактирования товара
|
||||||
|
row.addEventListener('click', function (e) {
|
||||||
|
// Игнорируем клики на кнопки управления количеством и удаления
|
||||||
|
if (e.target.closest('button') || e.target.closest('input')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log('Cart row clicked, cartKey:', cartKey, 'CartItemEditor:', typeof window.CartItemEditor);
|
||||||
|
if (window.CartItemEditor) {
|
||||||
|
window.CartItemEditor.openModal(cartKey);
|
||||||
|
} else {
|
||||||
|
console.error('CartItemEditor not available!');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
list.appendChild(row);
|
list.appendChild(row);
|
||||||
|
|
||||||
total += item.qty * item.price;
|
total += item.qty * item.price;
|
||||||
@@ -1734,12 +1849,12 @@ async function openCreateTempKitModal() {
|
|||||||
// Копируем содержимое cart в tempCart (изолированное состояние модалки)
|
// Копируем содержимое cart в tempCart (изолированное состояние модалки)
|
||||||
tempCart.clear();
|
tempCart.clear();
|
||||||
cart.forEach((item, key) => {
|
cart.forEach((item, key) => {
|
||||||
tempCart.set(key, {...item}); // Глубокая копия объекта
|
tempCart.set(key, { ...item }); // Глубокая копия объекта
|
||||||
});
|
});
|
||||||
|
|
||||||
// Генерируем название по умолчанию
|
// Генерируем название по умолчанию
|
||||||
const now = new Date();
|
const randomSuffix = Math.floor(Math.random() * 900) + 100;
|
||||||
const defaultName = `Витрина — ${now.toLocaleDateString('ru-RU')} ${now.toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'})}`;
|
const defaultName = `Витринный букет ${randomSuffix}`;
|
||||||
document.getElementById('tempKitName').value = defaultName;
|
document.getElementById('tempKitName').value = defaultName;
|
||||||
|
|
||||||
// Загружаем список витрин
|
// Загружаем список витрин
|
||||||
@@ -1782,6 +1897,7 @@ async function openEditKitModal(kitId) {
|
|||||||
id: item.product_id,
|
id: item.product_id,
|
||||||
name: item.name,
|
name: item.name,
|
||||||
price: Number(item.price),
|
price: Number(item.price),
|
||||||
|
actual_catalog_price: item.actual_catalog_price ? Number(item.actual_catalog_price) : Number(item.price),
|
||||||
qty: Number(item.qty),
|
qty: Number(item.qty),
|
||||||
type: 'product'
|
type: 'product'
|
||||||
});
|
});
|
||||||
@@ -1791,6 +1907,19 @@ async function openEditKitModal(kitId) {
|
|||||||
// Заполняем поля формы
|
// Заполняем поля формы
|
||||||
document.getElementById('tempKitName').value = kit.name;
|
document.getElementById('tempKitName').value = kit.name;
|
||||||
document.getElementById('tempKitDescription').value = kit.description;
|
document.getElementById('tempKitDescription').value = kit.description;
|
||||||
|
|
||||||
|
// Заполняем поле даты размещения на витрине
|
||||||
|
if (kit.showcase_created_at) {
|
||||||
|
// Конвертируем ISO в формат datetime-local (YYYY-MM-DDTHH:MM)
|
||||||
|
const date = new Date(kit.showcase_created_at);
|
||||||
|
// Компенсация смещения часового пояса
|
||||||
|
const offset = date.getTimezoneOffset() * 60000;
|
||||||
|
const localDate = new Date(date.getTime() - offset);
|
||||||
|
document.getElementById('showcaseCreatedAt').value = localDate.toISOString().slice(0, 16);
|
||||||
|
} else {
|
||||||
|
document.getElementById('showcaseCreatedAt').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
document.getElementById('priceAdjustmentType').value = kit.price_adjustment_type;
|
document.getElementById('priceAdjustmentType').value = kit.price_adjustment_type;
|
||||||
document.getElementById('priceAdjustmentValue').value = kit.price_adjustment_value;
|
document.getElementById('priceAdjustmentValue').value = kit.price_adjustment_value;
|
||||||
|
|
||||||
@@ -1826,6 +1955,7 @@ async function openEditKitModal(kitId) {
|
|||||||
|
|
||||||
// По<D09F><D0BE>азываем кнопку "Разобрать" и блок добавления товаров
|
// По<D09F><D0BE>азываем кнопку "Разобрать" и блок добавления товаров
|
||||||
document.getElementById('disassembleKitBtn').style.display = 'block';
|
document.getElementById('disassembleKitBtn').style.display = 'block';
|
||||||
|
document.getElementById('writeOffKitBtn').style.display = 'block';
|
||||||
document.getElementById('showcaseKitQuantityBlock').style.display = 'none';
|
document.getElementById('showcaseKitQuantityBlock').style.display = 'none';
|
||||||
document.getElementById('addProductBlock').style.display = 'block';
|
document.getElementById('addProductBlock').style.display = 'block';
|
||||||
|
|
||||||
@@ -1833,7 +1963,7 @@ async function openEditKitModal(kitId) {
|
|||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (window.ProductSearchPicker) {
|
if (window.ProductSearchPicker) {
|
||||||
const picker = ProductSearchPicker.init('#temp-kit-product-picker', {
|
const picker = ProductSearchPicker.init('#temp-kit-product-picker', {
|
||||||
onAddSelected: function(product, instance) {
|
onAddSelected: function (product, instance) {
|
||||||
if (product) {
|
if (product) {
|
||||||
// Добавляем товар в tempCart
|
// Добавляем товар в tempCart
|
||||||
const cartKey = `product-${product.id}`;
|
const cartKey = `product-${product.id}`;
|
||||||
@@ -1867,12 +1997,97 @@ async function openEditKitModal(kitId) {
|
|||||||
const modal = new bootstrap.Modal(document.getElementById('createTempKitModal'));
|
const modal = new bootstrap.Modal(document.getElementById('createTempKitModal'));
|
||||||
modal.show();
|
modal.show();
|
||||||
|
|
||||||
|
// Проверяем актуальность цен (сразу после открытия)
|
||||||
|
checkPricesActual();
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading kit for edit:', error);
|
console.error('Error loading kit for edit:', error);
|
||||||
alert('Ошибка при загрузке комплекта');
|
alert('Ошибка при загрузке комплекта');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Проверка актуальности цен в витринном комплекте
|
||||||
|
function checkPricesActual() {
|
||||||
|
// Удаляем старый warning если есть
|
||||||
|
const existingWarning = document.getElementById('priceOutdatedWarning');
|
||||||
|
if (existingWarning) existingWarning.remove();
|
||||||
|
|
||||||
|
// Проверяем цены используя actual_catalog_price из tempCart (уже загружен с бэкенда)
|
||||||
|
const outdatedItems = [];
|
||||||
|
let oldTotalPrice = 0;
|
||||||
|
let newTotalPrice = 0;
|
||||||
|
|
||||||
|
tempCart.forEach((item, cartKey) => {
|
||||||
|
if (item.type === 'product' && item.actual_catalog_price !== undefined) {
|
||||||
|
const savedPrice = parseFloat(item.price);
|
||||||
|
const actualPrice = parseFloat(item.actual_catalog_price);
|
||||||
|
const qty = parseFloat(item.qty) || 1;
|
||||||
|
|
||||||
|
if (Math.abs(savedPrice - actualPrice) > 0.01) {
|
||||||
|
oldTotalPrice += savedPrice * qty;
|
||||||
|
newTotalPrice += actualPrice * qty;
|
||||||
|
outdatedItems.push({
|
||||||
|
name: item.name,
|
||||||
|
old: savedPrice,
|
||||||
|
new: actualPrice,
|
||||||
|
qty: qty
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (outdatedItems.length > 0) {
|
||||||
|
showPriceOutdatedWarning(oldTotalPrice, newTotalPrice);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Показать warning о неактуальных ценах
|
||||||
|
function showPriceOutdatedWarning(oldTotalPrice, newTotalPrice) {
|
||||||
|
const modalBody = document.querySelector('#createTempKitModal .modal-body');
|
||||||
|
|
||||||
|
const warning = document.createElement('div');
|
||||||
|
warning.id = 'priceOutdatedWarning';
|
||||||
|
warning.className = 'alert alert-warning alert-dismissible fade show d-flex align-items-start';
|
||||||
|
warning.innerHTML = `
|
||||||
|
<i class="bi bi-exclamation-triangle-fill flex-shrink-0 me-2 mt-1"></i>
|
||||||
|
<div class="flex-grow-1">
|
||||||
|
<strong>Цена неактуальна!</strong><br>
|
||||||
|
<small class="text-muted">При сохранении комплекта было: <strong>${formatMoney(oldTotalPrice)} руб.</strong></small><br>
|
||||||
|
<small class="text-muted">Актуальная цена сейчас: <strong>${formatMoney(newTotalPrice)} руб.</strong></small>
|
||||||
|
<button type="button" class="btn btn-sm btn-warning mt-2" onclick="actualizeKitPrices()">
|
||||||
|
<i class="bi bi-arrow-clockwise"></i> Пересчитать по актуальным ценам
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-close flex-shrink-0" data-bs-dismiss="alert"></button>
|
||||||
|
`;
|
||||||
|
|
||||||
|
modalBody.insertBefore(warning, modalBody.firstChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Актуализировать цены в комплекте
|
||||||
|
function actualizeKitPrices() {
|
||||||
|
tempCart.forEach((item) => {
|
||||||
|
if (item.type === 'product' && item.actual_catalog_price !== undefined) {
|
||||||
|
item.price = item.actual_catalog_price;
|
||||||
|
// Удаляем actual_catalog_price чтобы не показывался warning снова
|
||||||
|
delete item.actual_catalog_price;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Отключаем чекбокс "Установить свою цену" чтобы использовать актуализированную цену
|
||||||
|
document.getElementById('useSalePrice').checked = false;
|
||||||
|
document.getElementById('salePrice').value = '';
|
||||||
|
document.getElementById('salePriceBlock').style.display = 'none';
|
||||||
|
|
||||||
|
// Перерисовываем товары и пересчитываем цену (после отключения чекбокса!)
|
||||||
|
renderTempKitItems();
|
||||||
|
updatePriceCalculations();
|
||||||
|
|
||||||
|
// Убираем warning
|
||||||
|
const warning = document.getElementById('priceOutdatedWarning');
|
||||||
|
if (warning) warning.remove();
|
||||||
|
}
|
||||||
|
|
||||||
// Обновление списка витринных комплектов
|
// Обновление списка витринных комплектов
|
||||||
async function loadShowcaseKits() {
|
async function loadShowcaseKits() {
|
||||||
try {
|
try {
|
||||||
@@ -2082,7 +2297,7 @@ function updatePriceCalculations(basePrice = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Обработчики для полей цены
|
// Обработчики для полей цены
|
||||||
document.getElementById('priceAdjustmentType').addEventListener('change', function() {
|
document.getElementById('priceAdjustmentType').addEventListener('change', function () {
|
||||||
const adjustmentBlock = document.getElementById('adjustmentValueBlock');
|
const adjustmentBlock = document.getElementById('adjustmentValueBlock');
|
||||||
if (this.value === 'none') {
|
if (this.value === 'none') {
|
||||||
adjustmentBlock.style.display = 'none';
|
adjustmentBlock.style.display = 'none';
|
||||||
@@ -2093,11 +2308,11 @@ document.getElementById('priceAdjustmentType').addEventListener('change', functi
|
|||||||
updatePriceCalculations();
|
updatePriceCalculations();
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('priceAdjustmentValue').addEventListener('input', function() {
|
document.getElementById('priceAdjustmentValue').addEventListener('input', function () {
|
||||||
updatePriceCalculations();
|
updatePriceCalculations();
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('useSalePrice').addEventListener('change', function() {
|
document.getElementById('useSalePrice').addEventListener('change', function () {
|
||||||
const salePriceBlock = document.getElementById('salePriceBlock');
|
const salePriceBlock = document.getElementById('salePriceBlock');
|
||||||
if (this.checked) {
|
if (this.checked) {
|
||||||
salePriceBlock.style.display = 'block';
|
salePriceBlock.style.display = 'block';
|
||||||
@@ -2108,12 +2323,12 @@ document.getElementById('useSalePrice').addEventListener('change', function() {
|
|||||||
updatePriceCalculations();
|
updatePriceCalculations();
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('salePrice').addEventListener('input', function() {
|
document.getElementById('salePrice').addEventListener('input', function () {
|
||||||
updatePriceCalculations();
|
updatePriceCalculations();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Обработчик загрузки фото
|
// Обработчик загрузки фото
|
||||||
document.getElementById('tempKitPhoto').addEventListener('change', function(e) {
|
document.getElementById('tempKitPhoto').addEventListener('change', function (e) {
|
||||||
const file = e.target.files[0];
|
const file = e.target.files[0];
|
||||||
if (file) {
|
if (file) {
|
||||||
if (!file.type.startsWith('image/')) {
|
if (!file.type.startsWith('image/')) {
|
||||||
@@ -2124,7 +2339,7 @@ document.getElementById('tempKitPhoto').addEventListener('change', function(e) {
|
|||||||
|
|
||||||
// Превью
|
// Превью
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onload = function(event) {
|
reader.onload = function (event) {
|
||||||
document.getElementById('photoPreviewImg').src = event.target.result;
|
document.getElementById('photoPreviewImg').src = event.target.result;
|
||||||
document.getElementById('photoPreview').style.display = 'block';
|
document.getElementById('photoPreview').style.display = 'block';
|
||||||
};
|
};
|
||||||
@@ -2133,7 +2348,7 @@ document.getElementById('tempKitPhoto').addEventListener('change', function(e) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Удаление фото
|
// Удаление фото
|
||||||
document.getElementById('removePhoto').addEventListener('click', function() {
|
document.getElementById('removePhoto').addEventListener('click', function () {
|
||||||
document.getElementById('tempKitPhoto').value = '';
|
document.getElementById('tempKitPhoto').value = '';
|
||||||
document.getElementById('photoPreview').style.display = 'none';
|
document.getElementById('photoPreview').style.display = 'none';
|
||||||
document.getElementById('photoPreviewImg').src = '';
|
document.getElementById('photoPreviewImg').src = '';
|
||||||
@@ -2144,6 +2359,7 @@ document.getElementById('confirmCreateTempKit').onclick = async () => {
|
|||||||
const kitName = document.getElementById('tempKitName').value.trim();
|
const kitName = document.getElementById('tempKitName').value.trim();
|
||||||
const showcaseId = document.getElementById('showcaseSelect').value;
|
const showcaseId = document.getElementById('showcaseSelect').value;
|
||||||
const description = document.getElementById('tempKitDescription').value.trim();
|
const description = document.getElementById('tempKitDescription').value.trim();
|
||||||
|
const showcaseCreatedAt = document.getElementById('showcaseCreatedAt').value;
|
||||||
const photoFile = document.getElementById('tempKitPhoto').files[0];
|
const photoFile = document.getElementById('tempKitPhoto').files[0];
|
||||||
|
|
||||||
// Валидация
|
// Валидация
|
||||||
@@ -2182,6 +2398,14 @@ document.getElementById('confirmCreateTempKit').onclick = async () => {
|
|||||||
// Получаем количество букетов для создания
|
// Получаем количество букетов для создания
|
||||||
const showcaseKitQuantity = parseInt(document.getElementById('showcaseKitQuantity').value, 10) || 1;
|
const showcaseKitQuantity = parseInt(document.getElementById('showcaseKitQuantity').value, 10) || 1;
|
||||||
|
|
||||||
|
// Вычисляем итоговую цену комплекта на основе изменённых цен в корзине
|
||||||
|
let calculatedPrice = 0;
|
||||||
|
tempCart.forEach((item) => {
|
||||||
|
if (item.type === 'product') {
|
||||||
|
calculatedPrice += item.qty * item.price;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Формируем FormData для отправки с файлом
|
// Формируем FormData для отправки с файлом
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('kit_name', kitName);
|
formData.append('kit_name', kitName);
|
||||||
@@ -2190,9 +2414,13 @@ document.getElementById('confirmCreateTempKit').onclick = async () => {
|
|||||||
formData.append('quantity', showcaseKitQuantity); // Количество экземпляров на витрину
|
formData.append('quantity', showcaseKitQuantity); // Количество экземпляров на витрину
|
||||||
}
|
}
|
||||||
formData.append('description', description);
|
formData.append('description', description);
|
||||||
|
if (showcaseCreatedAt) {
|
||||||
|
formData.append('showcase_created_at', showcaseCreatedAt);
|
||||||
|
}
|
||||||
formData.append('items', JSON.stringify(items));
|
formData.append('items', JSON.stringify(items));
|
||||||
formData.append('price_adjustment_type', priceAdjustmentType);
|
formData.append('price_adjustment_type', priceAdjustmentType);
|
||||||
formData.append('price_adjustment_value', priceAdjustmentValue);
|
formData.append('price_adjustment_value', priceAdjustmentValue);
|
||||||
|
// Если пользователь явно указал свою цену
|
||||||
if (useSalePrice && salePrice > 0) {
|
if (useSalePrice && salePrice > 0) {
|
||||||
formData.append('sale_price', salePrice);
|
formData.append('sale_price', salePrice);
|
||||||
}
|
}
|
||||||
@@ -2257,6 +2485,7 @@ document.getElementById('confirmCreateTempKit').onclick = async () => {
|
|||||||
|
|
||||||
// Сбрасываем поля формы
|
// Сбрасываем поля формы
|
||||||
document.getElementById('tempKitDescription').value = '';
|
document.getElementById('tempKitDescription').value = '';
|
||||||
|
document.getElementById('showcaseCreatedAt').value = '';
|
||||||
document.getElementById('tempKitPhoto').value = '';
|
document.getElementById('tempKitPhoto').value = '';
|
||||||
document.getElementById('photoPreview').style.display = 'none';
|
document.getElementById('photoPreview').style.display = 'none';
|
||||||
document.getElementById('priceAdjustmentType').value = 'none';
|
document.getElementById('priceAdjustmentType').value = 'none';
|
||||||
@@ -2357,6 +2586,53 @@ document.getElementById('disassembleKitBtn').addEventListener('click', async ()
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Обработчик кнопки "Списать букет"
|
||||||
|
document.getElementById('writeOffKitBtn').addEventListener('click', async () => {
|
||||||
|
if (!isEditMode || !editingKitId) {
|
||||||
|
alert('Ошибка: режим редактирования не активен');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Запрос подтверждения
|
||||||
|
const confirmed = confirm(
|
||||||
|
'Вы уверены?\n\n' +
|
||||||
|
'Букет будет списан:\n' +
|
||||||
|
'• Будет создан документ списания с компонентами букета\n' +
|
||||||
|
'• Комплект будет помечен как "Снят"\n' +
|
||||||
|
'• Будет открыта страница документа для редактирования\n\n' +
|
||||||
|
'Продолжить?'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!confirmed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/pos/api/product-kits/${editingKitId}/write-off/`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'X-CSRFToken': getCsrfToken()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
// Закрываем модальное окно
|
||||||
|
const modal = bootstrap.Modal.getInstance(document.getElementById('createTempKitModal'));
|
||||||
|
modal.hide();
|
||||||
|
|
||||||
|
// Перенаправляем на страницу документа
|
||||||
|
window.location.href = data.redirect_url;
|
||||||
|
} else {
|
||||||
|
alert(`❌ Ошибка: ${data.error}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error writing off kit:', error);
|
||||||
|
alert('Произошла ошибка при списании букета');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Вспомогательная функция для определения мобильного устройства
|
// Вспомогательная функция для определения мобильного устройства
|
||||||
function isMobileDevice() {
|
function isMobileDevice() {
|
||||||
// Проверяем по юзер-агенту и размеру экрана
|
// Проверяем по юзер-агенту и размеру экрана
|
||||||
@@ -2405,7 +2681,7 @@ const getCsrfToken = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Сброс режима редактирования при закрытии модального окна
|
// Сброс режима редактирования при закрытии модального окна
|
||||||
document.getElementById('createTempKitModal').addEventListener('hidden.bs.modal', function() {
|
document.getElementById('createTempKitModal').addEventListener('hidden.bs.modal', function () {
|
||||||
// Очищаем tempCart (изолированное состояние модалки)
|
// Очищаем tempCart (изолированное состояние модалки)
|
||||||
tempCart.clear();
|
tempCart.clear();
|
||||||
|
|
||||||
@@ -2419,8 +2695,9 @@ document.getElementById('createTempKitModal').addEventListener('hidden.bs.modal'
|
|||||||
document.getElementById('createTempKitModalLabel').textContent = 'Создать витринный букет из корзины';
|
document.getElementById('createTempKitModalLabel').textContent = 'Создать витринный букет из корзины';
|
||||||
document.getElementById('confirmCreateTempKit').innerHTML = '<i class="bi bi-check-circle"></i> Создать и зарезервировать';
|
document.getElementById('confirmCreateTempKit').innerHTML = '<i class="bi bi-check-circle"></i> Создать и зарезервировать';
|
||||||
|
|
||||||
// Скрываем кнопку "Разобрать" и блок добавления товаров
|
// Скрываем кнопки "Разобрать" и "Списать" и блок добавления товаров
|
||||||
document.getElementById('disassembleKitBtn').style.display = 'none';
|
document.getElementById('disassembleKitBtn').style.display = 'none';
|
||||||
|
document.getElementById('writeOffKitBtn').style.display = 'none';
|
||||||
document.getElementById('showcaseKitQuantityBlock').style.display = 'block';
|
document.getElementById('showcaseKitQuantityBlock').style.display = 'block';
|
||||||
document.getElementById('addProductBlock').style.display = 'none';
|
document.getElementById('addProductBlock').style.display = 'none';
|
||||||
}
|
}
|
||||||
@@ -2528,13 +2805,13 @@ document.getElementById('checkoutModal').addEventListener('show.bs.modal', async
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Переключение режима оплаты
|
// Переключение режима оплаты
|
||||||
document.getElementById('singlePaymentMode').addEventListener('click', function() {
|
document.getElementById('singlePaymentMode').addEventListener('click', function () {
|
||||||
document.getElementById('singlePaymentMode').classList.add('active');
|
document.getElementById('singlePaymentMode').classList.add('active');
|
||||||
document.getElementById('mixedPaymentMode').classList.remove('active');
|
document.getElementById('mixedPaymentMode').classList.remove('active');
|
||||||
reinitPaymentWidget('single');
|
reinitPaymentWidget('single');
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('mixedPaymentMode').addEventListener('click', function() {
|
document.getElementById('mixedPaymentMode').addEventListener('click', function () {
|
||||||
document.getElementById('mixedPaymentMode').classList.add('active');
|
document.getElementById('mixedPaymentMode').classList.add('active');
|
||||||
document.getElementById('singlePaymentMode').classList.remove('active');
|
document.getElementById('singlePaymentMode').classList.remove('active');
|
||||||
reinitPaymentWidget('mixed');
|
reinitPaymentWidget('mixed');
|
||||||
@@ -3170,8 +3447,8 @@ async function handleCheckoutSubmit(paymentsData) {
|
|||||||
if (result.success) {
|
if (result.success) {
|
||||||
console.log('✅ Заказ успешно создан:', result);
|
console.log('✅ Заказ успешно создан:', result);
|
||||||
|
|
||||||
// Успех
|
// Показываем toast уведомление
|
||||||
alert(`Заказ #${result.order_number} успешно создан!\nСумма: ${result.total_amount.toFixed(2)} руб.`);
|
showToast('success', `Заказ #${result.order_number} успешно создан! Сумма: ${result.total_amount.toFixed(2)} руб.`);
|
||||||
|
|
||||||
// Очищаем корзину
|
// Очищаем корзину
|
||||||
cart.clear();
|
cart.clear();
|
||||||
@@ -3192,12 +3469,12 @@ async function handleCheckoutSubmit(paymentsData) {
|
|||||||
}, 500);
|
}, 500);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
alert('Ошибка: ' + result.error);
|
showToast('error', 'Ошибка: ' + result.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка checkout:', error);
|
console.error('Ошибка checkout:', error);
|
||||||
alert('Ошибка при проведении продажи: ' + error.message);
|
showToast('error', 'Ошибка при проведении продажи: ' + error.message);
|
||||||
} finally {
|
} finally {
|
||||||
// Разблокируем кнопку
|
// Разблокируем кнопку
|
||||||
const btn = document.getElementById('confirmCheckoutBtn');
|
const btn = document.getElementById('confirmCheckoutBtn');
|
||||||
@@ -3392,6 +3669,30 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
categoriesContent.classList.add('collapsed');
|
categoriesContent.classList.add('collapsed');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== МОБИЛЬНЫЙ DROPDOWN "ЕЩЁ" =====
|
||||||
|
|
||||||
|
// Мобильная кнопка "Отложенный заказ"
|
||||||
|
const mobileScheduleLaterBtn = document.getElementById('mobileScheduleLaterBtn');
|
||||||
|
if (mobileScheduleLaterBtn) {
|
||||||
|
mobileScheduleLaterBtn.addEventListener('click', () => {
|
||||||
|
const scheduleBtn = document.getElementById('scheduleLater');
|
||||||
|
if (scheduleBtn) {
|
||||||
|
scheduleBtn.click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Мобильная кнопка "На витрину"
|
||||||
|
const mobileAddToShowcaseBtn = document.getElementById('mobileAddToShowcaseBtn');
|
||||||
|
if (mobileAddToShowcaseBtn) {
|
||||||
|
mobileAddToShowcaseBtn.addEventListener('click', () => {
|
||||||
|
const showcaseBtn = document.getElementById('addToShowcaseBtn');
|
||||||
|
if (showcaseBtn) {
|
||||||
|
showcaseBtn.click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Смена склада
|
// Смена склада
|
||||||
@@ -3488,6 +3789,14 @@ searchInput.addEventListener('input', (e) => {
|
|||||||
}, 300);
|
}, 300);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// При нажатии Enter на searchInput - скрываем виртуальную клавиатуру
|
||||||
|
searchInput.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
searchInput.blur(); // Скрывает виртуальную клавиатуру на мобильных
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Обработчик кнопки очистки поиска
|
// Обработчик кнопки очистки поиска
|
||||||
clearSearchBtn.addEventListener('click', () => {
|
clearSearchBtn.addEventListener('click', () => {
|
||||||
searchInput.value = '';
|
searchInput.value = '';
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
{% load static %}
|
||||||
|
<div class="modal fade" id="editCartItemModal" tabindex="-1" aria-hidden="true">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title">
|
||||||
|
<i class="bi bi-pencil-square"></i> Редактирование товара
|
||||||
|
</h5>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<!-- Название товара -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label text-muted small">Товар</label>
|
||||||
|
<div id="editModalProductName" class="fw-semibold">—</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Базовая цена (оригинальная) -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label text-muted small">Базовая цена</label>
|
||||||
|
<div class="d-flex align-items-center gap-2">
|
||||||
|
<span id="editModalBasePrice" class="text-muted">0.00 руб.</span>
|
||||||
|
<span id="editModalUnitBadge" class="badge bg-secondary" style="display: none;"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Новая цена -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="editModalPrice" class="form-label fw-semibold">Цена за единицу</label>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="number" class="form-control" id="editModalPrice"
|
||||||
|
min="0" step="0.01" placeholder="0.00">
|
||||||
|
<span class="input-group-text">руб.</span>
|
||||||
|
</div>
|
||||||
|
<div id="editModalPriceWarning" class="text-warning small mt-1" style="display: none;">
|
||||||
|
<i class="bi bi-exclamation-triangle"></i> Цена изменена
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Количество -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="editModalQuantity" class="form-label fw-semibold">Количество</label>
|
||||||
|
<input type="number" class="form-control" id="editModalQuantity"
|
||||||
|
min="0.001" step="0.001" value="1">
|
||||||
|
<div id="editModalQtyHint" class="text-muted small mt-1" style="display: none;">
|
||||||
|
<i class="bi bi-info-circle"></i> Количество нельзя изменить для витринного комплекта (собранный товар с резервами)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Итого -->
|
||||||
|
<div class="alert alert-info mb-0">
|
||||||
|
<div class="d-flex justify-content-between align-items-center">
|
||||||
|
<strong>Сумма:</strong>
|
||||||
|
<span class="fs-5" id="editModalTotal">0.00 руб.</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||||
|
<button type="button" class="btn btn-primary" id="confirmEditCartItem">
|
||||||
|
<i class="bi bi-check-lg"></i> Сохранить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -142,6 +142,26 @@
|
|||||||
<button class="btn btn-outline-secondary btn-sm" id="mobileClearCartBtn" title="Очистить корзину">
|
<button class="btn btn-outline-secondary btn-sm" id="mobileClearCartBtn" title="Очистить корзину">
|
||||||
<i class="bi bi-trash"></i>
|
<i class="bi bi-trash"></i>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<!-- Dropdown "Ещё" -->
|
||||||
|
<div class="dropdown">
|
||||||
|
<button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button"
|
||||||
|
id="mobileMoreBtn" data-bs-toggle="dropdown">
|
||||||
|
<i class="bi bi-three-dots"></i>
|
||||||
|
</button>
|
||||||
|
<ul class="dropdown-menu dropdown-menu-end">
|
||||||
|
<li>
|
||||||
|
<button class="dropdown-item" id="mobileScheduleLaterBtn" type="button">
|
||||||
|
<i class="bi bi-calendar2 me-2"></i>Отложенный заказ
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<button class="dropdown-item" id="mobileAddToShowcaseBtn" type="button">
|
||||||
|
<i class="bi bi-flower1 me-2"></i>На витрину
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -199,6 +219,14 @@
|
|||||||
<textarea class="form-control" id="tempKitDescription" rows="3" placeholder="Краткое описание комплекта"></textarea>
|
<textarea class="form-control" id="tempKitDescription" rows="3" placeholder="Краткое описание комплекта"></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Дата размещения на витрине -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="showcaseCreatedAt" class="form-label">Дата размещения на витрине</label>
|
||||||
|
<input type="datetime-local" class="form-control" id="showcaseCreatedAt"
|
||||||
|
placeholder="Выберите дату и время">
|
||||||
|
<small class="text-muted">Оставьте пустым для текущего времени</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Загрузка фото -->
|
<!-- Загрузка фото -->
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="tempKitPhoto" class="form-label">Фото комплекта (опционально)</label>
|
<label for="tempKitPhoto" class="form-label">Фото комплекта (опционально)</label>
|
||||||
@@ -302,6 +330,11 @@
|
|||||||
<i class="bi bi-scissors"></i> Разобрать букет
|
<i class="bi bi-scissors"></i> Разобрать букет
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<!-- Кнопка "Списать" (отображается только в режиме редактирования) -->
|
||||||
|
<button type="button" class="btn btn-warning me-auto" id="writeOffKitBtn" style="display: none;">
|
||||||
|
<i class="bi bi-file-earmark-x"></i> Списать букет
|
||||||
|
</button>
|
||||||
|
|
||||||
<!-- Правая группа кнопок -->
|
<!-- Правая группа кнопок -->
|
||||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||||
<button type="button" class="btn btn-primary" id="confirmCreateTempKit">
|
<button type="button" class="btn btn-primary" id="confirmCreateTempKit">
|
||||||
@@ -693,6 +726,31 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Модалка редактирования товара в корзине -->
|
||||||
|
{% include 'pos/components/edit_cart_item_modal.html' %}
|
||||||
|
|
||||||
|
<!-- Toast Container для уведомлений -->
|
||||||
|
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1060;">
|
||||||
|
<div id="orderSuccessToast" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true">
|
||||||
|
<div class="d-flex">
|
||||||
|
<div class="toast-body">
|
||||||
|
<i class="bi bi-check-circle-fill text-success me-2 fs-5"></i>
|
||||||
|
<span id="toastMessage"></span>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close" style="display: none;"></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="orderErrorToast" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true">
|
||||||
|
<div class="d-flex">
|
||||||
|
<div class="toast-body">
|
||||||
|
<i class="bi bi-exclamation-circle-fill text-danger me-2 fs-5"></i>
|
||||||
|
<span id="errorMessage"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block extra_js %}
|
{% block extra_js %}
|
||||||
@@ -712,4 +770,5 @@
|
|||||||
|
|
||||||
<script src="{% static 'products/js/product-search-picker.js' %}"></script>
|
<script src="{% static 'products/js/product-search-picker.js' %}"></script>
|
||||||
<script src="{% static 'pos/js/terminal.js' %}"></script>
|
<script src="{% static 'pos/js/terminal.js' %}"></script>
|
||||||
|
<script src="{% static 'pos/js/cart-item-editor.js' %}"></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ urlpatterns = [
|
|||||||
path('api/product-kits/<int:kit_id>/update/', views.update_product_kit, name='update-product-kit'),
|
path('api/product-kits/<int:kit_id>/update/', views.update_product_kit, name='update-product-kit'),
|
||||||
# Разобрать витринный комплект (освободить резервы, установить статус discontinued) [POST]
|
# Разобрать витринный комплект (освободить резервы, установить статус discontinued) [POST]
|
||||||
path('api/product-kits/<int:kit_id>/disassemble/', views.disassemble_product_kit, name='disassemble-product-kit'),
|
path('api/product-kits/<int:kit_id>/disassemble/', views.disassemble_product_kit, name='disassemble-product-kit'),
|
||||||
|
# Списать витринный комплект (создать документ списания с компонентами) [POST]
|
||||||
|
path('api/product-kits/<int:kit_id>/write-off/', views.write_off_showcase_kit, name='write-off-showcase-kit'),
|
||||||
# Создать временный комплект и зарезервировать на витрину [POST]
|
# Создать временный комплект и зарезервировать на витрину [POST]
|
||||||
path('api/create-temp-kit/', views.create_temp_kit_to_showcase, name='create-temp-kit-api'),
|
path('api/create-temp-kit/', views.create_temp_kit_to_showcase, name='create-temp-kit-api'),
|
||||||
# Создать заказ и провести оплату в POS [POST]
|
# Создать заказ и провести оплату в POS [POST]
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from django.shortcuts import render, get_object_or_404
|
from django.shortcuts import render, get_object_or_404
|
||||||
|
from django.urls import reverse
|
||||||
from django.contrib.auth.decorators import login_required
|
from django.contrib.auth.decorators import login_required
|
||||||
from django.http import JsonResponse
|
from django.http import JsonResponse
|
||||||
from django.views.decorators.http import require_http_methods
|
from django.views.decorators.http import require_http_methods
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.db.models import Prefetch, OuterRef, Subquery, DecimalField
|
from django.db.models import Prefetch, OuterRef, Subquery, DecimalField, F, Case, When, CharField
|
||||||
from django.db.models.functions import Coalesce
|
from django.db.models.functions import Coalesce
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
@@ -13,8 +14,9 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from products.models import Product, ProductCategory, ProductKit, KitItem
|
from products.models import Product, ProductCategory, ProductKit, KitItem
|
||||||
from inventory.models import Showcase, Reservation, Warehouse, Stock
|
from inventory.models import Showcase, Reservation, Warehouse, Stock, ShowcaseItem
|
||||||
from inventory.services import ShowcaseManager
|
from inventory.services import ShowcaseManager
|
||||||
|
from inventory.signals import skip_sale_creation, reset_sale_creation
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -81,6 +83,8 @@ def get_showcase_kits_for_pos():
|
|||||||
'product_kit__sku',
|
'product_kit__sku',
|
||||||
'product_kit__price',
|
'product_kit__price',
|
||||||
'product_kit__sale_price',
|
'product_kit__sale_price',
|
||||||
|
'product_kit__base_price',
|
||||||
|
'product_kit__showcase_created_at',
|
||||||
'showcase_id',
|
'showcase_id',
|
||||||
'showcase__name'
|
'showcase__name'
|
||||||
).annotate(
|
).annotate(
|
||||||
@@ -109,6 +113,19 @@ def get_showcase_kits_for_pos():
|
|||||||
thumbnail_url = None
|
thumbnail_url = None
|
||||||
kit_photos[photo.kit_id] = thumbnail_url
|
kit_photos[photo.kit_id] = thumbnail_url
|
||||||
|
|
||||||
|
# Загружаем состав комплектов для проверки актуальности цен
|
||||||
|
kit_items_data = {}
|
||||||
|
for ki in KitItem.objects.filter(kit_id__in=kit_ids).select_related('product'):
|
||||||
|
if ki.kit_id not in kit_items_data:
|
||||||
|
kit_items_data[ki.kit_id] = []
|
||||||
|
kit_items_data[ki.kit_id].append(ki)
|
||||||
|
|
||||||
|
# Считаем актуальные цены для каждого комплекта
|
||||||
|
kit_actual_prices = {}
|
||||||
|
for kit_id, items in kit_items_data.items():
|
||||||
|
actual_price = sum((ki.product.actual_price or 0) * (ki.quantity or 0) for ki in items)
|
||||||
|
kit_actual_prices[kit_id] = actual_price
|
||||||
|
|
||||||
# Формируем результат
|
# Формируем результат
|
||||||
showcase_kits = []
|
showcase_kits = []
|
||||||
for item in all_items:
|
for item in all_items:
|
||||||
@@ -125,6 +142,11 @@ def get_showcase_kits_for_pos():
|
|||||||
# Определяем актуальную цену
|
# Определяем актуальную цену
|
||||||
price = item['product_kit__sale_price'] or item['product_kit__price']
|
price = item['product_kit__sale_price'] or item['product_kit__price']
|
||||||
|
|
||||||
|
# Проверяем актуальность цены (сравниваем сохранённую цену с актуальной ценой товаров)
|
||||||
|
actual_price = kit_actual_prices.get(kit_id, Decimal('0'))
|
||||||
|
base_price = item['product_kit__base_price']
|
||||||
|
price_outdated = base_price and abs(float(base_price) - float(actual_price)) > 0.01
|
||||||
|
|
||||||
showcase_kits.append({
|
showcase_kits.append({
|
||||||
'id': kit_id,
|
'id': kit_id,
|
||||||
'name': item['product_kit__name'],
|
'name': item['product_kit__name'],
|
||||||
@@ -139,7 +161,11 @@ def get_showcase_kits_for_pos():
|
|||||||
# Количества
|
# Количества
|
||||||
'available_count': item['available_count'], # Сколько можно добавить
|
'available_count': item['available_count'], # Сколько можно добавить
|
||||||
'total_count': item['total_count'], # Всего на витрине (включая в корзине)
|
'total_count': item['total_count'], # Всего на витрине (включая в корзине)
|
||||||
'showcase_item_ids': available_item_ids # IDs только доступных
|
'showcase_item_ids': available_item_ids, # IDs только доступных
|
||||||
|
# Флаг неактуальной цены
|
||||||
|
'price_outdated': price_outdated,
|
||||||
|
# Дата размещения на витрине
|
||||||
|
'showcase_created_at': item.get('product_kit__showcase_created_at')
|
||||||
})
|
})
|
||||||
|
|
||||||
return showcase_kits
|
return showcase_kits
|
||||||
@@ -241,13 +267,25 @@ def pos_terminal(request):
|
|||||||
|
|
||||||
if showcase_item_ids:
|
if showcase_item_ids:
|
||||||
# Проверяем, что все указанные ShowcaseItem заблокированы на текущего пользователя
|
# Проверяем, что все указанные ShowcaseItem заблокированы на текущего пользователя
|
||||||
locked_items = ShowcaseItem.objects.filter(
|
from accounts.models import CustomUser
|
||||||
id__in=showcase_item_ids,
|
if isinstance(request.user, CustomUser):
|
||||||
product_kit=kit,
|
locked_items = ShowcaseItem.objects.filter(
|
||||||
status='in_cart',
|
id__in=showcase_item_ids,
|
||||||
locked_by_user=request.user,
|
product_kit=kit,
|
||||||
cart_lock_expires_at__gt=timezone.now()
|
status='in_cart',
|
||||||
)
|
locked_by_user=request.user,
|
||||||
|
cart_lock_expires_at__gt=timezone.now()
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Для PlatformAdmin используем проверку по сессии
|
||||||
|
session_id = request.session.session_key or ''
|
||||||
|
locked_items = ShowcaseItem.objects.filter(
|
||||||
|
id__in=showcase_item_ids,
|
||||||
|
product_kit=kit,
|
||||||
|
status='in_cart',
|
||||||
|
cart_session_id=session_id,
|
||||||
|
cart_lock_expires_at__gt=timezone.now()
|
||||||
|
)
|
||||||
|
|
||||||
locked_count = locked_items.count()
|
locked_count = locked_items.count()
|
||||||
|
|
||||||
@@ -454,10 +492,18 @@ def get_showcase_kits_api(request):
|
|||||||
product_kit_id__in=kit_ids,
|
product_kit_id__in=kit_ids,
|
||||||
cart_lock_expires_at__gt=timezone.now(),
|
cart_lock_expires_at__gt=timezone.now(),
|
||||||
status='reserved'
|
status='reserved'
|
||||||
).select_related('locked_by_user').values(
|
).select_related('locked_by_user').annotate(
|
||||||
|
# На уровне БД выбираем: если name есть - берем name, иначе email
|
||||||
|
locked_by_user_display=Case(
|
||||||
|
When(locked_by_user__name__isnull=False, then=F('locked_by_user__name')),
|
||||||
|
When(locked_by_user__name='', then=F('locked_by_user__email')),
|
||||||
|
default=F('locked_by_user__email'),
|
||||||
|
output_field=CharField()
|
||||||
|
)
|
||||||
|
).values(
|
||||||
'product_kit_id',
|
'product_kit_id',
|
||||||
'locked_by_user_id',
|
'locked_by_user_id',
|
||||||
'locked_by_user__username',
|
'locked_by_user_display',
|
||||||
'cart_lock_expires_at'
|
'cart_lock_expires_at'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -476,7 +522,7 @@ def get_showcase_kits_api(request):
|
|||||||
is_locked_by_me = lock_info['locked_by_user_id'] == request.user.id
|
is_locked_by_me = lock_info['locked_by_user_id'] == request.user.id
|
||||||
kit['is_locked'] = True
|
kit['is_locked'] = True
|
||||||
kit['locked_by_me'] = is_locked_by_me
|
kit['locked_by_me'] = is_locked_by_me
|
||||||
kit['locked_by_user'] = lock_info['locked_by_user__username']
|
kit['locked_by_user'] = lock_info['locked_by_user_display']
|
||||||
kit['lock_expires_at'] = lock_info['cart_lock_expires_at'].isoformat()
|
kit['lock_expires_at'] = lock_info['cart_lock_expires_at'].isoformat()
|
||||||
else:
|
else:
|
||||||
kit['is_locked'] = False
|
kit['is_locked'] = False
|
||||||
@@ -625,11 +671,22 @@ def remove_showcase_kit_from_cart(request, kit_id):
|
|||||||
showcase_item_ids = []
|
showcase_item_ids = []
|
||||||
|
|
||||||
# Базовый фильтр - экземпляры этого комплекта, заблокированные текущим пользователем
|
# Базовый фильтр - экземпляры этого комплекта, заблокированные текущим пользователем
|
||||||
qs = ShowcaseItem.objects.filter(
|
from accounts.models import CustomUser
|
||||||
product_kit=kit,
|
|
||||||
status='in_cart',
|
if isinstance(request.user, CustomUser):
|
||||||
locked_by_user=request.user
|
qs = ShowcaseItem.objects.filter(
|
||||||
)
|
product_kit=kit,
|
||||||
|
status='in_cart',
|
||||||
|
locked_by_user=request.user
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Для PlatformAdmin используем проверку по сессии
|
||||||
|
session_id = request.session.session_key or ''
|
||||||
|
qs = ShowcaseItem.objects.filter(
|
||||||
|
product_kit=kit,
|
||||||
|
status='in_cart',
|
||||||
|
cart_session_id=session_id
|
||||||
|
)
|
||||||
|
|
||||||
# Если указаны конкретные ID - фильтруем только их
|
# Если указаны конкретные ID - фильтруем только их
|
||||||
if showcase_item_ids:
|
if showcase_item_ids:
|
||||||
@@ -680,10 +737,22 @@ def release_all_my_showcase_locks(request):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
# Снимаем ВСЕ блокировки текущего пользователя
|
# Снимаем ВСЕ блокировки текущего пользователя
|
||||||
updated_count = ShowcaseItem.objects.filter(
|
from accounts.models import CustomUser
|
||||||
status='in_cart',
|
|
||||||
locked_by_user=request.user
|
if isinstance(request.user, CustomUser):
|
||||||
).update(
|
qs_to_release = ShowcaseItem.objects.filter(
|
||||||
|
status='in_cart',
|
||||||
|
locked_by_user=request.user
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Для PlatformAdmin фильтруем по сессии
|
||||||
|
session_id = request.session.session_key or ''
|
||||||
|
qs_to_release = ShowcaseItem.objects.filter(
|
||||||
|
status='in_cart',
|
||||||
|
cart_session_id=session_id
|
||||||
|
)
|
||||||
|
|
||||||
|
updated_count = qs_to_release.update(
|
||||||
status='available',
|
status='available',
|
||||||
locked_by_user=None,
|
locked_by_user=None,
|
||||||
cart_lock_expires_at=None,
|
cart_lock_expires_at=None,
|
||||||
@@ -948,12 +1017,21 @@ def get_product_kit_details(request, kit_id):
|
|||||||
showcase_id = showcase_reservation.showcase.id if showcase_reservation else None
|
showcase_id = showcase_reservation.showcase.id if showcase_reservation else None
|
||||||
|
|
||||||
# Собираем данные о составе
|
# Собираем данные о составе
|
||||||
items = [{
|
# Используем unit_price если есть (зафиксированная цена), иначе актуальную цену товара
|
||||||
'product_id': ki.product.id,
|
items = []
|
||||||
'name': ki.product.name,
|
for ki in kit.kit_items.all():
|
||||||
'qty': str(ki.quantity),
|
# Зафиксированная цена или актуальная цена товара
|
||||||
'price': str(ki.product.actual_price)
|
item_price = ki.unit_price if ki.unit_price is not None else ki.product.actual_price
|
||||||
} for ki in kit.kit_items.all()]
|
item_data = {
|
||||||
|
'product_id': ki.product.id,
|
||||||
|
'name': ki.product.name,
|
||||||
|
'qty': str(ki.quantity),
|
||||||
|
'price': str(item_price)
|
||||||
|
}
|
||||||
|
# Для временных комплектов добавляем актуальную цену из каталога для сравнения
|
||||||
|
if kit.is_temporary and ki.unit_price is not None:
|
||||||
|
item_data['actual_catalog_price'] = str(ki.product.actual_price)
|
||||||
|
items.append(item_data)
|
||||||
|
|
||||||
# Фото (используем миниатюру для быстрой загрузки)
|
# Фото (используем миниатюру для быстрой загрузки)
|
||||||
photo_url = None
|
photo_url = None
|
||||||
@@ -978,7 +1056,8 @@ def get_product_kit_details(request, kit_id):
|
|||||||
'final_price': str(kit.actual_price),
|
'final_price': str(kit.actual_price),
|
||||||
'showcase_id': showcase_id,
|
'showcase_id': showcase_id,
|
||||||
'items': items,
|
'items': items,
|
||||||
'photo_url': photo_url
|
'photo_url': photo_url,
|
||||||
|
'showcase_created_at': kit.showcase_created_at.isoformat() if kit.showcase_created_at else None
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
except ProductKit.DoesNotExist:
|
except ProductKit.DoesNotExist:
|
||||||
@@ -1013,6 +1092,7 @@ def create_temp_kit_to_showcase(request):
|
|||||||
sale_price_str = request.POST.get('sale_price', '')
|
sale_price_str = request.POST.get('sale_price', '')
|
||||||
photo_file = request.FILES.get('photo')
|
photo_file = request.FILES.get('photo')
|
||||||
showcase_kit_quantity = int(request.POST.get('quantity', 1)) # Количество букетов на витрину
|
showcase_kit_quantity = int(request.POST.get('quantity', 1)) # Количество букетов на витрину
|
||||||
|
showcase_created_at_str = request.POST.get('showcase_created_at', '').strip()
|
||||||
|
|
||||||
# Парсим items из JSON
|
# Парсим items из JSON
|
||||||
items = json.loads(items_json)
|
items = json.loads(items_json)
|
||||||
@@ -1027,6 +1107,23 @@ def create_temp_kit_to_showcase(request):
|
|||||||
except (ValueError, InvalidOperation):
|
except (ValueError, InvalidOperation):
|
||||||
sale_price = None
|
sale_price = None
|
||||||
|
|
||||||
|
# Showcase created at (опционально)
|
||||||
|
showcase_created_at = None
|
||||||
|
if showcase_created_at_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
showcase_created_at = datetime.fromisoformat(showcase_created_at_str)
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
showcase_created_at = datetime.strptime(showcase_created_at_str, '%Y-%m-%dT%H:%M')
|
||||||
|
except ValueError:
|
||||||
|
pass # Неверный формат, оставляем как None
|
||||||
|
|
||||||
|
# Если не указана - устанавливаем текущее время для новых комплектов
|
||||||
|
if not showcase_created_at:
|
||||||
|
showcase_created_at = timezone.now()
|
||||||
|
|
||||||
# Валидация
|
# Валидация
|
||||||
if not kit_name:
|
if not kit_name:
|
||||||
return JsonResponse({
|
return JsonResponse({
|
||||||
@@ -1087,15 +1184,18 @@ def create_temp_kit_to_showcase(request):
|
|||||||
price_adjustment_type=price_adjustment_type,
|
price_adjustment_type=price_adjustment_type,
|
||||||
price_adjustment_value=price_adjustment_value,
|
price_adjustment_value=price_adjustment_value,
|
||||||
sale_price=sale_price,
|
sale_price=sale_price,
|
||||||
showcase=showcase
|
showcase=showcase,
|
||||||
|
showcase_created_at=showcase_created_at
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. Создаём KitItem для каждого товара из корзины
|
# 2. Создаём KitItem для каждого товара из корзины
|
||||||
for product_id, quantity in aggregated_items.items():
|
for product_id, quantity in aggregated_items.items():
|
||||||
|
product = products[product_id]
|
||||||
KitItem.objects.create(
|
KitItem.objects.create(
|
||||||
kit=kit,
|
kit=kit,
|
||||||
product=products[product_id],
|
product=product,
|
||||||
quantity=quantity
|
quantity=quantity,
|
||||||
|
unit_price=product.actual_price # Фиксируем цену для временного комплекта
|
||||||
)
|
)
|
||||||
|
|
||||||
# 3. Пересчитываем цену комплекта
|
# 3. Пересчитываем цену комплекта
|
||||||
@@ -1220,6 +1320,7 @@ def update_product_kit(request, kit_id):
|
|||||||
sale_price_str = request.POST.get('sale_price', '')
|
sale_price_str = request.POST.get('sale_price', '')
|
||||||
photo_file = request.FILES.get('photo')
|
photo_file = request.FILES.get('photo')
|
||||||
remove_photo = request.POST.get('remove_photo', '') == '1'
|
remove_photo = request.POST.get('remove_photo', '') == '1'
|
||||||
|
showcase_created_at_str = request.POST.get('showcase_created_at', '').strip()
|
||||||
|
|
||||||
items = json.loads(items_json)
|
items = json.loads(items_json)
|
||||||
|
|
||||||
@@ -1232,6 +1333,23 @@ def update_product_kit(request, kit_id):
|
|||||||
except (ValueError, InvalidOperation):
|
except (ValueError, InvalidOperation):
|
||||||
sale_price = None
|
sale_price = None
|
||||||
|
|
||||||
|
# Showcase created at (опционально)
|
||||||
|
showcase_created_at = None
|
||||||
|
if showcase_created_at_str:
|
||||||
|
try:
|
||||||
|
from datetime import datetime
|
||||||
|
showcase_created_at = datetime.fromisoformat(showcase_created_at_str)
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
showcase_created_at = datetime.strptime(showcase_created_at_str, '%Y-%m-%dT%H:%M')
|
||||||
|
except ValueError:
|
||||||
|
pass # Неверный формат, оставляем как есть
|
||||||
|
|
||||||
|
# Делаем datetime timezone-aware
|
||||||
|
if showcase_created_at and showcase_created_at.tzinfo is None:
|
||||||
|
from django.utils import timezone
|
||||||
|
showcase_created_at = timezone.make_aware(showcase_created_at)
|
||||||
|
|
||||||
# Валидация
|
# Валидация
|
||||||
if not kit_name:
|
if not kit_name:
|
||||||
return JsonResponse({'success': False, 'error': 'Необходимо указать название'}, status=400)
|
return JsonResponse({'success': False, 'error': 'Необходимо указать название'}, status=400)
|
||||||
@@ -1305,15 +1423,19 @@ def update_product_kit(request, kit_id):
|
|||||||
kit.price_adjustment_type = price_adjustment_type
|
kit.price_adjustment_type = price_adjustment_type
|
||||||
kit.price_adjustment_value = price_adjustment_value
|
kit.price_adjustment_value = price_adjustment_value
|
||||||
kit.sale_price = sale_price
|
kit.sale_price = sale_price
|
||||||
|
if showcase_created_at is not None: # Обновляем только если передана
|
||||||
|
kit.showcase_created_at = showcase_created_at
|
||||||
kit.save()
|
kit.save()
|
||||||
|
|
||||||
# Обновляем состав
|
# Обновляем состав
|
||||||
kit.kit_items.all().delete()
|
kit.kit_items.all().delete()
|
||||||
for product_id, quantity in aggregated_items.items():
|
for product_id, quantity in aggregated_items.items():
|
||||||
|
product = products[product_id]
|
||||||
KitItem.objects.create(
|
KitItem.objects.create(
|
||||||
kit=kit,
|
kit=kit,
|
||||||
product=products[product_id],
|
product=product,
|
||||||
quantity=quantity
|
quantity=quantity,
|
||||||
|
unit_price=product.actual_price # Фиксируем актуальную цену
|
||||||
)
|
)
|
||||||
|
|
||||||
kit.recalculate_base_price()
|
kit.recalculate_base_price()
|
||||||
@@ -1415,6 +1537,88 @@ def disassemble_product_kit(request, kit_id):
|
|||||||
}, status=500)
|
}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@login_required
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
def write_off_showcase_kit(request, kit_id):
|
||||||
|
"""
|
||||||
|
Списывает витринный комплект с созданием документа списания.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
request: HTTP запрос
|
||||||
|
kit_id: ID комплекта для списания
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON: {
|
||||||
|
'success': bool,
|
||||||
|
'document_id': int,
|
||||||
|
'document_number': str,
|
||||||
|
'redirect_url': str,
|
||||||
|
'message': str,
|
||||||
|
'error': str (если failed)
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Получаем комплект с витриной (только временные комплекты)
|
||||||
|
kit = ProductKit.objects.select_related('showcase').get(id=kit_id, is_temporary=True)
|
||||||
|
|
||||||
|
# Проверяем, что комплект ещё не разобран
|
||||||
|
if kit.status == 'discontinued':
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Комплект уже разобран (статус: Снят)'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
# Проверяем, что у комплекта есть привязанная витрина
|
||||||
|
if not kit.showcase:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Комплект не привязан к витрине'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
# Находим экземпляр на витрине
|
||||||
|
showcase_item = ShowcaseItem.objects.filter(
|
||||||
|
showcase=kit.showcase,
|
||||||
|
product_kit=kit,
|
||||||
|
status='available'
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not showcase_item:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Экземпляр комплекта не найден на витрине'
|
||||||
|
}, status=404)
|
||||||
|
|
||||||
|
# Создаём документ списания
|
||||||
|
result = ShowcaseManager.write_off_from_showcase(
|
||||||
|
showcase_item=showcase_item,
|
||||||
|
reason='spoilage',
|
||||||
|
notes=f'Витринный букет: {kit.name}',
|
||||||
|
created_by=request.user
|
||||||
|
)
|
||||||
|
|
||||||
|
if not result['success']:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': result['message']
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
# Формируем URL для перенаправления
|
||||||
|
redirect_url = reverse('inventory:writeoff-document-detail', kwargs={'pk': result['document_id']})
|
||||||
|
|
||||||
|
return JsonResponse({
|
||||||
|
'success': True,
|
||||||
|
'document_id': result['document_id'],
|
||||||
|
'document_number': result['document_number'],
|
||||||
|
'redirect_url': redirect_url,
|
||||||
|
'message': result['message']
|
||||||
|
})
|
||||||
|
|
||||||
|
except ProductKit.DoesNotExist:
|
||||||
|
return JsonResponse({'success': False, 'error': 'Комплект не найден'}, status=404)
|
||||||
|
except Exception as e:
|
||||||
|
return JsonResponse({'success': False, 'error': f'Ошибка: {str(e)}'}, status=500)
|
||||||
|
|
||||||
|
|
||||||
@login_required
|
@login_required
|
||||||
@require_http_methods(["POST"])
|
@require_http_methods(["POST"])
|
||||||
def pos_checkout(request):
|
def pos_checkout(request):
|
||||||
@@ -1484,6 +1688,10 @@ def pos_checkout(request):
|
|||||||
|
|
||||||
# Атомарная операция
|
# Атомарная операция
|
||||||
with db_transaction.atomic():
|
with db_transaction.atomic():
|
||||||
|
# ВАЖНО: Устанавливаем флаг для пропуска автоматического создания Sale в сигнале.
|
||||||
|
# Sale будет создан ЯВНО после применения всех скидок.
|
||||||
|
skip_sale_creation()
|
||||||
|
|
||||||
# 1. Создаём заказ с текущей датой и временем в локальном часовом поясе (Europe/Minsk)
|
# 1. Создаём заказ с текущей датой и временем в локальном часовом поясе (Europe/Minsk)
|
||||||
from django.utils import timezone as tz
|
from django.utils import timezone as tz
|
||||||
from orders.models import Delivery
|
from orders.models import Delivery
|
||||||
@@ -1672,6 +1880,11 @@ def pos_checkout(request):
|
|||||||
cart_key = f'pos:cart:{request.user.id}:{warehouse_id}'
|
cart_key = f'pos:cart:{request.user.id}:{warehouse_id}'
|
||||||
cache.delete(cart_key)
|
cache.delete(cart_key)
|
||||||
|
|
||||||
|
# 7. Явно создаём Sale после применения всех скидок
|
||||||
|
# Сбрасываем флаг пропуска и вызываем save() для активации сигнала
|
||||||
|
reset_sale_creation()
|
||||||
|
order.save() # Триггерит сигнал create_sale_on_order_completion
|
||||||
|
|
||||||
return JsonResponse({
|
return JsonResponse({
|
||||||
'success': True,
|
'success': True,
|
||||||
'order_number': order.order_number,
|
'order_number': order.order_number,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from .models import ProductPhoto, ProductKitPhoto, ProductCategoryPhoto
|
|||||||
from .models import ProductVariantGroup, KitItemPriority, SKUCounter, CostPriceHistory
|
from .models import ProductVariantGroup, KitItemPriority, SKUCounter, CostPriceHistory
|
||||||
from .models import ConfigurableProduct, ConfigurableProductOption, ConfigurableProductAttribute
|
from .models import ConfigurableProduct, ConfigurableProductOption, ConfigurableProductAttribute
|
||||||
from .models import UnitOfMeasure, ProductSalesUnit
|
from .models import UnitOfMeasure, ProductSalesUnit
|
||||||
|
from .models import BouquetName
|
||||||
from .admin_displays import (
|
from .admin_displays import (
|
||||||
format_quality_badge,
|
format_quality_badge,
|
||||||
format_quality_display,
|
format_quality_display,
|
||||||
@@ -500,8 +501,8 @@ class ProductAdmin(TenantAdminOnlyMixin, admin.ModelAdmin):
|
|||||||
cost_price_details_display.short_description = 'Себестоимость товара'
|
cost_price_details_display.short_description = 'Себестоимость товара'
|
||||||
|
|
||||||
def get_queryset(self, request):
|
def get_queryset(self, request):
|
||||||
"""Переопределяем queryset для доступа ко всем товарам (включая удаленные)"""
|
"""Переопределяем queryset для доступа ко всем товарам"""
|
||||||
qs = Product.all_objects.all()
|
qs = super().get_queryset(request)
|
||||||
ordering = self.get_ordering(request)
|
ordering = self.get_ordering(request)
|
||||||
if ordering:
|
if ordering:
|
||||||
qs = qs.order_by(*ordering)
|
qs = qs.order_by(*ordering)
|
||||||
@@ -1086,3 +1087,42 @@ class ConfigurableProductAdmin(TenantAdminOnlyMixin, admin.ModelAdmin):
|
|||||||
count
|
count
|
||||||
)
|
)
|
||||||
get_options_count.short_description = 'Вариантов'
|
get_options_count.short_description = 'Вариантов'
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(BouquetName)
|
||||||
|
class BouquetNameAdmin(TenantAdminOnlyMixin, admin.ModelAdmin):
|
||||||
|
"""
|
||||||
|
Административный интерфейс для управления названиями букетов
|
||||||
|
"""
|
||||||
|
list_display = ('name', 'language', 'is_approved', 'usage_count', 'generated_at')
|
||||||
|
list_filter = ('language', 'is_approved')
|
||||||
|
search_fields = ('name',)
|
||||||
|
filter_horizontal = ('color_tags', 'occasion_tags', 'style_tags')
|
||||||
|
actions = ['approve_selected', 'reject_selected']
|
||||||
|
|
||||||
|
fieldsets = (
|
||||||
|
('Основная информация', {
|
||||||
|
'fields': ('name', 'language', 'is_approved')
|
||||||
|
}),
|
||||||
|
('Теги', {
|
||||||
|
'fields': ('color_tags', 'occasion_tags', 'style_tags')
|
||||||
|
}),
|
||||||
|
('Статистика', {
|
||||||
|
'fields': ('usage_count', 'generated_at', 'approved_at')
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
readonly_fields = ('usage_count', 'generated_at', 'approved_at')
|
||||||
|
|
||||||
|
def approve_selected(self, request, queryset):
|
||||||
|
from django.db import models
|
||||||
|
queryset.update(is_approved=True, approved_at=models.DateTimeField(auto_now=True))
|
||||||
|
self.message_user(request, "Выбранные названия были одобрены")
|
||||||
|
|
||||||
|
approve_selected.short_description = "Одобрить выбранные названия"
|
||||||
|
|
||||||
|
def reject_selected(self, request, queryset):
|
||||||
|
queryset.update(is_approved=False, approved_at=None)
|
||||||
|
self.message_user(request, "Выбранные названия были отклонены")
|
||||||
|
|
||||||
|
reject_selected.short_description = "Отклонить выбранные названия"
|
||||||
|
|||||||
@@ -313,15 +313,17 @@ class KitItemForm(forms.ModelForm):
|
|||||||
"""
|
"""
|
||||||
class Meta:
|
class Meta:
|
||||||
model = KitItem
|
model = KitItem
|
||||||
fields = ['product', 'variant_group', 'quantity']
|
fields = ['product', 'variant_group', 'sales_unit', 'quantity']
|
||||||
labels = {
|
labels = {
|
||||||
'product': 'Конкретный товар',
|
'product': 'Конкретный товар',
|
||||||
'variant_group': 'Группа вариантов',
|
'variant_group': 'Группа вариантов',
|
||||||
|
'sales_unit': 'Единица продажи',
|
||||||
'quantity': 'Количество'
|
'quantity': 'Количество'
|
||||||
}
|
}
|
||||||
widgets = {
|
widgets = {
|
||||||
'product': forms.Select(attrs={'class': 'form-control'}),
|
'product': forms.Select(attrs={'class': 'form-control'}),
|
||||||
'variant_group': forms.Select(attrs={'class': 'form-control'}),
|
'variant_group': forms.Select(attrs={'class': 'form-control'}),
|
||||||
|
'sales_unit': forms.Select(attrs={'class': 'form-control'}),
|
||||||
'quantity': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.001', 'min': '0'}),
|
'quantity': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.001', 'min': '0'}),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -335,24 +337,35 @@ class KitItemForm(forms.ModelForm):
|
|||||||
cleaned_data = super().clean()
|
cleaned_data = super().clean()
|
||||||
product = cleaned_data.get('product')
|
product = cleaned_data.get('product')
|
||||||
variant_group = cleaned_data.get('variant_group')
|
variant_group = cleaned_data.get('variant_group')
|
||||||
|
sales_unit = cleaned_data.get('sales_unit')
|
||||||
quantity = cleaned_data.get('quantity')
|
quantity = cleaned_data.get('quantity')
|
||||||
|
|
||||||
# Если оба поля пусты - это пустая форма (не валидируем, она будет удалена)
|
# Подсчитываем, сколько полей заполнено
|
||||||
if not product and not variant_group:
|
filled_fields = sum([bool(product), bool(variant_group), bool(sales_unit)])
|
||||||
|
|
||||||
|
# Если все поля пусты - это пустая форма (не валидируем, она будет удалена)
|
||||||
|
if filled_fields == 0:
|
||||||
# Для пустых форм обнуляем количество
|
# Для пустых форм обнуляем количество
|
||||||
cleaned_data['quantity'] = None
|
cleaned_data['quantity'] = None
|
||||||
return cleaned_data
|
return cleaned_data
|
||||||
|
|
||||||
# Валидация: должен быть указан либо product, либо variant_group (но не оба)
|
# Валидация несовместимых полей
|
||||||
if product and variant_group:
|
if variant_group and (product or sales_unit):
|
||||||
raise forms.ValidationError(
|
raise forms.ValidationError(
|
||||||
"Нельзя указывать одновременно товар и группу вариантов. Выберите что-то одно."
|
"Нельзя указывать группу вариантов одновременно с товаром или единицей продажи."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Валидация: если выбран товар/группа, количество обязательно и должно быть > 0
|
# Если выбрана единица продажи, товар обязателен
|
||||||
if (product or variant_group):
|
if sales_unit and not product:
|
||||||
if not quantity or quantity <= 0:
|
raise forms.ValidationError("Для единицы продажи должен быть выбран товар.")
|
||||||
raise forms.ValidationError('Необходимо указать количество больше 0')
|
|
||||||
|
# Валидация: если выбран товар/группа/единица продажи, количество обязательно и должно быть > 0
|
||||||
|
if not quantity or quantity <= 0:
|
||||||
|
raise forms.ValidationError('Необходимо указать количество больше 0')
|
||||||
|
|
||||||
|
# Валидация: если выбрана единица продажи, проверяем, что она принадлежит выбранному продукту
|
||||||
|
if sales_unit and product and sales_unit.product != product:
|
||||||
|
raise forms.ValidationError('Выбранная единица продажи не принадлежит указанному товару.')
|
||||||
|
|
||||||
return cleaned_data
|
return cleaned_data
|
||||||
|
|
||||||
@@ -367,6 +380,7 @@ class BaseKitItemFormSet(forms.BaseInlineFormSet):
|
|||||||
|
|
||||||
products = []
|
products = []
|
||||||
variant_groups = []
|
variant_groups = []
|
||||||
|
sales_units = []
|
||||||
|
|
||||||
for form in self.forms:
|
for form in self.forms:
|
||||||
if self.can_delete and self._should_delete_form(form):
|
if self.can_delete and self._should_delete_form(form):
|
||||||
@@ -374,6 +388,7 @@ class BaseKitItemFormSet(forms.BaseInlineFormSet):
|
|||||||
|
|
||||||
product = form.cleaned_data.get('product')
|
product = form.cleaned_data.get('product')
|
||||||
variant_group = form.cleaned_data.get('variant_group')
|
variant_group = form.cleaned_data.get('variant_group')
|
||||||
|
sales_unit = form.cleaned_data.get('sales_unit')
|
||||||
|
|
||||||
# Проверка дубликатов товаров
|
# Проверка дубликатов товаров
|
||||||
if product:
|
if product:
|
||||||
@@ -393,13 +408,22 @@ class BaseKitItemFormSet(forms.BaseInlineFormSet):
|
|||||||
)
|
)
|
||||||
variant_groups.append(variant_group)
|
variant_groups.append(variant_group)
|
||||||
|
|
||||||
|
# Проверка дубликатов единиц продажи
|
||||||
|
if sales_unit:
|
||||||
|
if sales_unit in sales_units:
|
||||||
|
raise forms.ValidationError(
|
||||||
|
f'Единица продажи "{sales_unit.name}" добавлена в комплект более одного раза. '
|
||||||
|
f'Каждая единица продажи может быть добавлена только один раз.'
|
||||||
|
)
|
||||||
|
sales_units.append(sales_unit)
|
||||||
|
|
||||||
# Формсет для создания комплектов (с пустой формой для удобства)
|
# Формсет для создания комплектов (с пустой формой для удобства)
|
||||||
KitItemFormSetCreate = inlineformset_factory(
|
KitItemFormSetCreate = inlineformset_factory(
|
||||||
ProductKit,
|
ProductKit,
|
||||||
KitItem,
|
KitItem,
|
||||||
form=KitItemForm,
|
form=KitItemForm,
|
||||||
formset=BaseKitItemFormSet,
|
formset=BaseKitItemFormSet,
|
||||||
fields=['product', 'variant_group', 'quantity'],
|
fields=['product', 'variant_group', 'sales_unit', 'quantity'],
|
||||||
extra=1, # Показать 1 пустую форму для первого компонента
|
extra=1, # Показать 1 пустую форму для первого компонента
|
||||||
can_delete=True, # Разрешить удаление компонентов
|
can_delete=True, # Разрешить удаление компонентов
|
||||||
min_num=0, # Минимум 0 компонентов (можно создать пустой комплект)
|
min_num=0, # Минимум 0 компонентов (можно создать пустой комплект)
|
||||||
@@ -413,7 +437,7 @@ KitItemFormSetUpdate = inlineformset_factory(
|
|||||||
KitItem,
|
KitItem,
|
||||||
form=KitItemForm,
|
form=KitItemForm,
|
||||||
formset=BaseKitItemFormSet,
|
formset=BaseKitItemFormSet,
|
||||||
fields=['product', 'variant_group', 'quantity'],
|
fields=['product', 'variant_group', 'sales_unit', 'quantity'],
|
||||||
extra=0, # НЕ показывать пустые формы при редактировании
|
extra=0, # НЕ показывать пустые формы при редактировании
|
||||||
can_delete=True, # Разрешить удаление компонентов
|
can_delete=True, # Разрешить удаление компонентов
|
||||||
min_num=0, # Минимум 0 компонентов
|
min_num=0, # Минимум 0 компонентов
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Generated migration file for adding sales_unit field to KitItem model
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('products', '0005_base_unit_nullable'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='kititem',
|
||||||
|
name='sales_unit',
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='kit_items',
|
||||||
|
to='products.productsalesunit',
|
||||||
|
verbose_name='Единица продажи'
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
||||||
33
myproject/products/migrations/0002_bouquetname.py
Normal file
33
myproject/products/migrations/0002_bouquetname.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2026-01-22 10:09
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('products', '0001_add_sales_unit_to_kititem'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='BouquetName',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('name', models.CharField(max_length=100, unique=True, verbose_name='Название букета')),
|
||||||
|
('language', models.CharField(default='russian', max_length=10, verbose_name='Язык')),
|
||||||
|
('is_approved', models.BooleanField(default=False, verbose_name='Одобрено для использования')),
|
||||||
|
('usage_count', models.PositiveIntegerField(default=0, verbose_name='Количество использований')),
|
||||||
|
('generated_at', models.DateTimeField(auto_now_add=True, verbose_name='Дата генерации')),
|
||||||
|
('approved_at', models.DateTimeField(blank=True, null=True, verbose_name='Дата одобрения')),
|
||||||
|
('color_tags', models.ManyToManyField(blank=True, related_name='bouquet_names_by_color', to='products.producttag', verbose_name='Цветные теги')),
|
||||||
|
('occasion_tags', models.ManyToManyField(blank=True, related_name='bouquet_names_by_occasion', to='products.producttag', verbose_name='Теги по поводу')),
|
||||||
|
('style_tags', models.ManyToManyField(blank=True, related_name='bouquet_names_by_style', to='products.producttag', verbose_name='Теги по стилю')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Название букета',
|
||||||
|
'verbose_name_plural': 'Названия букетов',
|
||||||
|
'indexes': [models.Index(fields=['language', 'is_approved'], name='products_bo_languag_8622de_idx'), models.Index(fields=['usage_count'], name='products_bo_usage_c_4ce5b8_idx')],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2026-01-23 22:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('products', '0002_bouquetname'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='productkit',
|
||||||
|
name='showcase_created_at',
|
||||||
|
field=models.DateTimeField(blank=True, help_text='Дата создания букета для витрины (редактируемая)', null=True, verbose_name='Дата размещения на витрине'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2026-01-19 12:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('products', '0003_remove_unit_from_sales_unit'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='kititem',
|
||||||
|
name='unit_price',
|
||||||
|
field=models.DecimalField(blank=True, decimal_places=2, help_text='Если задана, используется эта цена вместо актуальной цены товара. Применяется для временных витринных комплектов.', max_digits=10, null=True, verbose_name='Цена за единицу (зафиксированная)'),
|
||||||
|
),
|
||||||
|
]
|
||||||
19
myproject/products/migrations/0005_base_unit_nullable.py
Normal file
19
myproject/products/migrations/0005_base_unit_nullable.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2026-01-20 21:26
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('products', '0004_add_unit_price_to_kit_item'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='product',
|
||||||
|
name='base_unit',
|
||||||
|
field=models.ForeignKey(blank=True, help_text='Единица хранения и закупки (банч, кг, шт). Товар принимается и хранится в этих единицах.', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='products', to='products.unitofmeasure', verbose_name='Базовая единица'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -49,6 +49,9 @@ from .photos import BasePhoto, ProductPhoto, ProductKitPhoto, ProductCategoryPho
|
|||||||
# Задачи импорта
|
# Задачи импорта
|
||||||
from .import_job import ProductImportJob
|
from .import_job import ProductImportJob
|
||||||
|
|
||||||
|
# Названия букетов
|
||||||
|
from .bouquet_names import BouquetName
|
||||||
|
|
||||||
# Явно указываем, что экспортируется при импорте *
|
# Явно указываем, что экспортируется при импорте *
|
||||||
__all__ = [
|
__all__ = [
|
||||||
# Managers
|
# Managers
|
||||||
@@ -98,4 +101,7 @@ __all__ = [
|
|||||||
|
|
||||||
# Import Jobs
|
# Import Jobs
|
||||||
'ProductImportJob',
|
'ProductImportJob',
|
||||||
|
|
||||||
|
# Bouquet Names
|
||||||
|
'BouquetName',
|
||||||
]
|
]
|
||||||
|
|||||||
73
myproject/products/models/bouquet_names.py
Normal file
73
myproject/products/models/bouquet_names.py
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
from django.db import models
|
||||||
|
from .categories import ProductTag
|
||||||
|
|
||||||
|
|
||||||
|
class BouquetName(models.Model):
|
||||||
|
"""
|
||||||
|
Модель для хранения предопределенных названий букетов с метаинформацией
|
||||||
|
"""
|
||||||
|
name = models.CharField(
|
||||||
|
max_length=100,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Название букета"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Категории характеристик
|
||||||
|
color_tags = models.ManyToManyField(
|
||||||
|
ProductTag,
|
||||||
|
blank=True,
|
||||||
|
related_name='bouquet_names_by_color',
|
||||||
|
verbose_name="Цветные теги"
|
||||||
|
)
|
||||||
|
|
||||||
|
occasion_tags = models.ManyToManyField(
|
||||||
|
ProductTag,
|
||||||
|
blank=True,
|
||||||
|
related_name='bouquet_names_by_occasion',
|
||||||
|
verbose_name="Теги по поводу"
|
||||||
|
)
|
||||||
|
|
||||||
|
style_tags = models.ManyToManyField(
|
||||||
|
ProductTag,
|
||||||
|
blank=True,
|
||||||
|
related_name='bouquet_names_by_style',
|
||||||
|
verbose_name="Теги по стилю"
|
||||||
|
)
|
||||||
|
|
||||||
|
language = models.CharField(
|
||||||
|
max_length=10,
|
||||||
|
default='russian',
|
||||||
|
verbose_name="Язык"
|
||||||
|
)
|
||||||
|
|
||||||
|
is_approved = models.BooleanField(
|
||||||
|
default=False,
|
||||||
|
verbose_name="Одобрено для использования"
|
||||||
|
)
|
||||||
|
|
||||||
|
usage_count = models.PositiveIntegerField(
|
||||||
|
default=0,
|
||||||
|
verbose_name="Количество использований"
|
||||||
|
)
|
||||||
|
|
||||||
|
generated_at = models.DateTimeField(
|
||||||
|
auto_now_add=True,
|
||||||
|
verbose_name="Дата генерации"
|
||||||
|
)
|
||||||
|
|
||||||
|
approved_at = models.DateTimeField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name="Дата одобрения"
|
||||||
|
)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = "Название букета"
|
||||||
|
verbose_name_plural = "Названия букетов"
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=['language', 'is_approved']),
|
||||||
|
models.Index(fields=['usage_count']),
|
||||||
|
]
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.name
|
||||||
@@ -93,6 +93,14 @@ class ProductKit(BaseProductEntity):
|
|||||||
help_text="Временные комплекты не показываются в каталоге и создаются для конкретного заказа"
|
help_text="Временные комплекты не показываются в каталоге и создаются для конкретного заказа"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Showcase creation date - editable date for when the bouquet was put on display
|
||||||
|
showcase_created_at = models.DateTimeField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name="Дата размещения на витрине",
|
||||||
|
help_text="Дата создания букета для витрины (редактируемая)"
|
||||||
|
)
|
||||||
|
|
||||||
order = models.ForeignKey(
|
order = models.ForeignKey(
|
||||||
'orders.Order',
|
'orders.Order',
|
||||||
on_delete=models.SET_NULL,
|
on_delete=models.SET_NULL,
|
||||||
@@ -162,13 +170,21 @@ class ProductKit(BaseProductEntity):
|
|||||||
|
|
||||||
total = Decimal('0')
|
total = Decimal('0')
|
||||||
for item in self.kit_items.all():
|
for item in self.kit_items.all():
|
||||||
if item.product:
|
qty = item.quantity or Decimal('1')
|
||||||
actual_price = item.product.actual_price or Decimal('0')
|
if item.sales_unit:
|
||||||
qty = item.quantity or Decimal('1')
|
# Для sales_unit используем цену единицы продажи
|
||||||
total += actual_price * qty
|
unit_price = item.sales_unit.actual_price or Decimal('0')
|
||||||
|
total += unit_price * qty
|
||||||
|
elif item.product:
|
||||||
|
# Используем зафиксированную цену если есть, иначе актуальную цену товара
|
||||||
|
if item.unit_price is not None:
|
||||||
|
unit_price = item.unit_price
|
||||||
|
else:
|
||||||
|
unit_price = item.product.actual_price or Decimal('0')
|
||||||
|
total += unit_price * qty
|
||||||
elif item.variant_group:
|
elif item.variant_group:
|
||||||
|
# Для variant_group unit_price не используется (только для продуктов)
|
||||||
actual_price = item.variant_group.price or Decimal('0')
|
actual_price = item.variant_group.price or Decimal('0')
|
||||||
qty = item.quantity or Decimal('1')
|
|
||||||
total += actual_price * qty
|
total += actual_price * qty
|
||||||
|
|
||||||
self.base_price = total
|
self.base_price = total
|
||||||
@@ -209,7 +225,11 @@ class ProductKit(BaseProductEntity):
|
|||||||
# Пересчитаем базовую цену из компонентов
|
# Пересчитаем базовую цену из компонентов
|
||||||
total = Decimal('0')
|
total = Decimal('0')
|
||||||
for item in self.kit_items.all():
|
for item in self.kit_items.all():
|
||||||
if item.product:
|
if item.sales_unit:
|
||||||
|
actual_price = item.sales_unit.actual_price or Decimal('0')
|
||||||
|
qty = item.quantity or Decimal('1')
|
||||||
|
total += actual_price * qty
|
||||||
|
elif item.product:
|
||||||
actual_price = item.product.actual_price or Decimal('0')
|
actual_price = item.product.actual_price or Decimal('0')
|
||||||
qty = item.quantity or Decimal('1')
|
qty = item.quantity or Decimal('1')
|
||||||
total += actual_price * qty
|
total += actual_price * qty
|
||||||
@@ -297,7 +317,12 @@ class ProductKit(BaseProductEntity):
|
|||||||
min_available = kits_from_this_component
|
min_available = kits_from_this_component
|
||||||
|
|
||||||
# Возвращаем целую часть (нельзя собрать половину комплекта)
|
# Возвращаем целую часть (нельзя собрать половину комплекта)
|
||||||
return Decimal(int(min_available)) if min_available is not None else Decimal('0')
|
# Нельзя собрать отрицательное количество комплектов
|
||||||
|
if min_available is not None:
|
||||||
|
if min_available <= 0:
|
||||||
|
return Decimal('0')
|
||||||
|
return Decimal(int(min_available))
|
||||||
|
return Decimal('0')
|
||||||
|
|
||||||
def make_permanent(self):
|
def make_permanent(self):
|
||||||
"""
|
"""
|
||||||
@@ -315,17 +340,6 @@ class ProductKit(BaseProductEntity):
|
|||||||
self.save(update_fields=['is_temporary', 'order'])
|
self.save(update_fields=['is_temporary', 'order'])
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def delete(self, *args, **kwargs):
|
|
||||||
"""Soft delete вместо hard delete - марк как удаленный"""
|
|
||||||
self.is_deleted = True
|
|
||||||
self.deleted_at = timezone.now()
|
|
||||||
self.save(update_fields=['is_deleted', 'deleted_at'])
|
|
||||||
return 1, {self.__class__._meta.label: 1}
|
|
||||||
|
|
||||||
def hard_delete(self):
|
|
||||||
"""Полное удаление из БД (необратимо!)"""
|
|
||||||
super().delete()
|
|
||||||
|
|
||||||
def create_snapshot(self):
|
def create_snapshot(self):
|
||||||
"""
|
"""
|
||||||
Создает снимок текущего состояния комплекта.
|
Создает снимок текущего состояния комплекта.
|
||||||
@@ -365,6 +379,8 @@ class ProductKit(BaseProductEntity):
|
|||||||
product_sku=item.product.sku if item.product else '',
|
product_sku=item.product.sku if item.product else '',
|
||||||
product_price=product_price,
|
product_price=product_price,
|
||||||
variant_group_name=item.variant_group.name if item.variant_group else '',
|
variant_group_name=item.variant_group.name if item.variant_group else '',
|
||||||
|
original_sales_unit=item.sales_unit,
|
||||||
|
conversion_factor=item.sales_unit.conversion_factor if item.sales_unit else None,
|
||||||
quantity=item.quantity or Decimal('1'),
|
quantity=item.quantity or Decimal('1'),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -373,8 +389,8 @@ class ProductKit(BaseProductEntity):
|
|||||||
|
|
||||||
class KitItem(models.Model):
|
class KitItem(models.Model):
|
||||||
"""
|
"""
|
||||||
Состав комплекта: связь между ProductKit и Product или ProductVariantGroup.
|
Состав комплекта: связь между ProductKit и Product, ProductVariantGroup или ProductSalesUnit.
|
||||||
Позиция может быть либо конкретным товаром, либо группой вариантов.
|
Позиция может быть либо конкретным товаром, либо группой вариантов, либо конкретной единицей продажи.
|
||||||
"""
|
"""
|
||||||
kit = models.ForeignKey(ProductKit, on_delete=models.CASCADE, related_name='kit_items',
|
kit = models.ForeignKey(ProductKit, on_delete=models.CASCADE, related_name='kit_items',
|
||||||
verbose_name="Комплект")
|
verbose_name="Комплект")
|
||||||
@@ -394,7 +410,23 @@ class KitItem(models.Model):
|
|||||||
related_name='kit_items',
|
related_name='kit_items',
|
||||||
verbose_name="Группа вариантов"
|
verbose_name="Группа вариантов"
|
||||||
)
|
)
|
||||||
|
sales_unit = models.ForeignKey(
|
||||||
|
'ProductSalesUnit',
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
related_name='kit_items',
|
||||||
|
verbose_name="Единица продажи"
|
||||||
|
)
|
||||||
quantity = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, verbose_name="Количество")
|
quantity = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, verbose_name="Количество")
|
||||||
|
unit_price = models.DecimalField(
|
||||||
|
max_digits=10,
|
||||||
|
decimal_places=2,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name="Цена за единицу (зафиксированная)",
|
||||||
|
help_text="Если задана, используется эта цена вместо актуальной цены товара. Применяется для временных витринных комплектов."
|
||||||
|
)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = "Компонент комплекта"
|
verbose_name = "Компонент комплекта"
|
||||||
@@ -411,21 +443,46 @@ class KitItem(models.Model):
|
|||||||
return f"{self.kit.name} - {self.get_display_name()}"
|
return f"{self.kit.name} - {self.get_display_name()}"
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
"""Валидация: должен быть указан либо product, либо variant_group (но не оба)"""
|
"""Валидация: должна быть указана группа вариантов ИЛИ (товар [плюс опционально единица продажи])"""
|
||||||
if self.product and self.variant_group:
|
|
||||||
raise ValidationError(
|
has_variant = bool(self.variant_group)
|
||||||
"Нельзя указывать одновременно товар и группу вариантов. Выберите что-то одно."
|
has_product = bool(self.product)
|
||||||
)
|
has_sales_unit = bool(self.sales_unit)
|
||||||
if not self.product and not self.variant_group:
|
|
||||||
|
# 1. Проверка на пустоту
|
||||||
|
if not (has_variant or has_product or has_sales_unit):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Необходимо указать либо товар, либо группу вариантов."
|
"Необходимо указать либо товар, либо группу вариантов."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 2. Несовместимость: Группа вариантов VS Товар/Единица
|
||||||
|
if has_variant and (has_product or has_sales_unit):
|
||||||
|
raise ValidationError(
|
||||||
|
"Нельзя указывать группу вариантов одновременно с товаром или единицей продажи."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Зависимость: Если есть sales_unit, должен быть product
|
||||||
|
if has_sales_unit and not has_product:
|
||||||
|
raise ValidationError(
|
||||||
|
"Если указана единица продажи, должен быть выбран соответствующий товар."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Проверка принадлежности
|
||||||
|
if has_sales_unit and has_product and self.sales_unit.product != self.product:
|
||||||
|
raise ValidationError(
|
||||||
|
"Выбранная единица продажи не принадлежит указанному товару."
|
||||||
|
)
|
||||||
|
|
||||||
def get_display_name(self):
|
def get_display_name(self):
|
||||||
"""Возвращает строку для отображения названия компонента"""
|
"""Возвращает строку для отображения названия компонента"""
|
||||||
if self.variant_group:
|
# Приоритет: сначала единица продажи, затем товар, затем группа вариантов
|
||||||
|
if self.sales_unit:
|
||||||
|
return f"[Единица продажи] {self.sales_unit.name}"
|
||||||
|
elif self.product:
|
||||||
|
return self.product.name
|
||||||
|
elif self.variant_group:
|
||||||
return f"[Варианты] {self.variant_group.name}"
|
return f"[Варианты] {self.variant_group.name}"
|
||||||
return self.product.name if self.product else "Не указан"
|
return "Не указан"
|
||||||
|
|
||||||
def has_priorities_set(self):
|
def has_priorities_set(self):
|
||||||
"""Проверяет, настроены ли приоритеты замены для данного компонента"""
|
"""Проверяет, настроены ли приоритеты замены для данного компонента"""
|
||||||
@@ -435,10 +492,16 @@ class KitItem(models.Model):
|
|||||||
"""
|
"""
|
||||||
Возвращает список доступных товаров для этого компонента.
|
Возвращает список доступных товаров для этого компонента.
|
||||||
|
|
||||||
|
Если указана единица продажи - возвращает товар, к которому она относится.
|
||||||
Если указан конкретный товар - возвращает его.
|
Если указан конкретный товар - возвращает его.
|
||||||
Если указаны приоритеты - возвращает товары в порядке приоритета.
|
Если указаны приоритеты - возвращает товары в порядке приоритета.
|
||||||
Если не указаны приоритеты - возвращает все активные товары из группы вариантов.
|
Если не указаны приоритеты - возвращает все активные товары из группы вариантов.
|
||||||
"""
|
"""
|
||||||
|
# Приоритет: сначала единица продажи, затем товар, затем группа вариантов
|
||||||
|
if self.sales_unit:
|
||||||
|
# Если указана единица продажи, возвращаем товар, к которому она относится
|
||||||
|
return [self.sales_unit.product]
|
||||||
|
|
||||||
if self.product:
|
if self.product:
|
||||||
# Если указан конкретный товар, возвращаем только его
|
# Если указан конкретный товар, возвращаем только его
|
||||||
return [self.product]
|
return [self.product]
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ class Product(BaseProductEntity):
|
|||||||
on_delete=models.PROTECT,
|
on_delete=models.PROTECT,
|
||||||
related_name='products',
|
related_name='products',
|
||||||
verbose_name="Базовая единица",
|
verbose_name="Базовая единица",
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
help_text="Единица хранения и закупки (банч, кг, шт). Товар принимается и хранится в этих единицах."
|
help_text="Единица хранения и закупки (банч, кг, шт). Товар принимается и хранится в этих единицах."
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -139,6 +141,14 @@ class Product(BaseProductEntity):
|
|||||||
from ..services.cost_calculator import ProductCostCalculator
|
from ..services.cost_calculator import ProductCostCalculator
|
||||||
return ProductCostCalculator.get_cost_details(self)
|
return ProductCostCalculator.get_cost_details(self)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def kit_items_using_as_sales_unit(self):
|
||||||
|
"""
|
||||||
|
Возвращает QuerySet KitItem, где этот товар используется как единица продажи.
|
||||||
|
"""
|
||||||
|
from .kits import KitItem
|
||||||
|
return KitItem.objects.filter(sales_unit__product=self)
|
||||||
|
|
||||||
def save(self, *args, **kwargs):
|
def save(self, *args, **kwargs):
|
||||||
# Используем сервис для подготовки к сохранению
|
# Используем сервис для подготовки к сохранению
|
||||||
ProductSaveService.prepare_product_for_save(self)
|
ProductSaveService.prepare_product_for_save(self)
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
Сервисы для бизнес-логики products приложения.
|
Сервисы для бизнес-логики products приложения.
|
||||||
Следует принципу "Skinny Models, Fat Services".
|
Следует принципу "Тонкие модели, толстые сервисы".
|
||||||
"""
|
"""
|
||||||
from .unit_service import UnitOfMeasureService
|
from .unit_service import UnitOfMeasureService
|
||||||
|
from .ai.bouquet_names import BouquetNameGenerator
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'UnitOfMeasureService',
|
'UnitOfMeasureService',
|
||||||
|
'BouquetNameGenerator',
|
||||||
]
|
]
|
||||||
|
|||||||
6
myproject/products/services/ai/__init__.py
Normal file
6
myproject/products/services/ai/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
"""
|
||||||
|
AI-сервисы для products приложения.
|
||||||
|
|
||||||
|
Содержит инструменты для взаимодействия с нейросетями для решения специфичных
|
||||||
|
бизнес-задач, таких как генерация названий продуктов, описаний, классификация и т.д.
|
||||||
|
"""
|
||||||
48
myproject/products/services/ai/base.py
Normal file
48
myproject/products/services/ai/base.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import Tuple, Optional, Dict
|
||||||
|
from integrations.services.ai_services.glm_service import GLMIntegrationService
|
||||||
|
from integrations.services.ai_services.openrouter_service import OpenRouterIntegrationService
|
||||||
|
from integrations.models.ai_services.glm import GLMIntegration
|
||||||
|
from integrations.models.ai_services.openrouter import OpenRouterIntegration
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class BaseAIProductService(ABC):
|
||||||
|
"""
|
||||||
|
Абстрактный базовый класс для AI-сервисов продуктов
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def generate(self, **kwargs) -> Tuple[bool, str, Optional[Dict]]:
|
||||||
|
"""
|
||||||
|
Основной метод генерации
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_glm_service(cls) -> Optional[GLMIntegrationService]:
|
||||||
|
"""
|
||||||
|
Получить сервис GLM из активной интеграции
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
integration = GLMIntegration.objects.filter(is_active=True).first()
|
||||||
|
if integration:
|
||||||
|
return GLMIntegrationService(integration)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Ошибка при получении GLM сервиса: {str(e)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_openrouter_service(cls) -> Optional[OpenRouterIntegrationService]:
|
||||||
|
"""
|
||||||
|
Получить сервис OpenRouter из активной интеграции
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
integration = OpenRouterIntegration.objects.filter(is_active=True).first()
|
||||||
|
if integration:
|
||||||
|
return OpenRouterIntegrationService(integration)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Ошибка при получении OpenRouter сервиса: {str(e)}")
|
||||||
|
return None
|
||||||
272
myproject/products/services/ai/bouquet_names.py
Normal file
272
myproject/products/services/ai/bouquet_names.py
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
from typing import Tuple, Optional, Dict, List
|
||||||
|
from .base import BaseAIProductService
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class BouquetNameGenerator(BaseAIProductService):
|
||||||
|
"""
|
||||||
|
Сервис для генерации и управления названиями букетов
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_SYSTEM_PROMPT = (
|
||||||
|
"Вы эксперт в создании красивых, привлекательных и продаваемых названий для букетов цветов. "
|
||||||
|
"Ваша цель — генерировать запоминающиеся и выразительные названия, которые привлекут покупателей. "
|
||||||
|
"Названия должны быть краткими (2-4 слов), креативными и соответствующими характеристикам букета. "
|
||||||
|
"Избегайте общих терминов. Фокусируйтесь на эмоциях, эстетике"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Константы
|
||||||
|
MAX_TOKENS_GENERATION = 3000
|
||||||
|
DEFAULT_COUNT = 500
|
||||||
|
MAX_GENERATION_COUNT = 1000
|
||||||
|
SKIP_PREFIXES = {'here', 'names', "i'm", 'sorry', 'i hope', 'hope'}
|
||||||
|
|
||||||
|
def generate(
|
||||||
|
self,
|
||||||
|
count: int = 500,
|
||||||
|
characteristics: Optional[str] = None,
|
||||||
|
occasion: Optional[str] = None,
|
||||||
|
language: str = "russian"
|
||||||
|
) -> Tuple[bool, str, Optional[Dict]]:
|
||||||
|
"""
|
||||||
|
Генерация названий букетов
|
||||||
|
|
||||||
|
Args:
|
||||||
|
count: Количество названий для генерации
|
||||||
|
characteristics: Характеристики букетов (например, "розы, лилии, яркий")
|
||||||
|
occasion: П'occasion (например, "день рождения, Valentine's Day")
|
||||||
|
language: Язык генерации
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple: (success, message, data) где data содержит список названий
|
||||||
|
"""
|
||||||
|
# Валидация параметров
|
||||||
|
if count > self.MAX_GENERATION_COUNT:
|
||||||
|
count = self.MAX_GENERATION_COUNT
|
||||||
|
logger.warning(f"Count reduced to {self.MAX_GENERATION_COUNT}")
|
||||||
|
|
||||||
|
logger.info(f"Генерация {count} названий для букетов")
|
||||||
|
|
||||||
|
# Получаем доступный AI-сервис
|
||||||
|
service = self.get_glm_service() or self.get_openrouter_service()
|
||||||
|
if not service:
|
||||||
|
return False, "Нет активных AI-интеграций", None
|
||||||
|
|
||||||
|
# Формируем промпт
|
||||||
|
prompt = f"Сгенерируй {count} креативных и привлекательных названий для букетов цветов"
|
||||||
|
|
||||||
|
if characteristics:
|
||||||
|
prompt += f" с следующими характеристиками: {characteristics}"
|
||||||
|
|
||||||
|
if occasion:
|
||||||
|
prompt += f" для праздника: {occasion}"
|
||||||
|
|
||||||
|
prompt += (
|
||||||
|
"\n\nТребования к каждому названию:\n"
|
||||||
|
"- 2, 3 или 4 слова в равных пропорциях\n"
|
||||||
|
"- Выразительные и эмоциональные\n"
|
||||||
|
"- Продаваемые и запоминающиеся\n"
|
||||||
|
"- Избегайте общих названий типа 'Букет #1'\n"
|
||||||
|
"- Фокусируйтесь на красоте, романтике и подарках\n"
|
||||||
|
"- Используйте прилагательные и описательные слова\n"
|
||||||
|
"- Не используйте символы пунктуации в середине названий\n"
|
||||||
|
"\nВерните названия в виде нумерованного списка, по одному на строку.\n"
|
||||||
|
"Примеры хороших названий:\n"
|
||||||
|
"- 2 слова: 'Весенние Розы', 'Летнее Сияние', 'Нежность', 'Романтика'\n"
|
||||||
|
"- 3 слова: 'Весенний Вальс', 'Нежность Роз', 'Сияние Любви', 'Танец Цветов'\n"
|
||||||
|
"- 4 слова: 'Шепот Весенней Нежности', 'Сияние Розовой Любви', 'Танец Цветов Весны', 'Шёпот Сердечной Романтики'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Вызов AI-сервиса
|
||||||
|
success, msg, response = service.generate_text(
|
||||||
|
prompt=prompt,
|
||||||
|
system_prompt=self.DEFAULT_SYSTEM_PROMPT,
|
||||||
|
max_tokens=3000 # Увеличиваем лимит для большего числа названий
|
||||||
|
)
|
||||||
|
|
||||||
|
if not success:
|
||||||
|
return False, msg, None
|
||||||
|
|
||||||
|
# Парсим результат
|
||||||
|
names = self._parse_response(response.get('generated_text', ''))
|
||||||
|
|
||||||
|
return True, f"Сгенерировано {len(names)} названий для букетов", {
|
||||||
|
'names': names,
|
||||||
|
'model': response.get('model'),
|
||||||
|
'usage': response.get('usage')
|
||||||
|
}
|
||||||
|
|
||||||
|
def _parse_response(self, text: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Парсит текстовый ответ AI и извлекает названия букетов
|
||||||
|
"""
|
||||||
|
names = []
|
||||||
|
lines = text.split('\n')
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
line = line.strip()
|
||||||
|
# Пропускаем пустые строки и заголовки
|
||||||
|
if not line or any(line.lower().startswith(prefix) for prefix in self.SKIP_PREFIXES):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Удаляем номера списка
|
||||||
|
if line and (line[0].isdigit() or line[0] == '-'):
|
||||||
|
# Удаляем номер и точку или дефис
|
||||||
|
if '.' in line:
|
||||||
|
line = line.split('.', 1)[1].strip()
|
||||||
|
else:
|
||||||
|
line = line[1:].strip()
|
||||||
|
|
||||||
|
# Пропускаем строки, которые стали пустыми после удаления номера
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Удаляем markdown форматирование (жирный, курсив)
|
||||||
|
line = line.replace('**', '').replace('*', '').replace('"', '').replace("'", '').strip()
|
||||||
|
|
||||||
|
if line:
|
||||||
|
# Приводим к нужному формату: первое слово с заглавной, остальные строчные
|
||||||
|
normalized_line = self._normalize_case(line)
|
||||||
|
names.append(normalized_line)
|
||||||
|
|
||||||
|
# Фильтруем и сортируем названия по длине для равномерного распределения
|
||||||
|
names_by_length = {2: [], 3: [], 4: []}
|
||||||
|
|
||||||
|
for name in names:
|
||||||
|
word_count = len(name.split())
|
||||||
|
if word_count in names_by_length:
|
||||||
|
names_by_length[word_count].append(name)
|
||||||
|
|
||||||
|
# Удаляем дубликаты в каждой группе
|
||||||
|
for length in names_by_length:
|
||||||
|
unique_list = []
|
||||||
|
seen = set()
|
||||||
|
for name in names_by_length[length]:
|
||||||
|
if name not in seen:
|
||||||
|
seen.add(name)
|
||||||
|
unique_list.append(name)
|
||||||
|
names_by_length[length] = unique_list
|
||||||
|
|
||||||
|
# Объединяем названия в один список в пропорциях 2:3:4
|
||||||
|
balanced_names = []
|
||||||
|
|
||||||
|
# Определяем максимальное количество названий одного типа
|
||||||
|
max_per_length = max(len(names_list) for names_list in names_by_length.values()) if any(names_by_length.values()) else 0
|
||||||
|
|
||||||
|
# Добавляем названия по одному из каждой категории по очереди
|
||||||
|
for i in range(max_per_length):
|
||||||
|
for length in [2, 3, 4]: # Проходим по длине 2, 3, 4
|
||||||
|
if i < len(names_by_length[length]):
|
||||||
|
balanced_names.append(names_by_length[length][i])
|
||||||
|
|
||||||
|
return balanced_names
|
||||||
|
|
||||||
|
def _normalize_case(self, text: str) -> str:
|
||||||
|
"""
|
||||||
|
Приводит текст к формату: первое слово с заглавной буквы, остальные строчные
|
||||||
|
Например: "романтический БУКЕТ роз" -> "Романтический букет роз"
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return text
|
||||||
|
|
||||||
|
# Разбиваем текст на слова
|
||||||
|
words = text.split()
|
||||||
|
|
||||||
|
if not words:
|
||||||
|
return text
|
||||||
|
|
||||||
|
# Первое слово с заглавной буквы, остальные строчные
|
||||||
|
normalized_words = [words[0].capitalize()] + [word.lower() for word in words[1:]]
|
||||||
|
|
||||||
|
# Собираем обратно в строку
|
||||||
|
return ' '.join(normalized_words)
|
||||||
|
|
||||||
|
def generate_and_store(
|
||||||
|
self,
|
||||||
|
count: int = 500,
|
||||||
|
characteristics: Optional[str] = None,
|
||||||
|
occasion: Optional[str] = None,
|
||||||
|
language: str = "russian"
|
||||||
|
) -> Tuple[bool, str, Optional[Dict]]:
|
||||||
|
"""
|
||||||
|
Генерирует названия и сохраняет в базу данных
|
||||||
|
"""
|
||||||
|
from products.models import BouquetName
|
||||||
|
|
||||||
|
success, msg, data = self.generate(count, characteristics, occasion, language)
|
||||||
|
|
||||||
|
if success and data:
|
||||||
|
# Сохраняем названия в базу
|
||||||
|
stored_count = 0
|
||||||
|
failed_count = 0
|
||||||
|
|
||||||
|
for name in data['names']:
|
||||||
|
try:
|
||||||
|
BouquetName.objects.get_or_create(
|
||||||
|
name=name,
|
||||||
|
language=language,
|
||||||
|
defaults={
|
||||||
|
'is_approved': False
|
||||||
|
}
|
||||||
|
)
|
||||||
|
stored_count += 1
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Ошибка сохранения названия '{name}': {e}")
|
||||||
|
failed_count += 1
|
||||||
|
|
||||||
|
success_msg = f"Сгенерировано и сохранено {stored_count} названий для букетов"
|
||||||
|
if failed_count > 0:
|
||||||
|
success_msg += f", не удалось сохранить {failed_count} названий"
|
||||||
|
|
||||||
|
return True, success_msg, data
|
||||||
|
|
||||||
|
return success, msg, data
|
||||||
|
|
||||||
|
def get_approved_names(
|
||||||
|
self,
|
||||||
|
color_tags: Optional[List[str]] = None,
|
||||||
|
occasion_tags: Optional[List[str]] = None,
|
||||||
|
style_tags: Optional[List[str]] = None,
|
||||||
|
language: str = "russian",
|
||||||
|
limit: int = 100
|
||||||
|
) -> List[str]:
|
||||||
|
"""
|
||||||
|
Получает одобренные названия с фильтрацией по тегам
|
||||||
|
"""
|
||||||
|
from products.models import BouquetName
|
||||||
|
|
||||||
|
queryset = BouquetName.objects.filter(
|
||||||
|
is_approved=True,
|
||||||
|
language=language
|
||||||
|
)
|
||||||
|
|
||||||
|
if color_tags:
|
||||||
|
queryset = queryset.filter(color_tags__name__in=color_tags)
|
||||||
|
|
||||||
|
if occasion_tags:
|
||||||
|
queryset = queryset.filter(occasion_tags__name__in=occasion_tags)
|
||||||
|
|
||||||
|
if style_tags:
|
||||||
|
queryset = queryset.filter(style_tags__name__in=style_tags)
|
||||||
|
|
||||||
|
# Сортируем по популярности
|
||||||
|
queryset = queryset.order_by('-usage_count')
|
||||||
|
|
||||||
|
return list(queryset.values_list('name', flat=True)[:limit])
|
||||||
|
|
||||||
|
def mark_as_used(self, name: str, language: str = "russian") -> None:
|
||||||
|
"""
|
||||||
|
Увеличивает счетчик использования названия
|
||||||
|
"""
|
||||||
|
from products.models import BouquetName
|
||||||
|
|
||||||
|
BouquetName.objects.filter(
|
||||||
|
name=name,
|
||||||
|
language=language
|
||||||
|
).update(
|
||||||
|
usage_count=models.F('usage_count') + 1
|
||||||
|
)
|
||||||
@@ -111,6 +111,10 @@ def make_kit_permanent(kit: ProductKit) -> bool:
|
|||||||
kit.is_temporary = False
|
kit.is_temporary = False
|
||||||
kit.order = None # Отвязываем от заказа
|
kit.order = None # Отвязываем от заказа
|
||||||
kit.save()
|
kit.save()
|
||||||
|
|
||||||
|
# Очищаем зафиксированные цены - теперь будет использоваться актуальная цена товаров
|
||||||
|
kit.kit_items.update(unit_price=None)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ class UnitOfMeasureService:
|
|||||||
{'code': 'банч', 'name': 'Банч', 'short_name': 'банч', 'position': 10},
|
{'code': 'банч', 'name': 'Банч', 'short_name': 'банч', 'position': 10},
|
||||||
{'code': 'ветка', 'name': 'Ветка', 'short_name': 'вет.', 'position': 11},
|
{'code': 'ветка', 'name': 'Ветка', 'short_name': 'вет.', 'position': 11},
|
||||||
{'code': 'пучок', 'name': 'Пучок', 'short_name': 'пуч.', 'position': 12},
|
{'code': 'пучок', 'name': 'Пучок', 'short_name': 'пуч.', 'position': 12},
|
||||||
|
{'code': 'коробка', 'name': 'Коробка', 'short_name': 'кор.', 'position': 13},
|
||||||
]
|
]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
|
|||||||
@@ -207,6 +207,18 @@
|
|||||||
self._toggleProduct(productId);
|
self._toggleProduct(productId);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Двойной клик по товару - сразу добавляет в документ
|
||||||
|
this.elements.grid.addEventListener('dblclick', function(e) {
|
||||||
|
var productCard = e.target.closest('.product-picker-item');
|
||||||
|
if (productCard && self.options.onAddSelected) {
|
||||||
|
var productId = productCard.dataset.productId;
|
||||||
|
var product = self._findProductById(productId);
|
||||||
|
if (product) {
|
||||||
|
self.options.onAddSelected(product, self);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Добавить выбранный
|
// Добавить выбранный
|
||||||
@@ -435,17 +447,7 @@
|
|||||||
*/
|
*/
|
||||||
ProductSearchPicker.prototype._toggleProduct = function(productId) {
|
ProductSearchPicker.prototype._toggleProduct = function(productId) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var product = null;
|
var product = this._findProductById(productId);
|
||||||
|
|
||||||
// Находим товар в списке
|
|
||||||
for (var i = 0; i < this.state.products.length; i++) {
|
|
||||||
var p = this.state.products[i];
|
|
||||||
if (String(p.id).replace('product_', '') === productId) {
|
|
||||||
product = p;
|
|
||||||
product.id = productId; // Сохраняем очищенный ID
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!product) return;
|
if (!product) return;
|
||||||
|
|
||||||
@@ -473,6 +475,21 @@
|
|||||||
this._updateSelectionUI();
|
this._updateSelectionUI();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Поиск товара по ID в загруженном списке
|
||||||
|
*/
|
||||||
|
ProductSearchPicker.prototype._findProductById = function(productId) {
|
||||||
|
for (var i = 0; i < this.state.products.length; i++) {
|
||||||
|
var p = this.state.products[i];
|
||||||
|
if (String(p.id).replace('product_', '') === productId) {
|
||||||
|
var product = Object.assign({}, p);
|
||||||
|
product.id = productId; // Сохраняем очищенный ID
|
||||||
|
return product;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Принудительно снять выделение со всех товаров
|
* Принудительно снять выделение со всех товаров
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -65,7 +65,7 @@
|
|||||||
|
|
||||||
{% elif item.item_type == 'kit' %}
|
{% elif item.item_type == 'kit' %}
|
||||||
<span style="display: inline-block; width: 24px; margin-right: 8px;"></span>
|
<span style="display: inline-block; width: 24px; margin-right: 8px;"></span>
|
||||||
<a href="{% url 'products:kit-detail' item.pk %}"
|
<a href="{% url 'products:productkit-detail' item.pk %}"
|
||||||
style="color: #6c757d;">{{ item.name }}</a>
|
style="color: #6c757d;">{{ item.name }}</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
@@ -100,7 +100,7 @@
|
|||||||
{% elif item.item_type == 'product' %}
|
{% elif item.item_type == 'product' %}
|
||||||
<a href="{% url 'products:product-update' item.pk %}" class="btn btn-sm btn-outline-primary">Изменить</a>
|
<a href="{% url 'products:product-update' item.pk %}" class="btn btn-sm btn-outline-primary">Изменить</a>
|
||||||
{% elif item.item_type == 'kit' %}
|
{% elif item.item_type == 'kit' %}
|
||||||
<a href="{% url 'products:kit-update' item.pk %}" class="btn btn-sm btn-outline-primary">Изменить</a>
|
<a href="{% url 'products:productkit-update' item.pk %}" class="btn btn-sm btn-outline-primary">Изменить</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -48,27 +48,27 @@ ProductSearchPicker.init('#writeoff-products', {
|
|||||||
{% if skip_stock_filter %}data-skip-stock-filter="true"{% endif %}>
|
{% if skip_stock_filter %}data-skip-stock-filter="true"{% endif %}>
|
||||||
|
|
||||||
<div class="card shadow-sm">
|
<div class="card shadow-sm">
|
||||||
<!-- Строка поиска -->
|
<!-- Строка поиска - компактный размер -->
|
||||||
<div class="card-header bg-white py-3">
|
<div class="card-header bg-white py-1">
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text bg-light border-end-0">
|
<span class="input-group-text bg-light border-end-0">
|
||||||
<i class="bi bi-search text-primary"></i>
|
<i class="bi bi-search text-primary"></i>
|
||||||
</span>
|
</span>
|
||||||
<input type="text"
|
<input type="text"
|
||||||
class="form-control form-control-lg border-start-0 product-picker-search"
|
class="form-control form-control-sm border-start-0 product-picker-search"
|
||||||
placeholder="{{ title|default:'Поиск товара по названию, артикулу...' }}"
|
placeholder="{{ title|default:'Поиск товара по названию, артикулу...' }}"
|
||||||
style="box-shadow: none;">
|
style="box-shadow: none;">
|
||||||
<button class="btn btn-outline-secondary product-picker-search-clear"
|
<button class="btn btn-outline-secondary btn-sm product-picker-search-clear"
|
||||||
type="button" style="display: none;">
|
type="button" style="display: none;">
|
||||||
<i class="bi bi-x-lg"></i>
|
<i class="bi bi-x"></i>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% if show_filters|default:True %}
|
{% if show_filters|default:True %}
|
||||||
<!-- Фильтры -->
|
<!-- Фильтры - компактный вид -->
|
||||||
<div class="card-body border-bottom py-2">
|
<div class="card-body border-bottom py-1">
|
||||||
<div class="d-flex gap-2 align-items-center flex-wrap">
|
<div class="d-flex gap-1 align-items-center flex-wrap">
|
||||||
{% if categories %}
|
{% if categories %}
|
||||||
<!-- Фильтр по категории -->
|
<!-- Фильтр по категории -->
|
||||||
<select class="form-select form-select-sm product-picker-category" style="width: auto;">
|
<select class="form-select form-select-sm product-picker-category" style="width: auto;">
|
||||||
@@ -113,29 +113,29 @@ ProductSearchPicker.init('#writeoff-products', {
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<!-- Контент: сетка/список товаров -->
|
<!-- Контент: сетка/список товаров - компактный -->
|
||||||
<div class="card-body product-picker-content" style="max-height: {{ content_height|default:'400px' }}; overflow-y: auto;">
|
<div class="card-body product-picker-content p-1" style="max-height: {{ content_height|default:'400px' }}; overflow-y: auto;">
|
||||||
<!-- Индикатор загрузки -->
|
<!-- Индикатор загрузки -->
|
||||||
<div class="product-picker-loading text-center py-4" style="display: none;">
|
<div class="product-picker-loading text-center py-2" style="display: none;">
|
||||||
<div class="spinner-border text-primary" role="status">
|
<div class="spinner-border spinner-border-sm text-primary" role="status">
|
||||||
<span class="visually-hidden">Загрузка...</span>
|
<span class="visually-hidden">Загрузка...</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Сетка товаров -->
|
<!-- Сетка товаров -->
|
||||||
<div class="row g-2 product-picker-grid" data-view="{{ initial_view|default:'list' }}">
|
<div class="row g-1 product-picker-grid" data-view="{{ initial_view|default:'list' }}">
|
||||||
<!-- Товары загружаются через AJAX -->
|
<!-- Товары загружаются через AJAX -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Пустой результат -->
|
<!-- Пустой результат -->
|
||||||
<div class="product-picker-empty text-center py-4 text-muted" style="display: none;">
|
<div class="product-picker-empty text-center py-2 text-muted" style="display: none;">
|
||||||
<i class="bi bi-search fs-1 opacity-25"></i>
|
<i class="bi bi-search fs-5 opacity-25"></i>
|
||||||
<p class="mb-0 mt-2">Товары не найдены</p>
|
<p class="mb-0 mt-1 small">Товары не найдены</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Футер с кнопкой действия -->
|
<!-- Футер с кнопкой действия - компактный -->
|
||||||
<div class="card-footer bg-white py-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
|
<div class="card-footer bg-white py-1 d-flex justify-content-between align-items-center flex-wrap gap-1">
|
||||||
<div></div>
|
<div></div>
|
||||||
|
|
||||||
<button class="btn btn-primary btn-sm product-picker-add-selected" disabled>
|
<button class="btn btn-primary btn-sm product-picker-add-selected" disabled>
|
||||||
|
|||||||
@@ -8,25 +8,33 @@
|
|||||||
|
|
||||||
<div id="kititem-forms">
|
<div id="kititem-forms">
|
||||||
{% for kititem_form in kititem_formset %}
|
{% for kititem_form in kititem_formset %}
|
||||||
<div class="card mb-2 kititem-form border"
|
<div class="card mb-2 kititem-form border" data-form-index="{{ forloop.counter0 }}"
|
||||||
data-form-index="{{ forloop.counter0 }}"
|
data-product-id="{% if kititem_form.instance.product %}{{ kititem_form.instance.product.id }}{% endif %}"
|
||||||
data-product-id="{% if kititem_form.instance.product %}{{ kititem_form.instance.product.id }}{% endif %}"
|
data-product-price="{% if kititem_form.instance.product %}{{ kititem_form.instance.product.actual_price|default:0 }}{% else %}0{% endif %}">
|
||||||
data-product-price="{% if kititem_form.instance.product %}{{ kititem_form.instance.product.actual_price|default:0 }}{% else %}0{% endif %}">
|
|
||||||
{{ kititem_form.id }}
|
{{ kititem_form.id }}
|
||||||
<div class="card-body p-2">
|
<div class="card-body p-2">
|
||||||
{% if kititem_form.non_field_errors %}
|
{% if kititem_form.non_field_errors %}
|
||||||
<div class="alert alert-danger alert-sm mb-2">
|
<div class="alert alert-danger alert-sm mb-2">
|
||||||
{% for error in kititem_form.non_field_errors %}{{ error }}{% endfor %}
|
{% for error in kititem_form.non_field_errors %}{{ error }}{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<div class="row g-2 align-items-end">
|
<div class="row g-2 align-items-end">
|
||||||
<!-- ТОВАР -->
|
<!-- ТОВАР -->
|
||||||
<div class="col-md-4">
|
<div class="col-md-3">
|
||||||
<label class="form-label small text-muted mb-1">Товар</label>
|
<label class="form-label small text-muted mb-1">Товар</label>
|
||||||
{{ kititem_form.product }}
|
{{ kititem_form.product }}
|
||||||
{% if kititem_form.product.errors %}
|
{% if kititem_form.product.errors %}
|
||||||
<div class="text-danger small">{{ kititem_form.product.errors }}</div>
|
<div class="text-danger small">{{ kititem_form.product.errors }}</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ЕДИНИЦА ПРОДАЖИ -->
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label class="form-label small text-muted mb-1">Единица продажи</label>
|
||||||
|
{{ kititem_form.sales_unit }}
|
||||||
|
{% if kititem_form.sales_unit.errors %}
|
||||||
|
<div class="text-danger small">{{ kititem_form.sales_unit.errors }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -34,19 +42,18 @@
|
|||||||
<div class="col-md-1 d-flex justify-content-center align-items-center">
|
<div class="col-md-1 d-flex justify-content-center align-items-center">
|
||||||
<div class="kit-item-separator">
|
<div class="kit-item-separator">
|
||||||
<span class="separator-text">ИЛИ</span>
|
<span class="separator-text">ИЛИ</span>
|
||||||
<i class="bi bi-info-circle separator-help"
|
<i class="bi bi-info-circle separator-help" data-bs-toggle="tooltip"
|
||||||
data-bs-toggle="tooltip"
|
data-bs-placement="top"
|
||||||
data-bs-placement="top"
|
title="Вы можете выбрать что-то одно: либо товар, либо группу вариантов"></i>
|
||||||
title="Вы можете выбрать что-то одно: либо товар, либо группу вариантов"></i>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ГРУППА ВАРИАНТОВ -->
|
<!-- ГРУППА ВАРИАНТОВ -->
|
||||||
<div class="col-md-4">
|
<div class="col-md-3">
|
||||||
<label class="form-label small text-muted mb-1">Группа вариантов</label>
|
<label class="form-label small text-muted mb-1">Группа вариантов</label>
|
||||||
{{ kititem_form.variant_group }}
|
{{ kititem_form.variant_group }}
|
||||||
{% if kititem_form.variant_group.errors %}
|
{% if kititem_form.variant_group.errors %}
|
||||||
<div class="text-danger small">{{ kititem_form.variant_group.errors }}</div>
|
<div class="text-danger small">{{ kititem_form.variant_group.errors }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -55,17 +62,19 @@
|
|||||||
<label class="form-label small text-muted mb-1">Кол-во</label>
|
<label class="form-label small text-muted mb-1">Кол-во</label>
|
||||||
{{ kititem_form.quantity|smart_quantity }}
|
{{ kititem_form.quantity|smart_quantity }}
|
||||||
{% if kititem_form.quantity.errors %}
|
{% if kititem_form.quantity.errors %}
|
||||||
<div class="text-danger small">{{ kititem_form.quantity.errors }}</div>
|
<div class="text-danger small">{{ kititem_form.quantity.errors }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- УДАЛЕНИЕ -->
|
<!-- УДАЛЕНИЕ -->
|
||||||
<div class="col-md-1 text-end">
|
<div class="col-md-1 text-end">
|
||||||
{% if kititem_form.DELETE %}
|
{% if kititem_form.DELETE %}
|
||||||
<button type="button" class="btn btn-sm btn-link text-danger p-0" onclick="this.nextElementSibling.checked = true; this.closest('.kititem-form').style.display='none'; if(typeof calculateFinalPrice === 'function') calculateFinalPrice();" title="Удалить">
|
<button type="button" class="btn btn-sm btn-link text-danger p-0"
|
||||||
<i class="bi bi-x-lg"></i>
|
onclick="this.nextElementSibling.checked = true; this.closest('.kititem-form').style.display='none'; if(typeof calculateFinalPrice === 'function') calculateFinalPrice();"
|
||||||
</button>
|
title="Удалить">
|
||||||
{{ kititem_form.DELETE }}
|
<i class="bi bi-x-lg"></i>
|
||||||
|
</button>
|
||||||
|
{{ kititem_form.DELETE }}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -38,7 +38,7 @@
|
|||||||
/**
|
/**
|
||||||
* Инициализирует Select2 для элемента с AJAX поиском товаров
|
* Инициализирует Select2 для элемента с AJAX поиском товаров
|
||||||
* @param {Element} element - DOM элемент select
|
* @param {Element} element - DOM элемент select
|
||||||
* @param {string} type - Тип поиска ('product' или 'variant')
|
* @param {string} type - Тип поиска ('product', 'variant' или 'sales_unit')
|
||||||
* @param {string} apiUrl - URL API для поиска
|
* @param {string} apiUrl - URL API для поиска
|
||||||
* @returns {boolean} - true если инициализация прошла успешно, false иначе
|
* @returns {boolean} - true если инициализация прошла успешно, false иначе
|
||||||
*/
|
*/
|
||||||
@@ -70,60 +70,92 @@
|
|||||||
|
|
||||||
var placeholders = {
|
var placeholders = {
|
||||||
'product': 'Начните вводить название товара...',
|
'product': 'Начните вводить название товара...',
|
||||||
'variant': 'Начните вводить название группы...'
|
'variant': 'Начните вводить название группы...',
|
||||||
|
'sales_unit': 'Выберите единицу продажи...'
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
// Для единиц продажи используем другой подход - не AJAX, а загрузка при выборе товара
|
||||||
$element.select2({
|
if (type === 'sales_unit') {
|
||||||
theme: 'bootstrap-5',
|
try {
|
||||||
placeholder: placeholders[type] || 'Выберите...',
|
$element.select2({
|
||||||
allowClear: true,
|
theme: 'bootstrap-5',
|
||||||
width: '100%',
|
placeholder: placeholders[type] || 'Выберите...',
|
||||||
language: 'ru',
|
allowClear: true,
|
||||||
minimumInputLength: 0,
|
width: '100%',
|
||||||
dropdownAutoWidth: false,
|
language: 'ru',
|
||||||
ajax: {
|
minimumInputLength: 0,
|
||||||
url: apiUrl,
|
dropdownAutoWidth: false,
|
||||||
dataType: 'json',
|
// Для единиц продажи не используем AJAX, т.к. они загружаются при выборе товара
|
||||||
delay: 250,
|
disabled: true, // Изначально отключен до выбора товара
|
||||||
data: function (params) {
|
templateResult: formatSelectResult,
|
||||||
return {
|
templateSelection: formatSelectSelection
|
||||||
q: params.term || '',
|
});
|
||||||
type: type,
|
console.log('initProductSelect2: successfully initialized sales_unit for', element.name);
|
||||||
page: params.page || 1
|
return true;
|
||||||
};
|
} catch (error) {
|
||||||
|
console.error('initProductSelect2: initialization error for sales_unit', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Для товаров и вариантов используем AJAX
|
||||||
|
try {
|
||||||
|
$element.select2({
|
||||||
|
theme: 'bootstrap-5',
|
||||||
|
placeholder: placeholders[type] || 'Выберите...',
|
||||||
|
allowClear: true,
|
||||||
|
width: '100%',
|
||||||
|
language: 'ru',
|
||||||
|
minimumInputLength: 0,
|
||||||
|
dropdownAutoWidth: false,
|
||||||
|
ajax: {
|
||||||
|
url: apiUrl,
|
||||||
|
dataType: 'json',
|
||||||
|
delay: 250,
|
||||||
|
data: function (params) {
|
||||||
|
return {
|
||||||
|
q: params.term || '',
|
||||||
|
type: type,
|
||||||
|
page: params.page || 1
|
||||||
|
};
|
||||||
|
},
|
||||||
|
processResults: function (data) {
|
||||||
|
return {
|
||||||
|
results: data.results,
|
||||||
|
pagination: {
|
||||||
|
more: data.pagination.more
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
cache: true
|
||||||
},
|
},
|
||||||
processResults: function (data) {
|
templateResult: formatSelectResult,
|
||||||
return {
|
templateSelection: formatSelectSelection
|
||||||
results: data.results,
|
});
|
||||||
pagination: {
|
console.log('initProductSelect2: successfully initialized for', element.name);
|
||||||
more: data.pagination.more
|
return true;
|
||||||
}
|
} catch (error) {
|
||||||
};
|
console.error('initProductSelect2: initialization error', error);
|
||||||
},
|
return false;
|
||||||
cache: true
|
}
|
||||||
},
|
|
||||||
templateResult: formatSelectResult,
|
|
||||||
templateSelection: formatSelectSelection
|
|
||||||
});
|
|
||||||
console.log('initProductSelect2: successfully initialized for', element.name);
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('initProductSelect2: initialization error', error);
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Инициализирует Select2 для всех селектов, совпадающих с паттерном
|
* Инициализирует Select2 для всех селектов, совпадающих с паттерном
|
||||||
* @param {string} fieldPattern - Паттерн name атрибута (например: 'items-', 'kititem-')
|
* @param {string} fieldPattern - Паттерн name атрибута (например: 'items-', 'kititem-')
|
||||||
* @param {string} type - Тип поиска ('product' или 'variant')
|
* @param {string} type - Тип поиска ('product', 'variant' или 'sales_unit')
|
||||||
* @param {string} apiUrl - URL API для поиска
|
* @param {string} apiUrl - URL API для поиска
|
||||||
*/
|
*/
|
||||||
window.initAllProductSelect2 = function(fieldPattern, type, apiUrl) {
|
window.initAllProductSelect2 = function(fieldPattern, type, apiUrl) {
|
||||||
document.querySelectorAll('[name*="' + fieldPattern + '"][name*="-product"]').forEach(function(element) {
|
if (type === 'sales_unit') {
|
||||||
window.initProductSelect2(element, type, apiUrl);
|
document.querySelectorAll('[name*="' + fieldPattern + '"][name*="-sales_unit"]').forEach(function(element) {
|
||||||
});
|
window.initProductSelect2(element, type, apiUrl);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
document.querySelectorAll('[name*="' + fieldPattern + '"][name*="-product"]').forEach(function(element) {
|
||||||
|
window.initProductSelect2(element, type, apiUrl);
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -362,6 +362,113 @@
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Комплекты, содержащие этот товар как единицу продажи -->
|
||||||
|
{% if kit_items_using_sales_units %}
|
||||||
|
<div class="card mt-4">
|
||||||
|
<div class="card-header">
|
||||||
|
<h5>Комплекты, содержащие этот товар как единицу продажи</h5>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-sm table-bordered">
|
||||||
|
<thead class="table-light">
|
||||||
|
<tr>
|
||||||
|
<th>Комплект</th>
|
||||||
|
<th>Количество в комплекте</th>
|
||||||
|
<th>Цена за единицу</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for kit_item in kit_items_using_sales_units %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="{% url 'products:productkit-detail' kit_item.kit.pk %}">
|
||||||
|
{{ kit_item.kit.name }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>{{ kit_item.quantity|default:"1" }}</td>
|
||||||
|
<td>{{ kit_item.sales_unit.actual_price|default:"0.00" }} руб.</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- Комплекты, содержащие этот товар напрямую -->
|
||||||
|
{% if kit_items_using_products %}
|
||||||
|
<div class="card mt-4">
|
||||||
|
<div class="card-header">
|
||||||
|
<h5>Комплекты, содержащие этот товар напрямую</h5>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-sm table-bordered">
|
||||||
|
<thead class="table-light">
|
||||||
|
<tr>
|
||||||
|
<th>Комплект</th>
|
||||||
|
<th>Количество в комплекте</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for kit_item in kit_items_using_products %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="{% url 'products:productkit-detail' kit_item.kit.pk %}">
|
||||||
|
{{ kit_item.kit.name }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>{{ kit_item.quantity|default:"1" }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- Комплекты, содержащие этот товар как часть группы вариантов -->
|
||||||
|
{% if variant_group_kit_items %}
|
||||||
|
<div class="card mt-4">
|
||||||
|
<div class="card-header">
|
||||||
|
<h5>Комплекты, содержащие этот товар как часть группы вариантов</h5>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-sm table-bordered">
|
||||||
|
<thead class="table-light">
|
||||||
|
<tr>
|
||||||
|
<th>Комплект</th>
|
||||||
|
<th>Группа вариантов</th>
|
||||||
|
<th>Количество в комплекте</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for variant_group_item in variant_group_kit_items %}
|
||||||
|
{% for kit_item in variant_group_item.variant_group.kit_items.all %}
|
||||||
|
{% if kit_item.product == product %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="{% url 'products:productkit-detail' kit_item.kit.pk %}">
|
||||||
|
{{ kit_item.kit.name }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>{{ variant_group_item.variant_group.name }}</td>
|
||||||
|
<td>{{ kit_item.quantity|default:"1" }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -136,7 +136,13 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<td>{{ forloop.counter }}</td>
|
<td>{{ forloop.counter }}</td>
|
||||||
<td>
|
<td>
|
||||||
{% if item.product %}
|
{% if item.sales_unit %}
|
||||||
|
<a href="{% url 'products:product-detail' item.sales_unit.product.pk %}">
|
||||||
|
{{ item.sales_unit.name }}
|
||||||
|
</a>
|
||||||
|
<br>
|
||||||
|
<small class="text-muted">Единица продажи: {{ item.sales_unit.product.name }}</small>
|
||||||
|
{% elif item.product %}
|
||||||
<a href="{% url 'products:product-detail' item.product.pk %}">
|
<a href="{% url 'products:product-detail' item.product.pk %}">
|
||||||
{{ item.product.name }}
|
{{ item.product.name }}
|
||||||
</a>
|
</a>
|
||||||
@@ -149,7 +155,9 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
{% if item.product %}
|
{% if item.sales_unit %}
|
||||||
|
<span class="badge bg-info">Единица продажи</span>
|
||||||
|
{% elif item.product %}
|
||||||
<span class="badge bg-success">Товар</span>
|
<span class="badge bg-success">Товар</span>
|
||||||
{% else %}
|
{% else %}
|
||||||
<span class="badge bg-primary">Варианты</span>
|
<span class="badge bg-primary">Варианты</span>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -26,8 +26,13 @@
|
|||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_name" class="form-label">Название *</label>
|
<label for="{{ form.name.id_for_label }}" class="form-label">Название *</label>
|
||||||
{{ form.name }}
|
<input type="text"
|
||||||
|
name="{{ form.name.html_name }}"
|
||||||
|
class="form-control{% if form.name.errors %} is-invalid{% endif %}"
|
||||||
|
id="{{ form.name.id_for_label }}"
|
||||||
|
value="{{ form.name.value|default:'' }}"
|
||||||
|
required>
|
||||||
{% if form.name.errors %}
|
{% if form.name.errors %}
|
||||||
<div class="invalid-feedback d-block">
|
<div class="invalid-feedback d-block">
|
||||||
{{ form.name.errors }}
|
{{ form.name.errors }}
|
||||||
@@ -36,8 +41,11 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_description" class="form-label">Описание</label>
|
<label for="{{ form.description.id_for_label }}" class="form-label">Описание</label>
|
||||||
{{ form.description }}
|
<textarea name="{{ form.description.html_name }}"
|
||||||
|
class="form-control{% if form.description.errors %} is-invalid{% endif %}"
|
||||||
|
id="{{ form.description.id_for_label }}"
|
||||||
|
rows="3">{{ form.description.value|default:'' }}</textarea>
|
||||||
{% if form.description.errors %}
|
{% if form.description.errors %}
|
||||||
<div class="invalid-feedback d-block">
|
<div class="invalid-feedback d-block">
|
||||||
{{ form.description.errors }}
|
{{ form.description.errors }}
|
||||||
@@ -46,8 +54,18 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_categories" class="form-label">Категории</label>
|
<label for="{{ form.categories.id_for_label }}" class="form-label">Категории</label>
|
||||||
{{ form.categories }}
|
<select name="{{ form.categories.html_name }}"
|
||||||
|
class="form-select{% if form.categories.errors %} is-invalid{% endif %}"
|
||||||
|
id="{{ form.categories.id_for_label }}"
|
||||||
|
multiple>
|
||||||
|
{% for value, label in form.categories.field.choices %}
|
||||||
|
<option value="{{ value }}"
|
||||||
|
{% if value in form.categories.value %}selected{% endif %}>
|
||||||
|
{{ label }}
|
||||||
|
</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
{% if form.categories.errors %}
|
{% if form.categories.errors %}
|
||||||
<div class="invalid-feedback d-block">
|
<div class="invalid-feedback d-block">
|
||||||
{{ form.categories.errors }}
|
{{ form.categories.errors }}
|
||||||
@@ -59,8 +77,18 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_tags" class="form-label">Теги</label>
|
<label for="{{ form.tags.id_for_label }}" class="form-label">Теги</label>
|
||||||
{{ form.tags }}
|
<select name="{{ form.tags.html_name }}"
|
||||||
|
class="form-select{% if form.tags.errors %} is-invalid{% endif %}"
|
||||||
|
id="{{ form.tags.id_for_label }}"
|
||||||
|
multiple>
|
||||||
|
{% for value, label in form.tags.field.choices %}
|
||||||
|
<option value="{{ value }}"
|
||||||
|
{% if value in form.tags.value %}selected{% endif %}>
|
||||||
|
{{ label }}
|
||||||
|
</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
{% if form.tags.errors %}
|
{% if form.tags.errors %}
|
||||||
<div class="invalid-feedback d-block">
|
<div class="invalid-feedback d-block">
|
||||||
{{ form.tags.errors }}
|
{{ form.tags.errors }}
|
||||||
@@ -69,8 +97,14 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="id_sale_price" class="form-label">Цена со скидкой</label>
|
<label for="{{ form.sale_price.id_for_label }}" class="form-label">Цена со скидкой</label>
|
||||||
{{ form.sale_price }}
|
<input type="number"
|
||||||
|
name="{{ form.sale_price.html_name }}"
|
||||||
|
class="form-control{% if form.sale_price.errors %} is-invalid{% endif %}"
|
||||||
|
id="{{ form.sale_price.id_for_label }}"
|
||||||
|
value="{{ form.sale_price.value|default:'' }}"
|
||||||
|
step="0.01"
|
||||||
|
min="0">
|
||||||
{% if form.sale_price.errors %}
|
{% if form.sale_price.errors %}
|
||||||
<div class="invalid-feedback d-block">
|
<div class="invalid-feedback d-block">
|
||||||
{{ form.sale_price.errors }}
|
{{ form.sale_price.errors }}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<div class="container-fluid mt-4">
|
<div class="container-fluid mt-4">
|
||||||
<h2 class="mb-4">
|
<h2 class="mb-4">
|
||||||
<i class="bi bi-box-seam"></i> Товары иi они все комплекты
|
<i class="bi bi-box-seam"></i> Товары и комплекты
|
||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
<!-- Панель фильтрации и действий -->
|
<!-- Панель фильтрации и действий -->
|
||||||
|
|||||||
@@ -97,7 +97,7 @@
|
|||||||
<a href="{% url 'products:unit-list' %}" class="btn btn-outline-secondary">
|
<a href="{% url 'products:unit-list' %}" class="btn btn-outline-secondary">
|
||||||
Отмена
|
Отмена
|
||||||
</a>
|
</a>
|
||||||
<button type="submit" class="btn btn-primary">
|
<button type="submit" name="submit" class="btn btn-primary">
|
||||||
<i class="bi bi-check-lg"></i> {{ submit_text }}
|
<i class="bi bi-check-lg"></i> {{ submit_text }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
290
myproject/products/tests/test_ai_bouquet_names.py
Normal file
290
myproject/products/tests/test_ai_bouquet_names.py
Normal file
@@ -0,0 +1,290 @@
|
|||||||
|
from django_tenants.test.cases import TenantTestCase
|
||||||
|
from products.services import BouquetNameGenerator
|
||||||
|
from products.models import BouquetName, ProductTag
|
||||||
|
from unittest.mock import patch, MagicMock
|
||||||
|
|
||||||
|
|
||||||
|
class BouquetNameGeneratorTestCase(TenantTestCase):
|
||||||
|
"""
|
||||||
|
Тесты для сервиса генерации названий букетов
|
||||||
|
"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
"""
|
||||||
|
Создаем экземпляр сервиса для тестирования
|
||||||
|
"""
|
||||||
|
self.generator = BouquetNameGenerator()
|
||||||
|
|
||||||
|
@patch('products.services.ai.bouquet_names.BouquetNameGenerator.get_glm_service')
|
||||||
|
def test_generate_with_mock_glm(self, mock_get_glm_service):
|
||||||
|
"""
|
||||||
|
Тест генерации названий с мок-объектом GLM сервиса
|
||||||
|
"""
|
||||||
|
# Создаем мок-объект сервиса
|
||||||
|
mock_service = MagicMock()
|
||||||
|
mock_service.generate_text.return_value = (
|
||||||
|
True,
|
||||||
|
"Текст успешно сгенерирован",
|
||||||
|
{
|
||||||
|
'generated_text': (
|
||||||
|
"1. Розавая мечта\n"
|
||||||
|
"2. Лиловые настроения\n"
|
||||||
|
"3. Яркий букет для дня рождения\n"
|
||||||
|
"4. Сладкий сюрприз\n"
|
||||||
|
"5. Романтическое вдохновение"
|
||||||
|
),
|
||||||
|
'model': 'glm-4',
|
||||||
|
'usage': {'prompt_tokens': 100, 'completion_tokens': 50}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
mock_get_glm_service.return_value = mock_service
|
||||||
|
|
||||||
|
# Вызываем метод генерации
|
||||||
|
success, msg, data = self.generator.generate(count=5)
|
||||||
|
|
||||||
|
# Проверки
|
||||||
|
self.assertTrue(success)
|
||||||
|
self.assertIn("Сгенерировано 5 названий для букетов", msg)
|
||||||
|
self.assertIsNotNone(data)
|
||||||
|
self.assertIn('names', data)
|
||||||
|
self.assertEqual(len(data['names']), 5)
|
||||||
|
self.assertEqual(data['model'], 'glm-4')
|
||||||
|
self.assertIn('usage', data)
|
||||||
|
|
||||||
|
# Проверяем, что названия содержат нужные слова
|
||||||
|
expected_names = [
|
||||||
|
"Розавая мечта",
|
||||||
|
"Лиловые настроения",
|
||||||
|
"Яркий букет для дня рождения",
|
||||||
|
"Сладкий сюрприз",
|
||||||
|
"Романтическое вдохновение"
|
||||||
|
]
|
||||||
|
self.assertEqual(data['names'], expected_names)
|
||||||
|
|
||||||
|
@patch('products.services.ai.bouquet_names.BouquetNameGenerator.get_glm_service')
|
||||||
|
@patch('products.services.ai.bouquet_names.BouquetNameGenerator.get_openrouter_service')
|
||||||
|
def test_no_active_integration(self, mock_get_openrouter, mock_get_glm):
|
||||||
|
"""
|
||||||
|
Тест случая, когда нет активных интеграций
|
||||||
|
"""
|
||||||
|
mock_get_glm.return_value = None
|
||||||
|
mock_get_openrouter.return_value = None
|
||||||
|
|
||||||
|
success, msg, data = self.generator.generate(count=10)
|
||||||
|
|
||||||
|
self.assertFalse(success)
|
||||||
|
self.assertEqual(msg, "Нет активных AI-интеграций")
|
||||||
|
self.assertIsNone(data)
|
||||||
|
|
||||||
|
@patch('products.services.ai.bouquet_names.BouquetNameGenerator.get_glm_service')
|
||||||
|
def test_generate_with_characteristics(self, mock_get_glm_service):
|
||||||
|
"""
|
||||||
|
Тест генерации с характеристиками
|
||||||
|
"""
|
||||||
|
# Создаем мок-объект сервиса
|
||||||
|
mock_service = MagicMock()
|
||||||
|
mock_service.generate_text.return_value = (
|
||||||
|
True,
|
||||||
|
"Текст успешно сгенерирован",
|
||||||
|
{
|
||||||
|
'generated_text': (
|
||||||
|
"1. Ромашковое небо\n"
|
||||||
|
"2. Лавандовый спокойствие\n"
|
||||||
|
"3. Свежие ароматы\n"
|
||||||
|
"4. Милая композиция\n"
|
||||||
|
"5. Нежный букет"
|
||||||
|
),
|
||||||
|
'model': 'glm-4',
|
||||||
|
'usage': {'prompt_tokens': 120, 'completion_tokens': 45}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
mock_get_glm_service.return_value = mock_service
|
||||||
|
|
||||||
|
success, msg, data = self.generator.generate(
|
||||||
|
count=5,
|
||||||
|
characteristics="ромашки, лаванда, свежие",
|
||||||
|
occasion="день матери"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(success)
|
||||||
|
self.assertIn("Сгенерировано 5 названий для букетов", msg)
|
||||||
|
self.assertEqual(len(data['names']), 5)
|
||||||
|
# Проверяем, что сервис был вызван с нужными параметрами
|
||||||
|
mock_service.generate_text.assert_called_once()
|
||||||
|
|
||||||
|
def test_parse_response_with_markdown(self):
|
||||||
|
"""
|
||||||
|
Тест парсинга ответа с Markdown форматированием
|
||||||
|
"""
|
||||||
|
response_text = """
|
||||||
|
Here are 3 beautiful bouquet names for you:
|
||||||
|
|
||||||
|
1. **Spring Blossom Delight**
|
||||||
|
2. *Romantic Rose Elegance*
|
||||||
|
3. "Sunny Daisy Joy"
|
||||||
|
|
||||||
|
I hope you love these!
|
||||||
|
"""
|
||||||
|
|
||||||
|
names = self.generator._parse_response(response_text)
|
||||||
|
self.assertEqual(len(names), 3)
|
||||||
|
self.assertEqual(names[0], "Spring Blossom Delight")
|
||||||
|
self.assertEqual(names[1], "Romantic Rose Elegance")
|
||||||
|
self.assertEqual(names[2], "Sunny Daisy Joy")
|
||||||
|
|
||||||
|
def test_parse_response_with_duplicates(self):
|
||||||
|
"""
|
||||||
|
Тест парсинга ответа с дубликатами
|
||||||
|
"""
|
||||||
|
response_text = """
|
||||||
|
1. Розавая мечта
|
||||||
|
2. Лиловые настроения
|
||||||
|
3. Розавая мечта
|
||||||
|
4. Сладкий сюрприз
|
||||||
|
5. Лиловые настроения
|
||||||
|
"""
|
||||||
|
|
||||||
|
names = self.generator._parse_response(response_text)
|
||||||
|
self.assertEqual(len(names), 3)
|
||||||
|
self.assertIn("Розавая мечта", names)
|
||||||
|
self.assertIn("Лиловые настроения", names)
|
||||||
|
self.assertIn("Сладкий сюрприз", names)
|
||||||
|
|
||||||
|
def test_parse_response_empty(self):
|
||||||
|
"""
|
||||||
|
Тест парсинга пустого ответа
|
||||||
|
"""
|
||||||
|
response_text = """
|
||||||
|
"""
|
||||||
|
names = self.generator._parse_response(response_text)
|
||||||
|
self.assertEqual(len(names), 0)
|
||||||
|
|
||||||
|
def test_parse_response_no_names(self):
|
||||||
|
"""
|
||||||
|
Тест парсинга ответа без названий
|
||||||
|
"""
|
||||||
|
response_text = """
|
||||||
|
I'm sorry, but I can't help with that right now.
|
||||||
|
"""
|
||||||
|
names = self.generator._parse_response(response_text)
|
||||||
|
self.assertEqual(len(names), 0)
|
||||||
|
|
||||||
|
@patch('products.services.ai.bouquet_names.BouquetNameGenerator.get_glm_service')
|
||||||
|
def test_generate_and_store(self, mock_get_glm_service):
|
||||||
|
"""
|
||||||
|
Тест генерации и сохранения названий в базе данных
|
||||||
|
"""
|
||||||
|
# Создаем мок-объект сервиса
|
||||||
|
mock_service = MagicMock()
|
||||||
|
mock_service.generate_text.return_value = (
|
||||||
|
True,
|
||||||
|
"Текст успешно сгенерирован",
|
||||||
|
{
|
||||||
|
'generated_text': (
|
||||||
|
"1. Розавая мечта\n"
|
||||||
|
"2. Лиловые настроения\n"
|
||||||
|
"3. Яркий букет для дня рождения"
|
||||||
|
),
|
||||||
|
'model': 'glm-4',
|
||||||
|
'usage': {'prompt_tokens': 100, 'completion_tokens': 50}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
mock_get_glm_service.return_value = mock_service
|
||||||
|
|
||||||
|
# Очищаем базу перед тестом
|
||||||
|
BouquetName.objects.all().delete()
|
||||||
|
|
||||||
|
# Вызываем метод генерации и сохранения
|
||||||
|
success, msg, data = self.generator.generate_and_store(count=3)
|
||||||
|
|
||||||
|
self.assertTrue(success)
|
||||||
|
self.assertIn("Сгенерировано и сохранено 3 названий для букетов", msg)
|
||||||
|
self.assertEqual(BouquetName.objects.count(), 3)
|
||||||
|
|
||||||
|
def test_mark_as_used(self):
|
||||||
|
"""
|
||||||
|
Тест увеличения счетчика использования названия
|
||||||
|
"""
|
||||||
|
# Создаем тестовое название
|
||||||
|
bouquet_name = BouquetName.objects.create(
|
||||||
|
name="Тестовый букет",
|
||||||
|
language="russian",
|
||||||
|
is_approved=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Проверяем начальное значение счетчика
|
||||||
|
self.assertEqual(bouquet_name.usage_count, 0)
|
||||||
|
|
||||||
|
# Увеличиваем счетчик
|
||||||
|
self.generator.mark_as_used("Тестовый букет", "russian")
|
||||||
|
|
||||||
|
# Проверяем обновленное значение
|
||||||
|
bouquet_name.refresh_from_db()
|
||||||
|
self.assertEqual(bouquet_name.usage_count, 1)
|
||||||
|
|
||||||
|
def test_get_approved_names(self):
|
||||||
|
"""
|
||||||
|
Тест получения одобренных названий
|
||||||
|
"""
|
||||||
|
# Очищаем базу перед тестом
|
||||||
|
BouquetName.objects.all().delete()
|
||||||
|
|
||||||
|
# Создаем тестовые данные
|
||||||
|
BouquetName.objects.create(
|
||||||
|
name="Одобренный букет 1",
|
||||||
|
language="russian",
|
||||||
|
is_approved=True
|
||||||
|
)
|
||||||
|
BouquetName.objects.create(
|
||||||
|
name="Одобренный букет 2",
|
||||||
|
language="russian",
|
||||||
|
is_approved=True
|
||||||
|
)
|
||||||
|
BouquetName.objects.create(
|
||||||
|
name="Неодобренный букет",
|
||||||
|
language="russian",
|
||||||
|
is_approved=False
|
||||||
|
)
|
||||||
|
|
||||||
|
# Получаем одобренные названия
|
||||||
|
approved_names = self.generator.get_approved_names(language="russian")
|
||||||
|
|
||||||
|
self.assertEqual(len(approved_names), 2)
|
||||||
|
self.assertIn("Одобренный букет 1", approved_names)
|
||||||
|
self.assertIn("Одобренный букет 2", approved_names)
|
||||||
|
self.assertNotIn("Неодобренный букет", approved_names)
|
||||||
|
|
||||||
|
def test_bouquet_name_model(self):
|
||||||
|
"""
|
||||||
|
Тест создания и работы с моделью BouquetName
|
||||||
|
"""
|
||||||
|
# Создаем тестовые теги
|
||||||
|
red_tag = ProductTag.objects.create(name="красный", slug="krasny")
|
||||||
|
romantic_tag = ProductTag.objects.create(name="романтический", slug="romanticheskiy")
|
||||||
|
|
||||||
|
# Создаем экземпляр модели
|
||||||
|
bouquet_name = BouquetName.objects.create(
|
||||||
|
name="Романтический букет",
|
||||||
|
language="russian",
|
||||||
|
is_approved=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Добавляем теги
|
||||||
|
bouquet_name.color_tags.add(red_tag)
|
||||||
|
bouquet_name.style_tags.add(romantic_tag)
|
||||||
|
|
||||||
|
# Проверяем сохраненные значения
|
||||||
|
self.assertEqual(bouquet_name.name, "Романтический букет")
|
||||||
|
self.assertEqual(bouquet_name.language, "russian")
|
||||||
|
self.assertTrue(bouquet_name.is_approved)
|
||||||
|
self.assertEqual(bouquet_name.usage_count, 0)
|
||||||
|
self.assertIn(red_tag, bouquet_name.color_tags.all())
|
||||||
|
self.assertIn(romantic_tag, bouquet_name.style_tags.all())
|
||||||
|
|
||||||
|
# Обновляем поле
|
||||||
|
bouquet_name.usage_count = 5
|
||||||
|
bouquet_name.save()
|
||||||
|
|
||||||
|
# Проверяем обновление
|
||||||
|
updated_name = BouquetName.objects.get(id=bouquet_name.id)
|
||||||
|
self.assertEqual(updated_name.usage_count, 5)
|
||||||
@@ -42,6 +42,7 @@ urlpatterns = [
|
|||||||
path('kit/photo/<int:pk>/set-main/', views.productkit_photo_set_main, name='productkit-photo-set-main'),
|
path('kit/photo/<int:pk>/set-main/', views.productkit_photo_set_main, name='productkit-photo-set-main'),
|
||||||
path('kit/photo/<int:pk>/move-up/', views.productkit_photo_move_up, name='productkit-photo-move-up'),
|
path('kit/photo/<int:pk>/move-up/', views.productkit_photo_move_up, name='productkit-photo-move-up'),
|
||||||
path('kit/photo/<int:pk>/move-down/', views.productkit_photo_move_down, name='productkit-photo-move-down'),
|
path('kit/photo/<int:pk>/move-down/', views.productkit_photo_move_down, name='productkit-photo-move-down'),
|
||||||
|
path('kit/photos/delete-bulk/', views.productkit_photos_delete_bulk, name='productkit-photos-delete-bulk'),
|
||||||
|
|
||||||
# API endpoints
|
# API endpoints
|
||||||
path('api/search-products-variants/', views.search_products_and_variants, name='api-search-products-variants'),
|
path('api/search-products-variants/', views.search_products_and_variants, name='api-search-products-variants'),
|
||||||
@@ -55,6 +56,10 @@ urlpatterns = [
|
|||||||
path('api/payment-methods/', api_views.get_payment_methods, name='api-payment-methods'),
|
path('api/payment-methods/', api_views.get_payment_methods, name='api-payment-methods'),
|
||||||
path('api/filtered-items-ids/', api_views.get_filtered_items_ids, name='api-filtered-items-ids'),
|
path('api/filtered-items-ids/', api_views.get_filtered_items_ids, name='api-filtered-items-ids'),
|
||||||
path('api/bulk-update-categories/', api_views.bulk_update_categories, name='api-bulk-update-categories'),
|
path('api/bulk-update-categories/', api_views.bulk_update_categories, name='api-bulk-update-categories'),
|
||||||
|
path('api/bouquet-names/random/', api_views.RandomBouquetNamesView.as_view(), name='api-random-bouquet-names'),
|
||||||
|
path('api/bouquet-names/generate/', api_views.GenerateBouquetNamesView.as_view(), name='api-generate-bouquet-names'),
|
||||||
|
path('api/bouquet-names/<int:pk>/delete/', api_views.DeleteBouquetNameView.as_view(), name='api-delete-bouquet-name'),
|
||||||
|
path('api/bouquet-names/count/', api_views.GetBouquetNamesCountView.as_view(), name='api-get-bouquet-names-count'),
|
||||||
|
|
||||||
# Photo processing status API (for AJAX polling)
|
# Photo processing status API (for AJAX polling)
|
||||||
path('api/photos/status/<str:task_id>/', photo_status_api.photo_processing_status, name='api-photo-status'),
|
path('api/photos/status/<str:task_id>/', photo_status_api.photo_processing_status, name='api-photo-status'),
|
||||||
|
|||||||
@@ -158,49 +158,41 @@ class ImageProcessor:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def _resize_image(img, size):
|
def _resize_image(img, size):
|
||||||
"""
|
"""
|
||||||
Изменяет размер изображения с сохранением пропорций.
|
Изменяет размер изображения с center-crop до точного квадратного размера.
|
||||||
НЕ увеличивает маленькие изображения (сохраняет качество).
|
НЕ увеличивает маленькие изображения (сохраняет качество).
|
||||||
Создает адаптивный квадрат по размеру реального изображения.
|
Создает квадратное изображение без белых полей.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
img: PIL Image object
|
img: PIL Image object
|
||||||
size: Кортеж (width, height) - максимальный целевой размер
|
size: Кортеж (width, height) - целевой размер (обычно квадратный)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
PIL Image object - квадратное изображение с минимальным белым фоном
|
PIL Image object - квадратное изображение без белых полей
|
||||||
"""
|
"""
|
||||||
# Копируем изображение, чтобы не модифицировать оригинал
|
|
||||||
img_copy = img.copy()
|
img_copy = img.copy()
|
||||||
|
target_width, target_height = size
|
||||||
|
|
||||||
# Вычисляем пропорции исходного изображения и целевого размера
|
# Шаг 1: Center crop для получения квадрата
|
||||||
img_aspect = img_copy.width / img_copy.height
|
# Определяем минимальную сторону (будет размер квадрата)
|
||||||
target_aspect = size[0] / size[1]
|
min_side = min(img_copy.width, img_copy.height)
|
||||||
|
|
||||||
# Определяем, какой размер будет ограничивающим при масштабировании
|
# Вычисляем координаты для обрезки из центра
|
||||||
if img_aspect > target_aspect:
|
left = (img_copy.width - min_side) // 2
|
||||||
# Изображение шире - ограничиваемый размер это ширина
|
top = (img_copy.height - min_side) // 2
|
||||||
new_width = min(img_copy.width, size[0])
|
right = left + min_side
|
||||||
new_height = int(new_width / img_aspect)
|
bottom = top + min_side
|
||||||
|
|
||||||
|
# Обрезаем до квадрата
|
||||||
|
img_cropped = img_copy.crop((left, top, right, bottom))
|
||||||
|
|
||||||
|
# Шаг 2: Масштабируем до целевого размера (если исходный квадрат больше цели)
|
||||||
|
# Не увеличиваем маленькие изображения
|
||||||
|
if min_side > target_width:
|
||||||
|
img_resized = img_cropped.resize((target_width, target_height), Image.Resampling.LANCZOS)
|
||||||
else:
|
else:
|
||||||
# Изображение выше - ограничиваемый размер это высота
|
img_resized = img_cropped
|
||||||
new_height = min(img_copy.height, size[1])
|
|
||||||
new_width = int(new_height * img_aspect)
|
|
||||||
|
|
||||||
# Масштабируем только если необходимо (не увеличиваем маленькие изображения)
|
return img_resized
|
||||||
if img_copy.width > new_width or img_copy.height > new_height:
|
|
||||||
img_copy = img_copy.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
||||||
|
|
||||||
# Создаем адаптивный квадрат по размеру реального изображения (а не по конфигурации)
|
|
||||||
# Это позволяет избежать огромных белых полей для маленьких фото
|
|
||||||
square_size = max(img_copy.width, img_copy.height)
|
|
||||||
new_img = Image.new('RGB', (square_size, square_size), (255, 255, 255))
|
|
||||||
|
|
||||||
# Центрируем исходное изображение на белом фоне
|
|
||||||
offset_x = (square_size - img_copy.width) // 2
|
|
||||||
offset_y = (square_size - img_copy.height) // 2
|
|
||||||
new_img.paste(img_copy, (offset_x, offset_y))
|
|
||||||
|
|
||||||
return new_img
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _make_square_image(img, max_size):
|
def _make_square_image(img, max_size):
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from .photo_management import (
|
|||||||
productkit_photo_set_main,
|
productkit_photo_set_main,
|
||||||
productkit_photo_move_up,
|
productkit_photo_move_up,
|
||||||
productkit_photo_move_down,
|
productkit_photo_move_down,
|
||||||
|
productkit_photos_delete_bulk,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Управление фотографиями (Category)
|
# Управление фотографиями (Category)
|
||||||
@@ -114,7 +115,14 @@ from .attribute_views import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
# API представления
|
# API представления
|
||||||
from .api_views import search_products_and_variants, validate_kit_cost, create_temporary_kit_api, create_tag_api
|
from .api_views import (
|
||||||
|
search_products_and_variants,
|
||||||
|
validate_kit_cost,
|
||||||
|
create_temporary_kit_api,
|
||||||
|
create_tag_api,
|
||||||
|
RandomBouquetNamesView,
|
||||||
|
GenerateBouquetNamesView,
|
||||||
|
)
|
||||||
|
|
||||||
# Каталог
|
# Каталог
|
||||||
from .catalog_views import CatalogView
|
from .catalog_views import CatalogView
|
||||||
@@ -149,6 +157,7 @@ __all__ = [
|
|||||||
'productkit_photo_set_main',
|
'productkit_photo_set_main',
|
||||||
'productkit_photo_move_up',
|
'productkit_photo_move_up',
|
||||||
'productkit_photo_move_down',
|
'productkit_photo_move_down',
|
||||||
|
'productkit_photos_delete_bulk',
|
||||||
|
|
||||||
# Управление фотографиями Category
|
# Управление фотографиями Category
|
||||||
'category_photo_delete',
|
'category_photo_delete',
|
||||||
@@ -225,6 +234,8 @@ __all__ = [
|
|||||||
'validate_kit_cost',
|
'validate_kit_cost',
|
||||||
'create_temporary_kit_api',
|
'create_temporary_kit_api',
|
||||||
'create_tag_api',
|
'create_tag_api',
|
||||||
|
'RandomBouquetNamesView',
|
||||||
|
'GenerateBouquetNamesView',
|
||||||
|
|
||||||
# Каталог
|
# Каталог
|
||||||
'CatalogView',
|
'CatalogView',
|
||||||
|
|||||||
@@ -1800,3 +1800,72 @@ def bulk_update_categories(request):
|
|||||||
'success': False,
|
'success': False,
|
||||||
'message': f'Произошла ошибка: {str(e)}'
|
'message': f'Произошла ошибка: {str(e)}'
|
||||||
}, status=500)
|
}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
# ========== Генератор названий букетов ==========
|
||||||
|
|
||||||
|
from django.views import View
|
||||||
|
from ..models import BouquetName
|
||||||
|
from ..services import BouquetNameGenerator
|
||||||
|
|
||||||
|
|
||||||
|
class RandomBouquetNamesView(View):
|
||||||
|
"""Возвращает случайные названия из базы"""
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
count = int(request.GET.get('count', 3))
|
||||||
|
# Ограничиваем максимум до 100
|
||||||
|
count = min(count, 100)
|
||||||
|
|
||||||
|
# Получаем случайные названия с ID (любые, не только одобренные)
|
||||||
|
queryset = BouquetName.objects.order_by('?')[:count]
|
||||||
|
names_data = [{'id': obj.id, 'name': obj.name} for obj in queryset]
|
||||||
|
|
||||||
|
return JsonResponse({'names': names_data})
|
||||||
|
|
||||||
|
|
||||||
|
class GenerateBouquetNamesView(View):
|
||||||
|
"""Генерирует новые названия через LLM и сохраняет в базу"""
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
count = int(request.POST.get('count', 10))
|
||||||
|
# Ограничиваем максимум до 500
|
||||||
|
count = min(count, 500)
|
||||||
|
|
||||||
|
generator = BouquetNameGenerator()
|
||||||
|
|
||||||
|
success, msg, data = generator.generate_and_store(
|
||||||
|
count=count,
|
||||||
|
language='russian'
|
||||||
|
)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': True,
|
||||||
|
'message': msg,
|
||||||
|
'count': len(data.get('names', []))
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
return JsonResponse({'success': False, 'error': msg}, status=400)
|
||||||
|
|
||||||
|
|
||||||
|
class DeleteBouquetNameView(View):
|
||||||
|
"""Удаляет конкретное название из базы"""
|
||||||
|
|
||||||
|
def delete(self, request, pk):
|
||||||
|
try:
|
||||||
|
name_obj = BouquetName.objects.get(pk=pk)
|
||||||
|
name_obj.delete()
|
||||||
|
return JsonResponse({'success': True})
|
||||||
|
except BouquetName.DoesNotExist:
|
||||||
|
return JsonResponse({'success': False, 'error': 'Название не найдено'}, status=404)
|
||||||
|
except Exception as e:
|
||||||
|
return JsonResponse({'success': False, 'error': str(e)}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
class GetBouquetNamesCountView(View):
|
||||||
|
"""Возвращает количество названий в базе"""
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
count = BouquetName.objects.count()
|
||||||
|
return JsonResponse({'count': count})
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class TreeItem:
|
|||||||
if item_type == 'product':
|
if item_type == 'product':
|
||||||
self.price = obj.sale_price
|
self.price = obj.sale_price
|
||||||
elif item_type == 'kit':
|
elif item_type == 'kit':
|
||||||
self.price = obj.get_sale_price()
|
self.price = obj.actual_price
|
||||||
else:
|
else:
|
||||||
self.price = None
|
self.price = None
|
||||||
|
|
||||||
|
|||||||
@@ -380,3 +380,67 @@ def product_photos_delete_bulk(request):
|
|||||||
'success': False,
|
'success': False,
|
||||||
'error': f'Ошибка сервера: {str(e)}'
|
'error': f'Ошибка сервера: {str(e)}'
|
||||||
}, status=500)
|
}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@login_required
|
||||||
|
def productkit_photos_delete_bulk(request):
|
||||||
|
"""
|
||||||
|
AJAX endpoint для массового удаления фотографий комплекта.
|
||||||
|
|
||||||
|
Ожидает JSON: {photo_ids: [1, 2, 3]}
|
||||||
|
Возвращает JSON: {success: true, deleted: 3} или {success: false, error: "..."}
|
||||||
|
"""
|
||||||
|
# Проверка прав доступа
|
||||||
|
if not request.user.has_perm('products.change_productkit'):
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'У вас нет прав для удаления фотографий'
|
||||||
|
}, status=403)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Получаем список photo_ids из JSON тела запроса
|
||||||
|
data = json.loads(request.body)
|
||||||
|
photo_ids = data.get('photo_ids', [])
|
||||||
|
|
||||||
|
if not photo_ids or not isinstance(photo_ids, list):
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Неверный формат: требуется список photo_ids'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
# Удаляем фотографии
|
||||||
|
deleted_count = 0
|
||||||
|
for photo_id in photo_ids:
|
||||||
|
try:
|
||||||
|
photo = ProductKitPhoto.objects.get(pk=photo_id)
|
||||||
|
photo.delete() # Это вызовет ImageProcessor.delete_all_versions()
|
||||||
|
deleted_count += 1
|
||||||
|
except ProductKitPhoto.DoesNotExist:
|
||||||
|
# Если фото не найдена, просто пропускаем
|
||||||
|
continue
|
||||||
|
except Exception as e:
|
||||||
|
# Логируем ошибку но продолжаем удаление остальных
|
||||||
|
import logging
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logger.error(f"Error deleting kit photo {photo_id}: {str(e)}", exc_info=True)
|
||||||
|
continue
|
||||||
|
|
||||||
|
return JsonResponse({
|
||||||
|
'success': True,
|
||||||
|
'deleted': deleted_count
|
||||||
|
})
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Неверный JSON формат'
|
||||||
|
}, status=400)
|
||||||
|
except Exception as e:
|
||||||
|
import logging
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logger.error(f"Bulk kit photo deletion error: {str(e)}", exc_info=True)
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': f'Ошибка сервера: {str(e)}'
|
||||||
|
}, status=500)
|
||||||
|
|||||||
@@ -208,6 +208,15 @@ class ProductDetailView(LoginRequiredMixin, ManagerOwnerRequiredMixin, DetailVie
|
|||||||
# Единицы продажи (активные, отсортированные)
|
# Единицы продажи (активные, отсортированные)
|
||||||
context['sales_units'] = self.object.sales_units.filter(is_active=True).order_by('position', 'name')
|
context['sales_units'] = self.object.sales_units.filter(is_active=True).order_by('position', 'name')
|
||||||
|
|
||||||
|
# Комплекты, в которых этот товар используется как единица продажи
|
||||||
|
context['kit_items_using_sales_units'] = self.object.kit_items_using_as_sales_unit.select_related('kit', 'sales_unit').prefetch_related('kit__photos')
|
||||||
|
|
||||||
|
# Комплекты, в которых этот товар используется напрямую
|
||||||
|
context['kit_items_using_products'] = self.object.kit_items_direct.select_related('kit').prefetch_related('kit__photos')
|
||||||
|
|
||||||
|
# Комплекты, в которых этот товар используется как часть группы вариантов
|
||||||
|
context['variant_group_kit_items'] = self.object.variant_group_items.select_related('variant_group').prefetch_related('variant_group__kit_items__kit__photos')
|
||||||
|
|
||||||
return context
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,10 @@ from django.shortcuts import redirect
|
|||||||
from django.db import transaction, IntegrityError
|
from django.db import transaction, IntegrityError
|
||||||
|
|
||||||
from user_roles.mixins import ManagerOwnerRequiredMixin
|
from user_roles.mixins import ManagerOwnerRequiredMixin
|
||||||
from ..models import ProductKit, ProductCategory, ProductTag, ProductKitPhoto, Product, ProductVariantGroup
|
from ..models import ProductKit, ProductCategory, ProductTag, ProductKitPhoto, Product, ProductVariantGroup, BouquetName, ProductSalesUnit
|
||||||
from ..forms import ProductKitForm, KitItemFormSetCreate, KitItemFormSetUpdate
|
from ..forms import ProductKitForm, KitItemFormSetCreate, KitItemFormSetUpdate
|
||||||
from .utils import handle_photos
|
from .utils import handle_photos
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
class ProductKitListView(LoginRequiredMixin, ManagerOwnerRequiredMixin, ListView):
|
class ProductKitListView(LoginRequiredMixin, ManagerOwnerRequiredMixin, ListView):
|
||||||
@@ -97,6 +98,37 @@ class ProductKitCreateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Create
|
|||||||
form_class = ProductKitForm
|
form_class = ProductKitForm
|
||||||
template_name = 'products/productkit_create.html'
|
template_name = 'products/productkit_create.html'
|
||||||
|
|
||||||
|
def get_initial(self):
|
||||||
|
initial = super().get_initial()
|
||||||
|
copy_id = self.request.GET.get('copy_from')
|
||||||
|
if copy_id:
|
||||||
|
try:
|
||||||
|
kit = ProductKit.objects.get(pk=copy_id)
|
||||||
|
|
||||||
|
# Generate unique name
|
||||||
|
base_name = f"{kit.name} (Копия)"
|
||||||
|
new_name = base_name
|
||||||
|
counter = 1
|
||||||
|
while ProductKit.objects.filter(name=new_name).exists():
|
||||||
|
counter += 1
|
||||||
|
new_name = f"{base_name} {counter}"
|
||||||
|
|
||||||
|
initial.update({
|
||||||
|
'name': new_name,
|
||||||
|
'description': kit.description,
|
||||||
|
'short_description': kit.short_description,
|
||||||
|
'categories': list(kit.categories.values_list('pk', flat=True)),
|
||||||
|
'tags': list(kit.tags.values_list('pk', flat=True)),
|
||||||
|
'sale_price': kit.sale_price,
|
||||||
|
'price_adjustment_type': kit.price_adjustment_type,
|
||||||
|
'price_adjustment_value': kit.price_adjustment_value,
|
||||||
|
'external_category': kit.external_category,
|
||||||
|
'status': 'active', # Default to active for new kits
|
||||||
|
})
|
||||||
|
except ProductKit.DoesNotExist:
|
||||||
|
pass
|
||||||
|
return initial
|
||||||
|
|
||||||
def post(self, request, *args, **kwargs):
|
def post(self, request, *args, **kwargs):
|
||||||
"""
|
"""
|
||||||
Обрабатываем POST данные и очищаем ID товаров/комплектов от префиксов.
|
Обрабатываем POST данные и очищаем ID товаров/комплектов от префиксов.
|
||||||
@@ -113,6 +145,12 @@ class ProductKitCreateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Create
|
|||||||
# Извлекаем числовой ID из "product_123"
|
# Извлекаем числовой ID из "product_123"
|
||||||
numeric_id = value.split('_')[1]
|
numeric_id = value.split('_')[1]
|
||||||
post_data[key] = numeric_id
|
post_data[key] = numeric_id
|
||||||
|
elif key.endswith('-sales_unit') and post_data[key]:
|
||||||
|
value = post_data[key]
|
||||||
|
if '_' in value:
|
||||||
|
# Извлекаем числовой ID из "sales_unit_123"
|
||||||
|
numeric_id = value.split('_')[1]
|
||||||
|
post_data[key] = numeric_id
|
||||||
|
|
||||||
# Заменяем request.POST на очищенные данные
|
# Заменяем request.POST на очищенные данные
|
||||||
request.POST = post_data
|
request.POST = post_data
|
||||||
@@ -126,9 +164,9 @@ class ProductKitCreateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Create
|
|||||||
context['kititem_formset'] = KitItemFormSetCreate(self.request.POST, prefix='kititem')
|
context['kititem_formset'] = KitItemFormSetCreate(self.request.POST, prefix='kititem')
|
||||||
|
|
||||||
# При ошибке валидации: извлекаем выбранные товары для предзагрузки в Select2
|
# При ошибке валидации: извлекаем выбранные товары для предзагрузки в Select2
|
||||||
from ..models import Product, ProductVariantGroup
|
|
||||||
selected_products = {}
|
selected_products = {}
|
||||||
selected_variants = {}
|
selected_variants = {}
|
||||||
|
selected_sales_units = {}
|
||||||
|
|
||||||
for key, value in self.request.POST.items():
|
for key, value in self.request.POST.items():
|
||||||
if '-product' in key and value:
|
if '-product' in key and value:
|
||||||
@@ -168,10 +206,120 @@ class ProductKitCreateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Create
|
|||||||
except ProductVariantGroup.DoesNotExist:
|
except ProductVariantGroup.DoesNotExist:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
if '-sales_unit' in key and value:
|
||||||
|
try:
|
||||||
|
sales_unit = ProductSalesUnit.objects.select_related('product').get(id=value)
|
||||||
|
|
||||||
|
text = f"{sales_unit.name} ({sales_unit.product.name})"
|
||||||
|
# Получаем actual_price: приоритет sale_price > price
|
||||||
|
actual_price = sales_unit.sale_price if sales_unit.sale_price else sales_unit.price
|
||||||
|
selected_sales_units[key] = {
|
||||||
|
'id': sales_unit.id,
|
||||||
|
'text': text,
|
||||||
|
'price': str(sales_unit.price) if sales_unit.price else None,
|
||||||
|
'actual_price': str(actual_price) if actual_price else '0'
|
||||||
|
}
|
||||||
|
except ProductSalesUnit.DoesNotExist:
|
||||||
|
pass
|
||||||
|
|
||||||
context['selected_products'] = selected_products
|
context['selected_products'] = selected_products
|
||||||
context['selected_variants'] = selected_variants
|
context['selected_variants'] = selected_variants
|
||||||
|
context['selected_sales_units'] = selected_sales_units
|
||||||
else:
|
else:
|
||||||
context['kititem_formset'] = KitItemFormSetCreate(prefix='kititem')
|
# COPY KIT LOGIC
|
||||||
|
copy_id = self.request.GET.get('copy_from')
|
||||||
|
initial_items = []
|
||||||
|
selected_products = {}
|
||||||
|
selected_variants = {}
|
||||||
|
selected_sales_units = {}
|
||||||
|
|
||||||
|
if copy_id:
|
||||||
|
try:
|
||||||
|
source_kit = ProductKit.objects.get(pk=copy_id)
|
||||||
|
for item in source_kit.kit_items.all():
|
||||||
|
item_data = {
|
||||||
|
'quantity': item.quantity,
|
||||||
|
# Delete flag is false by default
|
||||||
|
}
|
||||||
|
|
||||||
|
form_prefix = f"kititem-{len(initial_items)}"
|
||||||
|
|
||||||
|
if item.product:
|
||||||
|
item_data['product'] = item.product
|
||||||
|
# Select2 prefill
|
||||||
|
product = item.product
|
||||||
|
text = product.name
|
||||||
|
if product.sku:
|
||||||
|
text += f" ({product.sku})"
|
||||||
|
actual_price = product.sale_price if product.sale_price else product.price
|
||||||
|
selected_products[f"{form_prefix}-product"] = {
|
||||||
|
'id': product.id,
|
||||||
|
'text': text,
|
||||||
|
'price': str(product.price) if product.price else None,
|
||||||
|
'actual_price': str(actual_price) if actual_price else '0'
|
||||||
|
}
|
||||||
|
|
||||||
|
if item.sales_unit:
|
||||||
|
item_data['sales_unit'] = item.sales_unit
|
||||||
|
# Select2 prefill
|
||||||
|
sales_unit = item.sales_unit
|
||||||
|
text = f"{sales_unit.name} ({sales_unit.product.name})"
|
||||||
|
actual_price = sales_unit.sale_price if sales_unit.sale_price else sales_unit.price
|
||||||
|
selected_sales_units[f"{form_prefix}-sales_unit"] = {
|
||||||
|
'id': sales_unit.id,
|
||||||
|
'text': text,
|
||||||
|
'price': str(sales_unit.price) if sales_unit.price else None,
|
||||||
|
'actual_price': str(actual_price) if actual_price else '0'
|
||||||
|
}
|
||||||
|
|
||||||
|
if item.variant_group:
|
||||||
|
item_data['variant_group'] = item.variant_group
|
||||||
|
# Select2 prefill
|
||||||
|
variant_group = ProductVariantGroup.objects.prefetch_related(
|
||||||
|
'items__product'
|
||||||
|
).get(id=item.variant_group.id)
|
||||||
|
variant_price = variant_group.price or 0
|
||||||
|
count = variant_group.items.count()
|
||||||
|
selected_variants[f"{form_prefix}-variant_group"] = {
|
||||||
|
'id': variant_group.id,
|
||||||
|
'text': f"{variant_group.name} ({count} вариантов)",
|
||||||
|
'price': str(variant_price),
|
||||||
|
'actual_price': str(variant_price),
|
||||||
|
'type': 'variant',
|
||||||
|
'count': count
|
||||||
|
}
|
||||||
|
|
||||||
|
initial_items.append(item_data)
|
||||||
|
except ProductKit.DoesNotExist:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if initial_items:
|
||||||
|
context['kititem_formset'] = KitItemFormSetCreate(
|
||||||
|
prefix='kititem',
|
||||||
|
initial=initial_items
|
||||||
|
)
|
||||||
|
context['kititem_formset'].extra = len(initial_items)
|
||||||
|
else:
|
||||||
|
context['kititem_formset'] = KitItemFormSetCreate(prefix='kititem')
|
||||||
|
|
||||||
|
# Pass Select2 data to context
|
||||||
|
context['selected_products'] = selected_products
|
||||||
|
context['selected_variants'] = selected_variants
|
||||||
|
context['selected_sales_units'] = selected_sales_units
|
||||||
|
|
||||||
|
# Pass source photos if copying
|
||||||
|
if copy_id:
|
||||||
|
try:
|
||||||
|
source_kit = ProductKit.objects.prefetch_related('photos').get(pk=copy_id)
|
||||||
|
photos = source_kit.photos.all().order_by('order')
|
||||||
|
print(f"DEBUG: Found {photos.count()} source photos for kit {copy_id}")
|
||||||
|
context['source_photos'] = photos
|
||||||
|
except ProductKit.DoesNotExist:
|
||||||
|
print(f"DEBUG: Source kit {copy_id} not found")
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Количество названий букетов в базе
|
||||||
|
context['bouquet_names_count'] = BouquetName.objects.count()
|
||||||
|
|
||||||
return context
|
return context
|
||||||
|
|
||||||
@@ -208,6 +356,48 @@ class ProductKitCreateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Create
|
|||||||
# Обработка фотографий
|
# Обработка фотографий
|
||||||
handle_photos(self.request, self.object, ProductKitPhoto, 'kit')
|
handle_photos(self.request, self.object, ProductKitPhoto, 'kit')
|
||||||
|
|
||||||
|
# Handle copied photos
|
||||||
|
copied_photo_ids = self.request.POST.getlist('copied_photos')
|
||||||
|
print(f"DEBUG: copied_photo_ids in POST: {copied_photo_ids}")
|
||||||
|
|
||||||
|
if copied_photo_ids:
|
||||||
|
from django.core.files.base import ContentFile
|
||||||
|
original_photos = ProductKitPhoto.objects.filter(id__in=copied_photo_ids)
|
||||||
|
print(f"DEBUG: Found {original_photos.count()} original photos to copy")
|
||||||
|
|
||||||
|
# Get max order from existing photos (uploaded via handle_photos)
|
||||||
|
from django.db.models import Max
|
||||||
|
max_order = self.object.photos.aggregate(Max('order'))['order__max']
|
||||||
|
next_order = 0 if max_order is None else max_order + 1
|
||||||
|
print(f"DEBUG: Starting order for copies: {next_order}")
|
||||||
|
|
||||||
|
for photo in original_photos:
|
||||||
|
try:
|
||||||
|
# Open the original image file
|
||||||
|
if photo.image:
|
||||||
|
print(f"DEBUG: Processing photo {photo.id}: {photo.image.name}")
|
||||||
|
with photo.image.open('rb') as f:
|
||||||
|
image_content = f.read()
|
||||||
|
|
||||||
|
# Create a new ContentFile
|
||||||
|
new_image_name = f"copy_{self.object.id}_{os.path.basename(photo.image.name)}"
|
||||||
|
print(f"DEBUG: New image name: {new_image_name}")
|
||||||
|
|
||||||
|
# Create new photo instance
|
||||||
|
new_photo = ProductKitPhoto(kit=self.object, order=next_order)
|
||||||
|
# Save the image file (this also saves the model instance)
|
||||||
|
new_photo.image.save(new_image_name, ContentFile(image_content))
|
||||||
|
print(f"DEBUG: Successfully saved copy for photo {photo.id}")
|
||||||
|
|
||||||
|
next_order += 1
|
||||||
|
else:
|
||||||
|
print(f"DEBUG: Photo {photo.id} has no image file")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error copying photo {photo.id}: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
continue
|
||||||
|
|
||||||
messages.success(
|
messages.success(
|
||||||
self.request,
|
self.request,
|
||||||
f'Комплект "{self.object.name}" успешно создан!'
|
f'Комплект "{self.object.name}" успешно создан!'
|
||||||
@@ -271,6 +461,12 @@ class ProductKitUpdateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Update
|
|||||||
# Извлекаем числовой ID из "product_123"
|
# Извлекаем числовой ID из "product_123"
|
||||||
numeric_id = value.split('_')[1]
|
numeric_id = value.split('_')[1]
|
||||||
post_data[key] = numeric_id
|
post_data[key] = numeric_id
|
||||||
|
elif key.endswith('-sales_unit') and post_data[key]:
|
||||||
|
value = post_data[key]
|
||||||
|
if '_' in value:
|
||||||
|
# Извлекаем числовой ID из "sales_unit_123"
|
||||||
|
numeric_id = value.split('_')[1]
|
||||||
|
post_data[key] = numeric_id
|
||||||
|
|
||||||
# Заменяем request.POST на очищенные данные
|
# Заменяем request.POST на очищенные данные
|
||||||
request.POST = post_data
|
request.POST = post_data
|
||||||
@@ -284,8 +480,10 @@ class ProductKitUpdateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Update
|
|||||||
context['kititem_formset'] = KitItemFormSetUpdate(self.request.POST, instance=self.object, prefix='kititem')
|
context['kititem_formset'] = KitItemFormSetUpdate(self.request.POST, instance=self.object, prefix='kititem')
|
||||||
|
|
||||||
# При ошибке валидации - подготавливаем данные для Select2
|
# При ошибке валидации - подготавливаем данные для Select2
|
||||||
|
from ..models import Product, ProductVariantGroup, ProductSalesUnit
|
||||||
selected_products = {}
|
selected_products = {}
|
||||||
selected_variants = {}
|
selected_variants = {}
|
||||||
|
selected_sales_units = {}
|
||||||
|
|
||||||
for key, value in self.request.POST.items():
|
for key, value in self.request.POST.items():
|
||||||
if '-product' in key and value:
|
if '-product' in key and value:
|
||||||
@@ -328,14 +526,35 @@ class ProductKitUpdateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Update
|
|||||||
except ProductVariantGroup.DoesNotExist:
|
except ProductVariantGroup.DoesNotExist:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
if '-sales_unit' in key and value:
|
||||||
|
try:
|
||||||
|
# Очищаем ID от префикса если есть
|
||||||
|
numeric_value = value.split('_')[1] if '_' in value else value
|
||||||
|
sales_unit = ProductSalesUnit.objects.select_related('product').get(id=numeric_value)
|
||||||
|
|
||||||
|
text = f"{sales_unit.name} ({sales_unit.product.name})"
|
||||||
|
# Получаем actual_price: приоритет sale_price > price
|
||||||
|
actual_price = sales_unit.sale_price if sales_unit.sale_price else sales_unit.price
|
||||||
|
selected_sales_units[key] = {
|
||||||
|
'id': sales_unit.id,
|
||||||
|
'text': text,
|
||||||
|
'price': str(sales_unit.price) if sales_unit.price else None,
|
||||||
|
'actual_price': str(actual_price) if actual_price else '0'
|
||||||
|
}
|
||||||
|
except ProductSalesUnit.DoesNotExist:
|
||||||
|
pass
|
||||||
|
|
||||||
context['selected_products'] = selected_products
|
context['selected_products'] = selected_products
|
||||||
context['selected_variants'] = selected_variants
|
context['selected_variants'] = selected_variants
|
||||||
|
context['selected_sales_units'] = selected_sales_units
|
||||||
else:
|
else:
|
||||||
context['kititem_formset'] = KitItemFormSetUpdate(instance=self.object, prefix='kititem')
|
context['kititem_formset'] = KitItemFormSetUpdate(instance=self.object, prefix='kititem')
|
||||||
|
|
||||||
# Подготавливаем данные для предзагрузки в Select2
|
# Подготавливаем данные для предзагрузки в Select2
|
||||||
|
from ..models import Product, ProductVariantGroup, ProductSalesUnit
|
||||||
selected_products = {}
|
selected_products = {}
|
||||||
selected_variants = {}
|
selected_variants = {}
|
||||||
|
selected_sales_units = {}
|
||||||
|
|
||||||
for item in self.object.kit_items.all():
|
for item in self.object.kit_items.all():
|
||||||
form_prefix = f"kititem-{item.id}"
|
form_prefix = f"kititem-{item.id}"
|
||||||
@@ -354,6 +573,17 @@ class ProductKitUpdateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Update
|
|||||||
'actual_price': str(actual_price) if actual_price else '0'
|
'actual_price': str(actual_price) if actual_price else '0'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if item.sales_unit:
|
||||||
|
sales_unit = item.sales_unit
|
||||||
|
text = f"{sales_unit.name} ({sales_unit.product.name})"
|
||||||
|
actual_price = sales_unit.sale_price if sales_unit.sale_price else sales_unit.price
|
||||||
|
selected_sales_units[f"{form_prefix}-sales_unit"] = {
|
||||||
|
'id': sales_unit.id,
|
||||||
|
'text': text,
|
||||||
|
'price': str(sales_unit.price) if sales_unit.price else None,
|
||||||
|
'actual_price': str(actual_price) if actual_price else '0'
|
||||||
|
}
|
||||||
|
|
||||||
if item.variant_group:
|
if item.variant_group:
|
||||||
variant_group = ProductVariantGroup.objects.prefetch_related(
|
variant_group = ProductVariantGroup.objects.prefetch_related(
|
||||||
'items__product'
|
'items__product'
|
||||||
@@ -373,6 +603,7 @@ class ProductKitUpdateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Update
|
|||||||
|
|
||||||
context['selected_products'] = selected_products
|
context['selected_products'] = selected_products
|
||||||
context['selected_variants'] = selected_variants
|
context['selected_variants'] = selected_variants
|
||||||
|
context['selected_sales_units'] = selected_sales_units
|
||||||
|
|
||||||
context['productkit_photos'] = self.object.photos.all().order_by('order', 'created_at')
|
context['productkit_photos'] = self.object.photos.all().order_by('order', 'created_at')
|
||||||
context['photos_count'] = self.object.photos.count()
|
context['photos_count'] = self.object.photos.count()
|
||||||
|
|||||||
@@ -63,6 +63,11 @@ def unit_of_measure_create(request):
|
|||||||
"""
|
"""
|
||||||
Создание новой единицы измерения
|
Создание новой единицы измерения
|
||||||
"""
|
"""
|
||||||
|
# Проверка: PlatformAdmin не имеет доступа к бизнес-данным тенантов
|
||||||
|
if request.user.__class__.__name__ == 'PlatformAdmin':
|
||||||
|
messages.error(request, 'У вас недостаточно прав для выполнения этого действия')
|
||||||
|
return redirect('products:unit-list')
|
||||||
|
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
form = UnitOfMeasureForm(request.POST)
|
form = UnitOfMeasureForm(request.POST)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
@@ -85,6 +90,11 @@ def unit_of_measure_update(request, pk):
|
|||||||
"""
|
"""
|
||||||
Редактирование единицы измерения
|
Редактирование единицы измерения
|
||||||
"""
|
"""
|
||||||
|
# Проверка: PlatformAdmin не имеет доступа к бизнес-данным тенантов
|
||||||
|
if request.user.__class__.__name__ == 'PlatformAdmin':
|
||||||
|
messages.error(request, 'У вас недостаточно прав для выполнения этого действия')
|
||||||
|
return redirect('products:unit-list')
|
||||||
|
|
||||||
unit = get_object_or_404(UnitOfMeasure, pk=pk)
|
unit = get_object_or_404(UnitOfMeasure, pk=pk)
|
||||||
|
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
@@ -110,11 +120,16 @@ def unit_of_measure_delete(request, pk):
|
|||||||
"""
|
"""
|
||||||
Удаление единицы измерения
|
Удаление единицы измерения
|
||||||
"""
|
"""
|
||||||
|
# Проверка: PlatformAdmin не имеет доступа к бизнес-данным тенантов
|
||||||
|
if request.user.__class__.__name__ == 'PlatformAdmin':
|
||||||
|
messages.error(request, 'У вас недостаточно прав для выполнения этого действия')
|
||||||
|
return redirect('products:unit-list')
|
||||||
|
|
||||||
unit = get_object_or_404(UnitOfMeasure, pk=pk)
|
unit = get_object_or_404(UnitOfMeasure, pk=pk)
|
||||||
|
|
||||||
# Проверяем использование
|
# Проверяем использование
|
||||||
products_using = unit.products.count()
|
products_using = unit.products.count()
|
||||||
sales_units_using = unit.productsalesunit_set.count()
|
sales_units_using = ProductSalesUnit.objects.filter(product__base_unit=unit).count()
|
||||||
|
|
||||||
can_delete = products_using == 0 and sales_units_using == 0
|
can_delete = products_using == 0 and sales_units_using == 0
|
||||||
|
|
||||||
|
|||||||
120
myproject/reproduce_issue.py
Normal file
120
myproject/reproduce_issue.py
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import django
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
# Setup Django
|
||||||
|
sys.path.append(os.getcwd())
|
||||||
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
|
||||||
|
django.setup()
|
||||||
|
|
||||||
|
from django.test import RequestFactory
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.db import connection
|
||||||
|
|
||||||
|
from customers.models import Customer
|
||||||
|
from inventory.models import Warehouse, Sale
|
||||||
|
from products.models import Product, UnitOfMeasure
|
||||||
|
from pos.views import pos_checkout
|
||||||
|
from orders.models import OrderStatus
|
||||||
|
|
||||||
|
def run():
|
||||||
|
# Setup Data
|
||||||
|
User = get_user_model()
|
||||||
|
user = User.objects.first()
|
||||||
|
if not user:
|
||||||
|
print("No user found")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Create/Get Customer
|
||||||
|
customer, _ = Customer.objects.get_or_create(
|
||||||
|
name="Test Customer",
|
||||||
|
defaults={'phone': '+375291112233'}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create/Get Warehouse
|
||||||
|
warehouse, _ = Warehouse.objects.get_or_create(
|
||||||
|
name="Test Warehouse",
|
||||||
|
defaults={'is_active': True}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create product
|
||||||
|
product, _ = Product.objects.get_or_create(
|
||||||
|
name="Test Product Debug",
|
||||||
|
defaults={
|
||||||
|
'sku': 'DEBUG001',
|
||||||
|
'buying_price': 10,
|
||||||
|
'actual_price': 50,
|
||||||
|
'warehouse': warehouse
|
||||||
|
}
|
||||||
|
)
|
||||||
|
product.actual_price = 50
|
||||||
|
product.save()
|
||||||
|
|
||||||
|
# Ensure OrderStatus exists
|
||||||
|
OrderStatus.objects.get_or_create(code='completed', is_system=True, defaults={'name': 'Completed', 'is_positive_end': True})
|
||||||
|
OrderStatus.objects.get_or_create(code='draft', is_system=True, defaults={'name': 'Draft'})
|
||||||
|
|
||||||
|
# Prepare Request
|
||||||
|
factory = RequestFactory()
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"customer_id": customer.id,
|
||||||
|
"warehouse_id": warehouse.id,
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"type": "product",
|
||||||
|
"id": product.id,
|
||||||
|
"quantity": 1,
|
||||||
|
"price": 100.00, # Custom price
|
||||||
|
"quantity_base": 1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"payments": [
|
||||||
|
{"payment_method": "cash", "amount": 100.00}
|
||||||
|
],
|
||||||
|
"notes": "Debug Sale"
|
||||||
|
}
|
||||||
|
|
||||||
|
request = factory.post(
|
||||||
|
'/pos/api/checkout/',
|
||||||
|
data=json.dumps(payload),
|
||||||
|
content_type='application/json'
|
||||||
|
)
|
||||||
|
request.user = user
|
||||||
|
|
||||||
|
print("Executing pos_checkout...")
|
||||||
|
response = pos_checkout(request)
|
||||||
|
print(f"Response: {response.content}")
|
||||||
|
|
||||||
|
# Verify Sale
|
||||||
|
sales = Sale.objects.filter(product=product).order_by('-id')[:1]
|
||||||
|
if sales:
|
||||||
|
sale = sales[0]
|
||||||
|
print(f"Sale created. ID: {sale.id}")
|
||||||
|
print(f"Sale Quantity: {sale.quantity}")
|
||||||
|
print(f"Sale Price: {sale.sale_price}")
|
||||||
|
if sale.sale_price == 0:
|
||||||
|
print("FAILURE: Sale price is 0!")
|
||||||
|
else:
|
||||||
|
print(f"SUCCESS: Sale price is {sale.sale_price}")
|
||||||
|
else:
|
||||||
|
print("FAILURE: No Sale created!")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
from django_tenants.utils import schema_context
|
||||||
|
# Replace with actual schema name if needed, assuming 'public' for now or the default tenant
|
||||||
|
# Since I don't know the tenant, I'll try to run in the current context.
|
||||||
|
# But usually need to set schema.
|
||||||
|
# Let's try to find a tenant.
|
||||||
|
from tenants.models import Client
|
||||||
|
tenant = Client.objects.first()
|
||||||
|
if tenant:
|
||||||
|
print(f"Running in tenant: {tenant.schema_name}")
|
||||||
|
with schema_context(tenant.schema_name):
|
||||||
|
run()
|
||||||
|
else:
|
||||||
|
print("No tenant found, running in public?")
|
||||||
|
run()
|
||||||
@@ -153,8 +153,8 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
statusBadge.style.display = 'inline';
|
statusBadge.style.display = 'inline';
|
||||||
|
|
||||||
// Построить форму
|
// Построить форму (теперь асинхронно)
|
||||||
buildForm(data.fields, data.data || {});
|
await buildForm(data.fields, data.data || {});
|
||||||
|
|
||||||
// Показать/скрыть кнопку тестирования
|
// Показать/скрыть кнопку тестирования
|
||||||
const testBtn = document.getElementById('test-connection-btn');
|
const testBtn = document.getElementById('test-connection-btn');
|
||||||
@@ -173,11 +173,11 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Построение формы из метаданных полей
|
// Построение формы из метаданных полей
|
||||||
function buildForm(fields, data) {
|
async function buildForm(fields, data) {
|
||||||
const container = document.getElementById('settings-fields');
|
const container = document.getElementById('settings-fields');
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
|
|
||||||
fields.forEach(field => {
|
for (const field of fields) {
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
div.className = 'mb-3';
|
div.className = 'mb-3';
|
||||||
|
|
||||||
@@ -189,27 +189,82 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
<label class="form-check-label" for="field-${field.name}">${field.label}</label>
|
<label class="form-check-label" for="field-${field.name}">${field.label}</label>
|
||||||
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
} else if (field.type === 'select') {
|
} else if (field.type === 'select') {
|
||||||
div.innerHTML = `
|
let optionsHtml = '';
|
||||||
<label class="form-label" for="field-${field.name}">
|
|
||||||
${field.label}
|
if (field.dynamic_choices) {
|
||||||
${field.required ? '<span class="text-danger">*</span>' : ''}
|
// Динамическая загрузка options
|
||||||
</label>
|
optionsHtml = '<option value="">Загрузка моделей...</option>';
|
||||||
<select class="form-select" id="field-${field.name}"
|
|
||||||
name="${field.name}"
|
div.innerHTML = `
|
||||||
${field.required ? 'required' : ''}>
|
<label class="form-label" for="field-${field.name}">
|
||||||
${field.choices.map(choice => `
|
${field.label}
|
||||||
<option value="${choice[0]}" ${data[field.name] === choice[0] ? 'selected' : ''}>
|
${field.required ? '<span class="text-danger">*</span>' : ''}
|
||||||
${choice[1]}
|
</label>
|
||||||
</option>
|
<select class="form-select" id="field-${field.name}"
|
||||||
`).join('')}
|
name="${field.name}"
|
||||||
</select>
|
${field.required ? 'required' : ''}>
|
||||||
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
${optionsHtml}
|
||||||
`;
|
</select>
|
||||||
|
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
||||||
|
`;
|
||||||
|
container.appendChild(div);
|
||||||
|
|
||||||
|
// Асинхронная загрузка
|
||||||
|
const select = div.querySelector('select');
|
||||||
|
try {
|
||||||
|
const response = await fetch(field.choices_url);
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
select.innerHTML = '<option value="">Ошибка загрузки моделей</option>';
|
||||||
|
console.error(result.error);
|
||||||
|
} else {
|
||||||
|
select.innerHTML = result.models.map(m =>
|
||||||
|
`<option value="${m.id}">${m.name}</option>`
|
||||||
|
).join('');
|
||||||
|
|
||||||
|
if (data[field.name]) {
|
||||||
|
select.value = data[field.name];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
select.innerHTML = '<option value="">Ошибка загрузки моделей</option>';
|
||||||
|
console.error('Error loading models:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Статический select (для temperature)
|
||||||
|
optionsHtml = field.choices.map(choice => `
|
||||||
|
<option value="${choice[0]}" ${data[field.name] === choice[0] ? 'selected' : ''}>
|
||||||
|
${choice[1]}
|
||||||
|
</option>
|
||||||
|
`).join('');
|
||||||
|
|
||||||
|
div.innerHTML = `
|
||||||
|
<label class="form-label" for="field-${field.name}">
|
||||||
|
${field.label}
|
||||||
|
${field.required ? '<span class="text-danger">*</span>' : ''}
|
||||||
|
</label>
|
||||||
|
<select class="form-select" id="field-${field.name}"
|
||||||
|
name="${field.name}"
|
||||||
|
${field.required ? 'required' : ''}>
|
||||||
|
${optionsHtml}
|
||||||
|
</select>
|
||||||
|
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
// text, password, url
|
||||||
const inputType = field.type === 'password' ? 'password' : (field.type === 'url' ? 'url' : 'text');
|
const inputType = field.type === 'password' ? 'password' : (field.type === 'url' ? 'url' : 'text');
|
||||||
const value = data[field.name] || '';
|
let value = data[field.name] || '';
|
||||||
const placeholder = field.type === 'password' && value === '........' ? 'Введите новое значение для изменения' : '';
|
const isMasked = value === '••••••••';
|
||||||
|
const placeholder = isMasked ? 'Ключ сохранён. Оставьте пустым, чтобы не менять' : '';
|
||||||
|
|
||||||
|
// Для password полей показываем звёздочки (8 штук как индикатор сохранённого ключа)
|
||||||
|
const inputValue = (field.type === 'password' && isMasked) ? '********' : value;
|
||||||
|
|
||||||
div.innerHTML = `
|
div.innerHTML = `
|
||||||
<label class="form-label" for="field-${field.name}">
|
<label class="form-label" for="field-${field.name}">
|
||||||
@@ -217,15 +272,17 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
${field.required ? '<span class="text-danger">*</span>' : ''}
|
${field.required ? '<span class="text-danger">*</span>' : ''}
|
||||||
</label>
|
</label>
|
||||||
<input type="${inputType}" class="form-control" id="field-${field.name}"
|
<input type="${inputType}" class="form-control" id="field-${field.name}"
|
||||||
name="${field.name}" value="${value !== '........' ? value : ''}"
|
name="${field.name}" value="${inputValue}"
|
||||||
placeholder="${placeholder}"
|
placeholder="${placeholder}"
|
||||||
${field.required ? 'required' : ''}>
|
${field.required && !isMasked ? 'required' : ''}>
|
||||||
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
${field.help_text ? `<div class="form-text">${field.help_text}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
container.appendChild(div);
|
if (field.type !== 'select' || !field.dynamic_choices) {
|
||||||
});
|
container.appendChild(div);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Обработчик клика на интеграцию
|
// Обработчик клика на интеграцию
|
||||||
@@ -313,9 +370,9 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
// Собрать данные формы
|
// Собрать данные формы
|
||||||
for (const [key, value] of formData.entries()) {
|
for (const [key, value] of formData.entries()) {
|
||||||
// Пропустить пустые password поля (не менять если не введено)
|
// Пропустить пустые password поля или звёздочки (не менять если не введено новое значение)
|
||||||
const input = document.getElementById(`field-${key}`);
|
const input = document.getElementById(`field-${key}`);
|
||||||
if (input && input.type === 'password' && !value) continue;
|
if (input && input.type === 'password' && (!value || value === '********')) continue;
|
||||||
data[key] = value;
|
data[key] = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,14 +20,14 @@
|
|||||||
{% if user.is_authenticated %}
|
{% if user.is_authenticated %}
|
||||||
{% comment %}Показываем меню tenant приложений только если мы не на странице setup-password (public схема){% endcomment %}
|
{% comment %}Показываем меню tenant приложений только если мы не на странице setup-password (public схема){% endcomment %}
|
||||||
{% if 'setup-password' not in request.path %}
|
{% if 'setup-password' not in request.path %}
|
||||||
<!-- 📦 Товары -->
|
<!-- Товары -->
|
||||||
<li class="nav-item dropdown">
|
<li class="nav-item dropdown">
|
||||||
<a class="nav-link dropdown-toggle {% if request.resolver_match.namespace == 'products' %}active{% endif %}" href="#" id="productsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
<a class="nav-link dropdown-toggle {% if request.resolver_match.namespace == 'products' %}active{% endif %}" href="#" id="productsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||||
📦 Товары
|
Товары
|
||||||
</a>
|
</a>
|
||||||
<ul class="dropdown-menu" aria-labelledby="productsDropdown">
|
<ul class="dropdown-menu" aria-labelledby="productsDropdown">
|
||||||
<li><a class="dropdown-item" href="{% url 'products:products-list' %}">Все товары</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:products-list' %}">Все товары</a></li>
|
||||||
<li><a class="dropdown-item" href="{% url 'products:catalog' %}"><i class="bi bi-grid-3x3-gap"></i> Каталог</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:catalog' %}">Каталог</a></li>
|
||||||
<li><a class="dropdown-item" href="{% url 'products:configurableproduct-list' %}">Вариативные товары</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:configurableproduct-list' %}">Вариативные товары</a></li>
|
||||||
<li><hr class="dropdown-divider"></li>
|
<li><hr class="dropdown-divider"></li>
|
||||||
<li><a class="dropdown-item" href="{% url 'products:category-list' %}">Категории</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:category-list' %}">Категории</a></li>
|
||||||
@@ -35,15 +35,15 @@
|
|||||||
<li><a class="dropdown-item" href="{% url 'products:variantgroup-list' %}">Варианты (группы)</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:variantgroup-list' %}">Варианты (группы)</a></li>
|
||||||
<li><a class="dropdown-item" href="{% url 'products:attribute-list' %}">Атрибуты</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:attribute-list' %}">Атрибуты</a></li>
|
||||||
<li><hr class="dropdown-divider"></li>
|
<li><hr class="dropdown-divider"></li>
|
||||||
<li><a class="dropdown-item" href="{% url 'products:unit-list' %}"><i class="bi bi-rulers"></i> Единицы измерения</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:unit-list' %}">Единицы измерения</a></li>
|
||||||
<li><a class="dropdown-item" href="{% url 'products:sales-unit-list' %}"><i class="bi bi-box-seam"></i> Единицы продажи</a></li>
|
<li><a class="dropdown-item" href="{% url 'products:sales-unit-list' %}">Единицы продажи</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<!-- 📋 Заказы -->
|
<!-- Заказы -->
|
||||||
<li class="nav-item dropdown">
|
<li class="nav-item dropdown">
|
||||||
<a class="nav-link dropdown-toggle {% if request.resolver_match.namespace == 'orders' %}active{% endif %}" href="{% url 'orders:order-list' %}" id="ordersDropdown">
|
<a class="nav-link dropdown-toggle {% if request.resolver_match.namespace == 'orders' %}active{% endif %}" href="{% url 'orders:order-list' %}" id="ordersDropdown">
|
||||||
📋 Заказы
|
Заказы
|
||||||
</a>
|
</a>
|
||||||
<ul class="dropdown-menu" aria-labelledby="ordersDropdown">
|
<ul class="dropdown-menu" aria-labelledby="ordersDropdown">
|
||||||
<li><a class="dropdown-item" href="{% url 'orders:order-list' %}">Список заказов</a></li>
|
<li><a class="dropdown-item" href="{% url 'orders:order-list' %}">Список заказов</a></li>
|
||||||
@@ -52,17 +52,17 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<!-- 👥 Клиенты -->
|
<!-- Клиенты -->
|
||||||
<li class="nav-item">
|
<li class="nav-item">
|
||||||
<a class="nav-link {% if request.resolver_match.namespace == 'customers' %}active{% endif %}" href="{% url 'customers:customer-list' %}">
|
<a class="nav-link {% if request.resolver_match.namespace == 'customers' %}active{% endif %}" href="{% url 'customers:customer-list' %}">
|
||||||
👥 Клиенты
|
Клиенты
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<!-- 📦 Склад -->
|
<!-- Склад -->
|
||||||
<li class="nav-item dropdown">
|
<li class="nav-item dropdown">
|
||||||
<a class="nav-link dropdown-toggle {% if request.resolver_match.namespace == 'inventory' %}active{% endif %}" href="#" id="inventoryDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
<a class="nav-link dropdown-toggle {% if request.resolver_match.namespace == 'inventory' %}active{% endif %}" href="#" id="inventoryDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||||
🏭 Склад
|
Склад
|
||||||
</a>
|
</a>
|
||||||
<ul class="dropdown-menu" aria-labelledby="inventoryDropdown">
|
<ul class="dropdown-menu" aria-labelledby="inventoryDropdown">
|
||||||
<li><a class="dropdown-item" href="{% url 'inventory:inventory-home' %}">Управление складом</a></li>
|
<li><a class="dropdown-item" href="{% url 'inventory:inventory-home' %}">Управление складом</a></li>
|
||||||
@@ -70,37 +70,37 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<!-- 💰 Касса -->
|
<!-- Касса -->
|
||||||
<li class="nav-item">
|
<li class="nav-item">
|
||||||
<a class="nav-link {% if request.resolver_match.namespace == 'pos' %}active{% endif %}" href="{% url 'pos:terminal' %}">
|
<a class="nav-link {% if request.resolver_match.namespace == 'pos' %}active{% endif %}" href="{% url 'pos:terminal' %}">
|
||||||
💰 Касса
|
Касса
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<!-- ⚙️ Настройки (только для owner/superuser) -->
|
<!-- Настройки (только для owner/superuser) -->
|
||||||
{% if request.user.is_owner or request.user.is_superuser %}
|
{% if request.user.is_owner or request.user.is_superuser %}
|
||||||
<li class="nav-item">
|
<li class="nav-item">
|
||||||
{% if request.tenant %}
|
{% if request.tenant %}
|
||||||
<a class="nav-link {% if request.resolver_match.namespace == 'system_settings' or 'user_roles' in request.resolver_match.app_names %}active{% endif %}"
|
<a class="nav-link {% if request.resolver_match.namespace == 'system_settings' or 'user_roles' in request.resolver_match.app_names %}active{% endif %}"
|
||||||
href="{% url 'system_settings:settings' %}">
|
href="{% url 'system_settings:settings' %}">
|
||||||
⚙️ Настройки
|
Настройки
|
||||||
</a>
|
</a>
|
||||||
{% else %}
|
{% else %}
|
||||||
<a class="nav-link" href="/platform/dashboard">
|
<a class="nav-link" href="/platform/dashboard">
|
||||||
⚙️ Настройки
|
Настройки
|
||||||
</a>
|
</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</li>
|
</li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<!-- 🔧 Debug (только для superuser) -->
|
<!-- Debug (для owner или manager) -->
|
||||||
{% if user.is_superuser %}
|
{% if user.is_owner or user.is_manager %}
|
||||||
{% url 'inventory:debug_page' as debug_url %}
|
{% url 'inventory:debug_page' as debug_url %}
|
||||||
{% if debug_url %}
|
{% if debug_url %}
|
||||||
<li class="nav-item">
|
<li class="nav-item">
|
||||||
<a class="nav-link" href="{{ debug_url }}" style="color: #dc3545; font-weight: bold;">
|
<a class="nav-link" href="{{ debug_url }}" style="color: #dc3545; font-weight: bold;">
|
||||||
🔧 Debug
|
Debug
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
29
prepare_js.py
Normal file
29
prepare_js.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
file_path = r'c:\Users\team_\Desktop\test_qwen\myproject\products\templates\products\productkit_edit.html'
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
except FileNotFoundError:
|
||||||
|
print(f"File not found: {file_path}")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
# Extract script part (approx lines 451 to 1321)
|
||||||
|
# Note: lines are 0-indexed in list
|
||||||
|
script_lines = lines[450:1322]
|
||||||
|
script_content = "".join(script_lines)
|
||||||
|
|
||||||
|
# Replace Django tags
|
||||||
|
# Replace {% ... %} with "TEMPLATETAG"
|
||||||
|
script_content = re.sub(r'\{%.*?%\}', '"TEMPLATETAG"', script_content)
|
||||||
|
# Replace {{ ... }} with "VARIABLE" or {}
|
||||||
|
script_content = re.sub(r'\{\{.*?\}\}', '{}', script_content)
|
||||||
|
|
||||||
|
# Save to temp js file
|
||||||
|
temp_js_path = r'c:\Users\team_\Desktop\test_qwen\temp_check.js'
|
||||||
|
with open(temp_js_path, 'w', encoding='utf-8') as f:
|
||||||
|
f.write(script_content)
|
||||||
|
|
||||||
|
print(f"Written to {temp_js_path}")
|
||||||
54
test_bouquet_api.py
Normal file
54
test_bouquet_api.py
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
"""
|
||||||
|
Простой тест для проверки API-эндпоинтов генератора названий букетов
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import django
|
||||||
|
from django.test import Client
|
||||||
|
|
||||||
|
# Настройка Django
|
||||||
|
sys.path.append(r'c:\Users\team_\Desktop\test_qwen')
|
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
||||||
|
django.setup()
|
||||||
|
|
||||||
|
def test_bouquet_api_endpoints():
|
||||||
|
client = Client()
|
||||||
|
|
||||||
|
print("Тестируем API-эндпоинты для названий букетов...")
|
||||||
|
|
||||||
|
# Тестируем получение случайных названий
|
||||||
|
print("\n1. Тестируем получение случайных названий...")
|
||||||
|
response = client.get('/products/api/bouquet-names/random/?count=3')
|
||||||
|
print(f"Статус: {response.status_code}")
|
||||||
|
if response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
print(f"Получено названий: {len(data.get('names', []))}")
|
||||||
|
print(f"Примеры: {data.get('names', [])[:2]}")
|
||||||
|
else:
|
||||||
|
print(f"Ошибка: {response.content.decode()}")
|
||||||
|
|
||||||
|
# Тестируем получение количества названий
|
||||||
|
print("\n2. Тестируем получение количества названий...")
|
||||||
|
response = client.get('/products/api/bouquet-names/count/')
|
||||||
|
print(f"Статус: {response.status_code}")
|
||||||
|
if response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
print(f"Количество названий в базе: {data.get('count', 0)}")
|
||||||
|
else:
|
||||||
|
print(f"Ошибка: {response.content.decode()}")
|
||||||
|
|
||||||
|
# Попробуем сгенерировать названия (только если есть настройки для AI)
|
||||||
|
print("\n3. Попробуем сгенерировать названия...")
|
||||||
|
try:
|
||||||
|
response = client.post('/products/api/bouquet-names/generate/', {'count': 5})
|
||||||
|
print(f"Статус: {response.status_code}")
|
||||||
|
if response.status_code == 200:
|
||||||
|
data = response.json()
|
||||||
|
print(f"Результат генерации: {data}")
|
||||||
|
else:
|
||||||
|
print(f"Ошибка генерации: {response.content.decode()}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Исключение при генерации: {e}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_bouquet_api_endpoints()
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# Скрипт деплоя для octopus (FIXED v4 - Auto-Update Compose)
|
# Скрипт деплоя для octopus (FIXED v7 - Correct paths and docker-compose)
|
||||||
LOG_FILE="/tmp/deploy-octopus.log"
|
LOG_FILE="/Volume1/DockerAppsData/mixapp/deploy-octopus.log"
|
||||||
HASH_FILE="/tmp/requirements-hash.txt"
|
HASH_FILE="/Volume1/DockerAppsData/mixapp/requirements-hash.txt"
|
||||||
DOCKER_COMPOSE_DIR="/Volume1/DockerYAML/mix"
|
DOCKER_COMPOSE_DIR="/Volume1/DockerYAML/mix"
|
||||||
APP_ROOT="/Volume1/DockerAppsData/mixapp/app"
|
APP_ROOT="/Volume1/DockerAppsData/mixapp/app"
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ echo "=== Deploy started at $(date) ===" >> "$LOG_FILE"
|
|||||||
echo "Step 1: Git pull..." >> "$LOG_FILE"
|
echo "Step 1: Git pull..." >> "$LOG_FILE"
|
||||||
docker exec git-cli sh -c "cd /git/octopus && git pull" >> "$LOG_FILE" 2>&1
|
docker exec git-cli sh -c "cd /git/octopus && git pull" >> "$LOG_FILE" 2>&1
|
||||||
|
|
||||||
# 2. Вычисляем общий хеш (requirements + docker config + docker-compose)
|
# 2. Вычисляем общий хеш (requirements + docker config + docker-compose.yml)
|
||||||
echo "Step 2: Checking for structural changes..." >> "$LOG_FILE"
|
echo "Step 2: Checking for structural changes..." >> "$LOG_FILE"
|
||||||
NEW_HASH=$(docker exec git-cli sh -c "cd /git/octopus && cat myproject/requirements.txt docker/* docker/docker-compose.yml | md5sum" | awk '{print $1}')
|
NEW_HASH=$(docker exec git-cli sh -c "cd /git/octopus && cat myproject/requirements.txt docker/* docker/docker-compose.yml | md5sum" | awk '{print $1}')
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user