Compare commits
14 Commits
2bc70968c3
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 2dc397b3ce | |||
| 9a7c0728f0 | |||
| 67ad0e50ee | |||
| 32bc0d2c39 | |||
| f140469a56 | |||
| d947f4eee7 | |||
| 5700314b10 | |||
| b24a0d9f21 | |||
| 034be20a5a | |||
| f75e861bb8 | |||
| 5a66d492c8 | |||
| 6cd0a945de | |||
| 41e6c33683 | |||
| bf399996b8 |
@@ -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
|
||||||
|
|||||||
@@ -366,7 +366,7 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
# === ЗАЩИТА ОТ ПРЕЖДЕВРЕМЕННОГО СОЗДАНИЯ SALE ===
|
# === ЗАЩИТА ОТ ПРЕЖДЕВРЕМЕННОГО СОЗДАНИЯ SALE ===
|
||||||
# Проверяем, есть ли уже Sale для этого заказа
|
# Проверяем, есть ли уже Sale для этого заказа
|
||||||
if Sale.objects.filter(order=instance).exists():
|
if Sale.objects.filter(order=instance).exists():
|
||||||
logger.info(f"✓ Заказ {instance.order_number}: Sale уже существуют, пропускаем")
|
logger.info(f"Заказ {instance.order_number}: Sale уже существуют, пропускаем")
|
||||||
update_is_returned_flag(instance)
|
update_is_returned_flag(instance)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -376,7 +376,7 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
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..."
|
||||||
)
|
)
|
||||||
if Sale.objects.filter(order=instance).exists():
|
if Sale.objects.filter(order=instance).exists():
|
||||||
@@ -454,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,
|
||||||
@@ -472,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(
|
||||||
@@ -548,6 +602,21 @@ def create_sale_on_order_completion(sender, instance, created, **kwargs):
|
|||||||
else:
|
else:
|
||||||
base_price = price_with_discount
|
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,
|
||||||
|
|||||||
@@ -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');
|
||||||
|
|||||||
@@ -20,10 +20,12 @@
|
|||||||
<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-chevron-down" id="document-info-collapse-icon"></i>
|
||||||
|
<span>
|
||||||
<i class="bi bi-file-earmark-plus me-2"></i>{{ document.document_number }}
|
<i class="bi bi-file-earmark-plus me-2"></i>{{ document.document_number }}
|
||||||
{% if document.status == 'draft' %}
|
{% if document.status == 'draft' %}
|
||||||
<span class="badge bg-warning text-dark ms-2">Черновик</span>
|
<span class="badge bg-warning text-dark ms-2">Черновик</span>
|
||||||
@@ -32,7 +34,8 @@
|
|||||||
{% elif document.status == 'cancelled' %}
|
{% elif document.status == 'cancelled' %}
|
||||||
<span class="badge bg-secondary ms-2">Отменён</span>
|
<span class="badge bg-secondary ms-2">Отменён</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</h5>
|
</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,6 +53,7 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="collapse" id="document-info-collapse">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="row mb-3">
|
<div class="row mb-3">
|
||||||
<div class="col-md-3">
|
<div class="col-md-3">
|
||||||
@@ -98,17 +102,18 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
<!-- Информация о выбранном товаре -->
|
<!-- Информация о выбранном товаре -->
|
||||||
@@ -217,11 +222,19 @@
|
|||||||
{% 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 %}
|
||||||
|
<span class="editable-cost-price"
|
||||||
|
data-item-id="{{ item.id }}"
|
||||||
|
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"
|
<input type="number" class="form-control form-control-sm item-cost-price-input"
|
||||||
value="{{ item.cost_price|stringformat:'g' }}" step="0.01" min="0"
|
value="{{ item.cost_price|stringformat:'g' }}" step="0.01" min="0"
|
||||||
style="display: none; width: 100px; text-align: right; margin-left: auto;">
|
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;">
|
||||||
@@ -271,24 +284,13 @@
|
|||||||
</td>
|
</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;">
|
||||||
@@ -351,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_', '');
|
||||||
@@ -416,160 +434,10 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
clearSelectedBtn.addEventListener('click', clearSelectedProduct);
|
clearSelectedBtn.addEventListener('click', clearSelectedProduct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================
|
|
||||||
// Inline редактирование позиций в таблице
|
|
||||||
// ============================================
|
|
||||||
|
|
||||||
// Хранилище оригинальных значений при редактировании
|
|
||||||
const originalValues = {};
|
|
||||||
|
|
||||||
// Обработчики для кнопок редактирования
|
|
||||||
document.querySelectorAll('.btn-edit-item').forEach(btn => {
|
|
||||||
btn.addEventListener('click', function() {
|
|
||||||
const row = this.closest('tr');
|
|
||||||
const itemId = row.dataset.itemId;
|
|
||||||
|
|
||||||
// Сохраняем оригинальные значения
|
|
||||||
originalValues[itemId] = {
|
|
||||||
quantity: row.querySelector('.item-quantity-input').value,
|
|
||||||
cost_price: row.querySelector('.item-cost-price-input').value,
|
|
||||||
notes: row.querySelector('.item-notes-input').value
|
|
||||||
};
|
|
||||||
|
|
||||||
// Переключаем в режим редактирования
|
|
||||||
toggleEditMode(row, true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Обработчики для кнопок сохранения
|
|
||||||
document.querySelectorAll('.btn-save-item').forEach(btn => {
|
|
||||||
btn.addEventListener('click', function() {
|
|
||||||
const row = this.closest('tr');
|
|
||||||
const itemId = row.dataset.itemId;
|
|
||||||
saveItemChanges(itemId, row);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Обработчики для кнопок отмены
|
|
||||||
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);
|
|
||||||
row.querySelector('td:nth-child(4) strong').textContent = totalCost;
|
|
||||||
|
|
||||||
// Выходим из режима редактирования
|
|
||||||
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>';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================
|
// ============================================
|
||||||
// Inline редактирование количества
|
// Inline редактирование количества и цены
|
||||||
// ============================================
|
// ============================================
|
||||||
|
|
||||||
function initInlineQuantityEdit() {
|
function initInlineQuantityEdit() {
|
||||||
@@ -708,14 +576,146 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
function updateTotals() {
|
||||||
// Можно реализовать пересчет итогов, если нужно
|
// Можно реализовать пересчет итогов, если нужно
|
||||||
// Пока оставим как есть, так как сервер возвращает обновленные данные
|
// Пока оставим как есть, так как сервер возвращает обновленные данные
|
||||||
}
|
}
|
||||||
|
|
||||||
// Инициализация inline редактирования количества
|
// Инициализация inline редактирования
|
||||||
initInlineQuantityEdit();
|
initInlineQuantityEdit();
|
||||||
|
initInlineCostPriceEdit();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -745,6 +745,17 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
color: #0d6efd !important;
|
color: #0d6efd !important;
|
||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Стили для редактируемой цены */
|
||||||
|
.editable-cost-price {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editable-cost-price:hover {
|
||||||
|
color: #0d6efd !important;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|||||||
@@ -19,9 +19,14 @@
|
|||||||
</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">
|
||||||
|
<i class="bi bi-chevron-down" id="info-collapse-icon"></i>
|
||||||
|
<span>Информация</span>
|
||||||
|
</button>
|
||||||
|
<div class="collapse" id="inventory-info-collapse">
|
||||||
<table class="table table-borderless">
|
<table class="table table-borderless">
|
||||||
{% if inventory.document_number %}
|
{% if inventory.document_number %}
|
||||||
<tr>
|
<tr>
|
||||||
@@ -64,6 +69,25 @@
|
|||||||
</table>
|
</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' %}
|
||||||
<!-- Информация о созданных документах -->
|
<!-- Информация о созданных документах -->
|
||||||
@@ -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' skip_stock_filter=True %}
|
{% 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 %}
|
||||||
|
|||||||
@@ -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 %}
|
||||||
|
|||||||
@@ -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())\""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -272,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
|
||||||
};
|
};
|
||||||
@@ -289,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;
|
||||||
|
|
||||||
// Проверяем это не опция "Создать нового клиента"
|
// Проверяем это не опция "Создать нового клиента"
|
||||||
@@ -1487,7 +1519,7 @@ function renderCart() {
|
|||||||
row.appendChild(deleteBtn);
|
row.appendChild(deleteBtn);
|
||||||
|
|
||||||
// Обработчик клика для редактирования товара
|
// Обработчик клика для редактирования товара
|
||||||
row.addEventListener('click', function(e) {
|
row.addEventListener('click', function (e) {
|
||||||
// Игнорируем клики на кнопки управления количеством и удаления
|
// Игнорируем клики на кнопки управления количеством и удаления
|
||||||
if (e.target.closest('button') || e.target.closest('input')) {
|
if (e.target.closest('button') || e.target.closest('input')) {
|
||||||
return;
|
return;
|
||||||
@@ -1817,7 +1849,7 @@ 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 }); // Глубокая копия объекта
|
||||||
});
|
});
|
||||||
|
|
||||||
// Генерируем название по умолчанию
|
// Генерируем название по умолчанию
|
||||||
@@ -1931,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}`;
|
||||||
@@ -2265,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';
|
||||||
@@ -2276,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';
|
||||||
@@ -2291,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/')) {
|
||||||
@@ -2307,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';
|
||||||
};
|
};
|
||||||
@@ -2316,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 = '';
|
||||||
@@ -2347,7 +2379,8 @@ document.getElementById('confirmCreateTempKit').onclick = async () => {
|
|||||||
if (item.type === 'product') {
|
if (item.type === 'product') {
|
||||||
items.push({
|
items.push({
|
||||||
product_id: item.id,
|
product_id: item.id,
|
||||||
quantity: item.qty
|
quantity: item.qty,
|
||||||
|
unit_price: item.price // Передаём изменённую цену из корзины
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -2388,10 +2421,9 @@ document.getElementById('confirmCreateTempKit').onclick = async () => {
|
|||||||
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);
|
||||||
// Если пользователь не задал свою цену, используем вычисленную
|
// Если пользователь явно указал свою цену
|
||||||
const finalSalePrice = useSalePrice ? salePrice : calculatedPrice;
|
if (useSalePrice && salePrice > 0) {
|
||||||
if (finalSalePrice > 0) {
|
formData.append('sale_price', salePrice);
|
||||||
formData.append('sale_price', finalSalePrice);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Фото: для редактирования проверяем, удалено ли оно
|
// Фото: для редактирования проверяем, удалено ли оно
|
||||||
@@ -2650,7 +2682,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();
|
||||||
|
|
||||||
@@ -2774,13 +2806,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');
|
||||||
@@ -3416,8 +3448,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();
|
||||||
@@ -3438,12 +3470,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');
|
||||||
|
|||||||
@@ -729,6 +729,28 @@
|
|||||||
|
|
||||||
<!-- Модалка редактирования товара в корзине -->
|
<!-- Модалка редактирования товара в корзине -->
|
||||||
{% include 'pos/components/edit_cart_item_modal.html' %}
|
{% 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 %}
|
||||||
|
|||||||
@@ -1163,15 +1163,20 @@ def create_temp_kit_to_showcase(request):
|
|||||||
}, status=400)
|
}, status=400)
|
||||||
|
|
||||||
# Агрегируем дубликаты (если один товар добавлен несколько раз)
|
# Агрегируем дубликаты (если один товар добавлен несколько раз)
|
||||||
|
# Сохраняем также цену из корзины (unit_price)
|
||||||
aggregated_items = {}
|
aggregated_items = {}
|
||||||
for item in items:
|
for item in items:
|
||||||
product_id = item['product_id']
|
product_id = item['product_id']
|
||||||
quantity = Decimal(str(item['quantity']))
|
quantity = Decimal(str(item['quantity']))
|
||||||
|
unit_price = item.get('unit_price') # Цена из корзины (может быть изменена пользователем)
|
||||||
|
|
||||||
if product_id in aggregated_items:
|
if product_id in aggregated_items:
|
||||||
aggregated_items[product_id] += quantity
|
aggregated_items[product_id]['quantity'] += quantity
|
||||||
else:
|
else:
|
||||||
aggregated_items[product_id] = quantity
|
aggregated_items[product_id] = {
|
||||||
|
'quantity': quantity,
|
||||||
|
'unit_price': Decimal(str(unit_price)) if unit_price is not None else None
|
||||||
|
}
|
||||||
|
|
||||||
# Создаём временный комплект и резервируем на витрину
|
# Создаём временный комплект и резервируем на витрину
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
@@ -1189,13 +1194,15 @@ def create_temp_kit_to_showcase(request):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# 2. Создаём KitItem для каждого товара из корзины
|
# 2. Создаём KitItem для каждого товара из корзины
|
||||||
for product_id, quantity in aggregated_items.items():
|
for product_id, item_data in aggregated_items.items():
|
||||||
product = products[product_id]
|
product = products[product_id]
|
||||||
|
# Используем цену из корзины, если передана, иначе из каталога
|
||||||
|
final_price = item_data['unit_price'] if item_data['unit_price'] is not None else product.actual_price
|
||||||
KitItem.objects.create(
|
KitItem.objects.create(
|
||||||
kit=kit,
|
kit=kit,
|
||||||
product=product,
|
product=product,
|
||||||
quantity=quantity,
|
quantity=item_data['quantity'],
|
||||||
unit_price=product.actual_price # Фиксируем цену для временного комплекта
|
unit_price=final_price # Фиксируем цену из корзины (с учётом изменений пользователя)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 3. Пересчитываем цену комплекта
|
# 3. Пересчитываем цену комплекта
|
||||||
@@ -1264,7 +1271,7 @@ def create_temp_kit_to_showcase(request):
|
|||||||
f' Название: {request.POST.get("kit_name")}\n'
|
f' Название: {request.POST.get("kit_name")}\n'
|
||||||
f' Витрина ID: {request.POST.get("showcase_id")}\n'
|
f' Витрина ID: {request.POST.get("showcase_id")}\n'
|
||||||
f' Товары: {request.POST.get("items")}\n'
|
f' Товары: {request.POST.get("items")}\n'
|
||||||
f' Пользователь: {request.user.username}\n'
|
f' Пользователь: {str(request.user)}\n'
|
||||||
f' Ошибка: {str(e)}',
|
f' Ошибка: {str(e)}',
|
||||||
exc_info=True
|
exc_info=True
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -230,6 +230,10 @@ class ProductKit(BaseProductEntity):
|
|||||||
qty = item.quantity or Decimal('1')
|
qty = item.quantity or Decimal('1')
|
||||||
total += actual_price * qty
|
total += actual_price * qty
|
||||||
elif item.product:
|
elif item.product:
|
||||||
|
# Используем зафиксированную цену (unit_price) если задана, иначе актуальную цену товара
|
||||||
|
if item.unit_price is not None:
|
||||||
|
actual_price = item.unit_price
|
||||||
|
else:
|
||||||
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
|
||||||
@@ -340,17 +344,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):
|
||||||
"""
|
"""
|
||||||
Создает снимок текущего состояния комплекта.
|
Создает снимок текущего состояния комплекта.
|
||||||
|
|||||||
@@ -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;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Принудительно снять выделение со всех товаров
|
* Принудительно снять выделение со всех товаров
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -76,7 +76,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Загрузка с устройства -->
|
<!-- Загрузка с устройства -->
|
||||||
<input type="file" name="photos" accept="image/*" multiple class="form-control form-control-sm" id="id_photos">
|
<input type="file" name="photos" accept="image/*" multiple class="form-control form-control-sm"
|
||||||
|
id="id_photos">
|
||||||
<div id="photoPreviewContainer" class="mt-2" style="display: none;">
|
<div id="photoPreviewContainer" class="mt-2" style="display: none;">
|
||||||
<div id="photoPreview" class="row g-1"></div>
|
<div id="photoPreview" class="row g-1"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -97,7 +98,8 @@
|
|||||||
<div class="card-body p-3">
|
<div class="card-body p-3">
|
||||||
<p class="small text-muted mb-3">
|
<p class="small text-muted mb-3">
|
||||||
Сгенерируйте привлекательное название для вашего букета автоматически
|
Сгенерируйте привлекательное название для вашего букета автоматически
|
||||||
<br><span class="badge bg-secondary mt-1">В базе: <span id="bouquetNamesCount">{{ bouquet_names_count }}</span> названий</span>
|
<br><span class="badge bg-secondary mt-1">В базе: <span id="bouquetNamesCount">{{
|
||||||
|
bouquet_names_count }}</span> названий</span>
|
||||||
</p>
|
</p>
|
||||||
<div class="d-flex gap-2 mb-4">
|
<div class="d-flex gap-2 mb-4">
|
||||||
<button type="button" class="btn btn-outline-primary btn-sm" id="populateNamesBtn">
|
<button type="button" class="btn btn-outline-primary btn-sm" id="populateNamesBtn">
|
||||||
@@ -111,27 +113,36 @@
|
|||||||
<!-- Предложения названий -->
|
<!-- Предложения названий -->
|
||||||
<div class="name-suggestions">
|
<div class="name-suggestions">
|
||||||
<!-- Строка 1 -->
|
<!-- Строка 1 -->
|
||||||
<div class="d-flex justify-content-between align-items-center py-2 border-bottom name-row" data-name-id="">
|
<div class="d-flex justify-content-between align-items-center py-2 border-bottom name-row"
|
||||||
|
data-name-id="">
|
||||||
<span class="text-muted small name-text">-</span>
|
<span class="text-muted small name-text">-</span>
|
||||||
<div class="d-flex gap-1 name-buttons" style="display: none;">
|
<div class="d-flex gap-1 name-buttons" style="display: none;">
|
||||||
<button type="button" class="btn btn-success btn-xs btn-take-name">Взять</button>
|
<button type="button"
|
||||||
<button type="button" class="btn btn-outline-danger btn-xs btn-delete-name">Удалить</button>
|
class="btn btn-success btn-xs btn-take-name">Взять</button>
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-outline-danger btn-xs btn-delete-name">Удалить</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Строка 2 -->
|
<!-- Строка 2 -->
|
||||||
<div class="d-flex justify-content-between align-items-center py-2 border-bottom name-row" data-name-id="">
|
<div class="d-flex justify-content-between align-items-center py-2 border-bottom name-row"
|
||||||
|
data-name-id="">
|
||||||
<span class="text-muted small name-text">-</span>
|
<span class="text-muted small name-text">-</span>
|
||||||
<div class="d-flex gap-1 name-buttons" style="display: none;">
|
<div class="d-flex gap-1 name-buttons" style="display: none;">
|
||||||
<button type="button" class="btn btn-success btn-xs btn-take-name">Взять</button>
|
<button type="button"
|
||||||
<button type="button" class="btn btn-outline-danger btn-xs btn-delete-name">Удалить</button>
|
class="btn btn-success btn-xs btn-take-name">Взять</button>
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-outline-danger btn-xs btn-delete-name">Удалить</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Строка 3 -->
|
<!-- Строка 3 -->
|
||||||
<div class="d-flex justify-content-between align-items-center py-2 name-row" data-name-id="">
|
<div class="d-flex justify-content-between align-items-center py-2 name-row"
|
||||||
|
data-name-id="">
|
||||||
<span class="text-muted small name-text">-</span>
|
<span class="text-muted small name-text">-</span>
|
||||||
<div class="d-flex gap-1 name-buttons" style="display: none;">
|
<div class="d-flex gap-1 name-buttons" style="display: none;">
|
||||||
<button type="button" class="btn btn-success btn-xs btn-take-name">Взять</button>
|
<button type="button"
|
||||||
<button type="button" class="btn btn-outline-danger btn-xs btn-delete-name">Удалить</button>
|
class="btn btn-success btn-xs btn-take-name">Взять</button>
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-outline-danger btn-xs btn-delete-name">Удалить</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -154,8 +165,10 @@
|
|||||||
<!-- Базовая цена (отображение) -->
|
<!-- Базовая цена (отображение) -->
|
||||||
<div class="mb-3 p-2 rounded" style="background: #f8f9fa; border-left: 3px solid #6c757d;">
|
<div class="mb-3 p-2 rounded" style="background: #f8f9fa; border-left: 3px solid #6c757d;">
|
||||||
<div class="d-flex justify-content-between align-items-center">
|
<div class="d-flex justify-content-between align-items-center">
|
||||||
<span class="text-muted small"><i class="bi bi-calculator"></i> Сумма цен компонентов:</span>
|
<span class="text-muted small"><i class="bi bi-calculator"></i> Сумма цен
|
||||||
<span id="basePriceDisplay" class="fw-semibold" style="font-size: 1.1rem;">0.00 руб.</span>
|
компонентов:</span>
|
||||||
|
<span id="basePriceDisplay" class="fw-semibold" style="font-size: 1.1rem;">0.00
|
||||||
|
руб.</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -169,13 +182,15 @@
|
|||||||
<div class="row g-2">
|
<div class="row g-2">
|
||||||
<div class="col-6">
|
<div class="col-6">
|
||||||
<div class="input-group input-group-sm">
|
<div class="input-group input-group-sm">
|
||||||
<input type="number" id="id_increase_percent" class="form-control" placeholder="%" step="0.01" min="0">
|
<input type="number" id="id_increase_percent" class="form-control"
|
||||||
|
placeholder="%" step="0.01" min="0">
|
||||||
<span class="input-group-text">%</span>
|
<span class="input-group-text">%</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-6">
|
<div class="col-6">
|
||||||
<div class="input-group input-group-sm">
|
<div class="input-group input-group-sm">
|
||||||
<input type="number" id="id_increase_amount" class="form-control" placeholder="руб" step="0.01" min="0">
|
<input type="number" id="id_increase_amount" class="form-control"
|
||||||
|
placeholder="руб" step="0.01" min="0">
|
||||||
<span class="input-group-text">руб</span>
|
<span class="input-group-text">руб</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -191,13 +206,15 @@
|
|||||||
<div class="row g-2">
|
<div class="row g-2">
|
||||||
<div class="col-6">
|
<div class="col-6">
|
||||||
<div class="input-group input-group-sm">
|
<div class="input-group input-group-sm">
|
||||||
<input type="number" id="id_decrease_percent" class="form-control" placeholder="%" step="0.01" min="0">
|
<input type="number" id="id_decrease_percent" class="form-control"
|
||||||
|
placeholder="%" step="0.01" min="0">
|
||||||
<span class="input-group-text">%</span>
|
<span class="input-group-text">%</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-6">
|
<div class="col-6">
|
||||||
<div class="input-group input-group-sm">
|
<div class="input-group input-group-sm">
|
||||||
<input type="number" id="id_decrease_amount" class="form-control" placeholder="руб" step="0.01" min="0">
|
<input type="number" id="id_decrease_amount" class="form-control"
|
||||||
|
placeholder="руб" step="0.01" min="0">
|
||||||
<span class="input-group-text">руб</span>
|
<span class="input-group-text">руб</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -210,8 +227,10 @@
|
|||||||
<!-- Итоговая цена -->
|
<!-- Итоговая цена -->
|
||||||
<div class="p-2 rounded" style="background: #e7f5e7; border-left: 3px solid #198754;">
|
<div class="p-2 rounded" style="background: #e7f5e7; border-left: 3px solid #198754;">
|
||||||
<div class="d-flex justify-content-between align-items-center">
|
<div class="d-flex justify-content-between align-items-center">
|
||||||
<span class="text-dark small"><i class="bi bi-check-circle me-1"></i><strong>Итоговая цена:</strong></span>
|
<span class="text-dark small"><i class="bi bi-check-circle me-1"></i><strong>Итоговая
|
||||||
<span id="finalPriceDisplay" class="fw-bold" style="font-size: 1.3rem; color: #198754;">0.00 руб.</span>
|
цена:</strong></span>
|
||||||
|
<span id="finalPriceDisplay" class="fw-bold"
|
||||||
|
style="font-size: 1.3rem; color: #198754;">0.00 руб.</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -227,7 +246,8 @@
|
|||||||
<h6 class="mb-2 text-muted"><i class="bi bi-tag-discount"></i> Цена со скидкой</h6>
|
<h6 class="mb-2 text-muted"><i class="bi bi-tag-discount"></i> Цена со скидкой</h6>
|
||||||
<label class="form-label small mb-1">{{ form.sale_price.label }}</label>
|
<label class="form-label small mb-1">{{ form.sale_price.label }}</label>
|
||||||
{{ form.sale_price }}
|
{{ form.sale_price }}
|
||||||
<small class="form-text text-muted">Если указана, будет использоваться вместо расчетной цены</small>
|
<small class="form-text text-muted">Если указана, будет использоваться вместо расчетной
|
||||||
|
цены</small>
|
||||||
{% if form.sale_price.errors %}
|
{% if form.sale_price.errors %}
|
||||||
<div class="text-danger small mt-1">{{ form.sale_price.errors }}</div>
|
<div class="text-danger small mt-1">{{ form.sale_price.errors }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -296,7 +316,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Sticky Footer -->
|
<!-- Sticky Footer -->
|
||||||
<div class="sticky-bottom bg-white border-top mt-4 p-3 d-flex justify-content-between align-items-center shadow-sm">
|
<div
|
||||||
|
class="sticky-bottom bg-white border-top mt-4 p-3 d-flex justify-content-between align-items-center shadow-sm">
|
||||||
<a href="{% url 'products:products-list' %}" class="btn btn-outline-secondary">
|
<a href="{% url 'products:products-list' %}" class="btn btn-outline-secondary">
|
||||||
Отмена
|
Отмена
|
||||||
</a>
|
</a>
|
||||||
@@ -308,14 +329,14 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
/* Breadcrumbs */
|
/* Breadcrumbs */
|
||||||
.breadcrumb-sm {
|
.breadcrumb-sm {
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
padding: 0.5rem 0;
|
padding: 0.5rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Крупное поле названия */
|
/* Крупное поле названия */
|
||||||
#id_name {
|
#id_name {
|
||||||
font-size: 1.5rem;
|
font-size: 1.5rem;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
border: 3px solid #dee2e6;
|
border: 3px solid #dee2e6;
|
||||||
@@ -323,222 +344,229 @@
|
|||||||
padding: 0.75rem 1rem;
|
padding: 0.75rem 1rem;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
|
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
|
||||||
}
|
}
|
||||||
|
|
||||||
#id_name:focus {
|
#id_name:focus {
|
||||||
border-color: #198754;
|
border-color: #198754;
|
||||||
box-shadow: 0 0 0 0.25rem rgba(25, 135, 84, 0.15);
|
box-shadow: 0 0 0 0.25rem rgba(25, 135, 84, 0.15);
|
||||||
outline: 0;
|
outline: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Описание */
|
/* Описание */
|
||||||
#id_description {
|
#id_description {
|
||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
min-height: 80px;
|
min-height: 80px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Компактные чекбоксы */
|
/* Компактные чекбоксы */
|
||||||
.compact-checkboxes {
|
.compact-checkboxes {
|
||||||
max-height: 200px;
|
max-height: 200px;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.compact-checkboxes ul {
|
.compact-checkboxes ul {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.compact-checkboxes li {
|
.compact-checkboxes li {
|
||||||
padding: 0.25rem 0;
|
padding: 0.25rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.compact-checkboxes label {
|
.compact-checkboxes label {
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Компонент комплекта */
|
/* Компонент комплекта */
|
||||||
.kititem-form {
|
.kititem-form {
|
||||||
transition: all 0.2s;
|
transition: all 0.2s;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kititem-form:hover {
|
.kititem-form:hover {
|
||||||
box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075) !important;
|
box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kititem-form .card-body {
|
.kititem-form .card-body {
|
||||||
background: #fafbfc;
|
background: #fafbfc;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kititem-form input[type="checkbox"][name$="-DELETE"] {
|
.kititem-form input[type="checkbox"][name$="-DELETE"] {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Sticky footer */
|
/* Sticky footer */
|
||||||
.sticky-bottom {
|
.sticky-bottom {
|
||||||
position: sticky;
|
position: sticky;
|
||||||
bottom: 0;
|
bottom: 0;
|
||||||
z-index: 1020;
|
z-index: 1020;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Карточки */
|
/* Карточки */
|
||||||
.card.border-0 {
|
.card.border-0 {
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Лейблы */
|
/* Лейблы */
|
||||||
.form-label.small {
|
.form-label.small {
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: #6c757d;
|
color: #6c757d;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.5px;
|
letter-spacing: 0.5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Фото превью */
|
/* Фото превью */
|
||||||
#photoPreview .col-4,
|
#photoPreview .col-4,
|
||||||
#photoPreview .col-md-3,
|
#photoPreview .col-md-3,
|
||||||
#photoPreview .col-lg-2 {
|
#photoPreview .col-lg-2 {
|
||||||
padding: 0.25rem;
|
padding: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
#photoPreview .card {
|
#photoPreview .card {
|
||||||
border-radius: 0.375rem;
|
border-radius: 0.375rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
#photoPreview img {
|
#photoPreview img {
|
||||||
height: 100px;
|
height: 100px;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Alert компактный */
|
/* Alert компактный */
|
||||||
.alert-sm {
|
.alert-sm {
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Анимация */
|
/* Анимация */
|
||||||
@keyframes slideIn {
|
@keyframes slideIn {
|
||||||
from {
|
from {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transform: translateY(-10px);
|
transform: translateY(-10px);
|
||||||
}
|
}
|
||||||
|
|
||||||
to {
|
to {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
transform: translateY(0);
|
transform: translateY(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.kititem-form.new-item {
|
.kititem-form.new-item {
|
||||||
animation: slideIn 0.3s ease-out;
|
animation: slideIn 0.3s ease-out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Разделитель ИЛИ */
|
/* Разделитель ИЛИ */
|
||||||
.kit-item-separator {
|
.kit-item-separator {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
min-height: 40px;
|
min-height: 40px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kit-item-separator .separator-text {
|
.kit-item-separator .separator-text {
|
||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #adb5bd;
|
color: #adb5bd;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 1px;
|
letter-spacing: 1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kit-item-separator .separator-help {
|
.kit-item-separator .separator-help {
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
color: #6c757d;
|
color: #6c757d;
|
||||||
cursor: help;
|
cursor: help;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kit-item-separator .separator-help:hover {
|
.kit-item-separator .separator-help:hover {
|
||||||
color: #0d6efd;
|
color: #0d6efd;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Стили для генератора названий */
|
/* Стили для генератора названий */
|
||||||
.cursor-pointer {
|
.cursor-pointer {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-header[data-bs-toggle="collapse"]:hover {
|
.card-header[data-bs-toggle="collapse"]:hover {
|
||||||
background-color: #f8f9fa;
|
background-color: #f8f9fa;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-header[data-bs-toggle="collapse"] .bi-chevron-down {
|
.card-header[data-bs-toggle="collapse"] .bi-chevron-down {
|
||||||
transition: transform 0.2s ease;
|
transition: transform 0.2s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
.collapse.show .card-header[data-bs-toggle="collapse"] .bi-chevron-down {
|
.collapse.show .card-header[data-bs-toggle="collapse"] .bi-chevron-down {
|
||||||
transform: rotate(180deg);
|
transform: rotate(180deg);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Кнопки очень маленького размера */
|
/* Кнопки очень маленького размера */
|
||||||
.btn-xs {
|
.btn-xs {
|
||||||
padding: 0.125rem 0.25rem;
|
padding: 0.125rem 0.25rem;
|
||||||
font-size: 0.75rem;
|
font-size: 0.75rem;
|
||||||
line-height: 1;
|
line-height: 1;
|
||||||
border-radius: 0.2rem;
|
border-radius: 0.2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-xs:hover {
|
.btn-xs:hover {
|
||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Стили для списка предложений */
|
/* Стили для списка предложений */
|
||||||
.name-suggestions {
|
.name-suggestions {
|
||||||
background-color: #f8f9fa;
|
background-color: #f8f9fa;
|
||||||
border-radius: 0.375rem;
|
border-radius: 0.375rem;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.name-suggestions .text-muted {
|
.name-suggestions .text-muted {
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.name-suggestions .border-bottom {
|
.name-suggestions .border-bottom {
|
||||||
border-color: #e9ecef !important;
|
border-color: #e9ecef !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Стили для полей корректировки цены */
|
/* Стили для полей корректировки цены */
|
||||||
#id_increase_percent:disabled,
|
#id_increase_percent:disabled,
|
||||||
#id_increase_amount:disabled,
|
#id_increase_amount:disabled,
|
||||||
#id_decrease_percent:disabled,
|
#id_decrease_percent:disabled,
|
||||||
#id_decrease_amount:disabled {
|
#id_decrease_amount:disabled {
|
||||||
background-color: #e9ecef;
|
background-color: #e9ecef;
|
||||||
color: #6c757d;
|
color: #6c757d;
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
#id_increase_percent.is-invalid,
|
#id_increase_percent.is-invalid,
|
||||||
#id_increase_amount.is-invalid,
|
#id_increase_amount.is-invalid,
|
||||||
#id_decrease_percent.is-invalid,
|
#id_decrease_percent.is-invalid,
|
||||||
#id_decrease_amount.is-invalid {
|
#id_decrease_amount.is-invalid {
|
||||||
border-color: #dc3545;
|
border-color: #dc3545;
|
||||||
box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
|
box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Адаптивность */
|
/* Адаптивность */
|
||||||
@media (max-width: 991px) {
|
@media (max-width: 991px) {
|
||||||
.col-lg-8, .col-lg-4 {
|
|
||||||
|
.col-lg-8,
|
||||||
|
.col-lg-4 {
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<!-- Select2 инициализация -->
|
<!-- Select2 инициализация -->
|
||||||
{% include 'products/includes/select2-product-init.html' %}
|
{% include 'products/includes/select2-product-init.html' %}
|
||||||
|
|
||||||
|
{{ selected_products|default:"{}"|json_script:"selected-products-data" }}
|
||||||
|
{{ selected_variants|default:"{}"|json_script:"selected-variants-data" }}
|
||||||
|
{{ selected_sales_units|default:"{}"|json_script:"selected-sales-units-data" }}
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
// ========== УПРАВЛЕНИЕ ЦЕНОЙ КОМПЛЕКТА ==========
|
// ========== УПРАВЛЕНИЕ ЦЕНОЙ КОМПЛЕКТА ==========
|
||||||
const increasePercentInput = document.getElementById('id_increase_percent');
|
const increasePercentInput = document.getElementById('id_increase_percent');
|
||||||
const increaseAmountInput = document.getElementById('id_increase_amount');
|
const increaseAmountInput = document.getElementById('id_increase_amount');
|
||||||
@@ -550,6 +578,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
const finalPriceDisplay = document.getElementById('finalPriceDisplay');
|
const finalPriceDisplay = document.getElementById('finalPriceDisplay');
|
||||||
|
|
||||||
let basePrice = 0;
|
let basePrice = 0;
|
||||||
|
let activeUpdates = 0; // Счетчик активных обновлений
|
||||||
|
|
||||||
// Кэш цен товаров для быстрого доступа
|
// Кэш цен товаров для быстрого доступа
|
||||||
const priceCache = {};
|
const priceCache = {};
|
||||||
@@ -743,6 +772,19 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
// Функция для обновления списка единиц продажи при выборе товара
|
// Функция для обновления списка единиц продажи при выборе товара
|
||||||
async function updateSalesUnitsOptions(salesUnitSelect, productValue) {
|
async function updateSalesUnitsOptions(salesUnitSelect, productValue) {
|
||||||
|
activeUpdates++; // Начинаем обновление
|
||||||
|
try {
|
||||||
|
// Сохраняем текущее значение перед очисткой (важно для редактирования и копирования)
|
||||||
|
let targetValue = salesUnitSelect.value;
|
||||||
|
|
||||||
|
// Если значения нет, проверяем preloaded данные (фаллбэк для инициализации)
|
||||||
|
if (!targetValue) {
|
||||||
|
const fieldName = salesUnitSelect.name;
|
||||||
|
if (selectedSalesUnits && selectedSalesUnits[fieldName]) {
|
||||||
|
targetValue = selectedSalesUnits[fieldName].id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Очищаем текущие опции
|
// Очищаем текущие опции
|
||||||
salesUnitSelect.innerHTML = '<option value="">---------</option>';
|
salesUnitSelect.innerHTML = '<option value="">---------</option>';
|
||||||
salesUnitSelect.disabled = true;
|
salesUnitSelect.disabled = true;
|
||||||
@@ -761,7 +803,6 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isNaN(productId) || productId <= 0) {
|
if (isNaN(productId) || productId <= 0) {
|
||||||
console.warn('updateSalesUnitsOptions: invalid product id', productValue);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -783,17 +824,29 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
salesUnitSelect.appendChild(option);
|
salesUnitSelect.appendChild(option);
|
||||||
});
|
});
|
||||||
salesUnitSelect.disabled = false;
|
salesUnitSelect.disabled = false;
|
||||||
// Обновляем Select2
|
|
||||||
|
// Восстанавливаем значение
|
||||||
|
if (targetValue) {
|
||||||
|
$(salesUnitSelect).val(targetValue).trigger('change');
|
||||||
|
} else {
|
||||||
|
// Обновляем Select2 без значения
|
||||||
$(salesUnitSelect).trigger('change');
|
$(salesUnitSelect).trigger('change');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching sales units:', error);
|
console.error('Error fetching sales units:', error);
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
activeUpdates--; // Завершаем обновление
|
||||||
|
if (activeUpdates === 0) {
|
||||||
|
calculateFinalPrice();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Обновляем data-product-id и загружаем цену при выборе товара
|
// Обновляем data-product-id и загружаем цену при выборе товара
|
||||||
$('[name$="-product"]').on('select2:select', async function() {
|
$('[name$="-product"]').on('select2:select', async function () {
|
||||||
const form = $(this).closest('.kititem-form');
|
const form = $(this).closest('.kititem-form');
|
||||||
if (this.value) {
|
if (this.value) {
|
||||||
// Извлекаем числовой ID из "product_123"
|
// Извлекаем числовой ID из "product_123"
|
||||||
@@ -809,9 +862,9 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
if (salesUnitSelect) {
|
if (salesUnitSelect) {
|
||||||
await updateSalesUnitsOptions(salesUnitSelect, this.value);
|
await updateSalesUnitsOptions(salesUnitSelect, this.value);
|
||||||
}
|
}
|
||||||
calculateFinalPrice();
|
|
||||||
}
|
}
|
||||||
}).on('select2:unselect', function() {
|
calculateFinalPrice();
|
||||||
|
}).on('select2:unselect', function () {
|
||||||
const form = $(this).closest('.kititem-form');
|
const form = $(this).closest('.kititem-form');
|
||||||
// Очищаем список единиц продажи
|
// Очищаем список единиц продажи
|
||||||
const salesUnitSelect = form.find('[name$="-sales_unit"]')[0];
|
const salesUnitSelect = form.find('[name$="-sales_unit"]')[0];
|
||||||
@@ -885,6 +938,11 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
// Функция для расчета финальной цены
|
// Функция для расчета финальной цены
|
||||||
async function calculateFinalPrice() {
|
async function calculateFinalPrice() {
|
||||||
|
// Если идут обновления - не считаем, ждем их завершения
|
||||||
|
if (activeUpdates > 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Получаем базовую цену (сумма всех компонентов)
|
// Получаем базовую цену (сумма всех компонентов)
|
||||||
let newBasePrice = 0;
|
let newBasePrice = 0;
|
||||||
const formsContainer = document.getElementById('kititem-forms');
|
const formsContainer = document.getElementById('kititem-forms');
|
||||||
@@ -1060,8 +1118,8 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Инициальный расчет (асинхронно)
|
// Инициальный расчет не нужен, так как он выполняется по событиям изменения полей
|
||||||
calculateFinalPrice();
|
// и после завершения загрузки единиц продажи
|
||||||
|
|
||||||
// ========== SELECT2 ИНИЦИАЛИЗАЦИЯ ==========
|
// ========== SELECT2 ИНИЦИАЛИЗАЦИЯ ==========
|
||||||
function initSelect2(element, type, preloadedData) {
|
function initSelect2(element, type, preloadedData) {
|
||||||
@@ -1072,23 +1130,23 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectedProducts = {{ selected_products|default:"{}"|safe }};
|
const selectedProducts = JSON.parse(document.getElementById('selected-products-data').textContent || '{}');
|
||||||
const selectedVariants = {{ selected_variants|default:"{}"|safe }};
|
const selectedVariants = JSON.parse(document.getElementById('selected-variants-data').textContent || '{}');
|
||||||
const selectedSalesUnits = {{ selected_sales_units|default:"{}"|safe }};
|
const selectedSalesUnits = JSON.parse(document.getElementById('selected-sales-units-data').textContent || '{}');
|
||||||
|
|
||||||
$('[name$="-product"]').each(function() {
|
$('[name$="-product"]').each(function () {
|
||||||
const fieldName = $(this).attr('name');
|
const fieldName = $(this).attr('name');
|
||||||
const preloadedData = selectedProducts[fieldName] || null;
|
const preloadedData = selectedProducts[fieldName] || null;
|
||||||
initSelect2(this, 'product', preloadedData);
|
initSelect2(this, 'product', preloadedData);
|
||||||
// Обработчик уже добавлен выше (строки 673-701)
|
// Обработчик уже добавлен выше (строки 673-701)
|
||||||
});
|
});
|
||||||
|
|
||||||
$('[name$="-variant_group"]').each(function() {
|
$('[name$="-variant_group"]').each(function () {
|
||||||
const fieldName = $(this).attr('name');
|
const fieldName = $(this).attr('name');
|
||||||
const preloadedData = selectedVariants[fieldName] || null;
|
const preloadedData = selectedVariants[fieldName] || null;
|
||||||
initSelect2(this, 'variant', preloadedData);
|
initSelect2(this, 'variant', preloadedData);
|
||||||
// При выборе варианта очищаем единицу продажи
|
// При выборе варианта очищаем единицу продажи
|
||||||
$(this).on('select2:select', function() {
|
$(this).on('select2:select', function () {
|
||||||
const form = $(this).closest('.kititem-form');
|
const form = $(this).closest('.kititem-form');
|
||||||
const salesUnitSelect = form.find('[name$="-sales_unit"]')[0];
|
const salesUnitSelect = form.find('[name$="-sales_unit"]')[0];
|
||||||
if (salesUnitSelect) {
|
if (salesUnitSelect) {
|
||||||
@@ -1099,7 +1157,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}).on('select2:unselect', calculateFinalPrice);
|
}).on('select2:unselect', calculateFinalPrice);
|
||||||
});
|
});
|
||||||
|
|
||||||
$('[name$="-sales_unit"]').each(function() {
|
$('[name$="-sales_unit"]').each(function () {
|
||||||
const fieldName = $(this).attr('name');
|
const fieldName = $(this).attr('name');
|
||||||
const preloadedData = selectedSalesUnits[fieldName] || null;
|
const preloadedData = selectedSalesUnits[fieldName] || null;
|
||||||
initSelect2(this, 'sales_unit', preloadedData);
|
initSelect2(this, 'sales_unit', preloadedData);
|
||||||
@@ -1169,7 +1227,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
if (quantityInput) {
|
if (quantityInput) {
|
||||||
quantityInput.addEventListener('change', calculateFinalPrice);
|
quantityInput.addEventListener('change', calculateFinalPrice);
|
||||||
// Выделяем весь текст при фокусе на поле количества
|
// Выделяем весь текст при фокусе на поле количества
|
||||||
quantityInput.addEventListener('focus', function() {
|
quantityInput.addEventListener('focus', function () {
|
||||||
this.select();
|
this.select();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1238,7 +1296,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
initSelect2(salesUnitSelect, 'sales_unit');
|
initSelect2(salesUnitSelect, 'sales_unit');
|
||||||
|
|
||||||
// Добавляем обработчики для новой формы (как в основном коде)
|
// Добавляем обработчики для новой формы (как в основном коде)
|
||||||
$(productSelect).on('select2:select', async function() {
|
$(productSelect).on('select2:select', async function () {
|
||||||
const form = $(this).closest('.kititem-form');
|
const form = $(this).closest('.kititem-form');
|
||||||
if (this.value) {
|
if (this.value) {
|
||||||
let numericId = this.value;
|
let numericId = this.value;
|
||||||
@@ -1252,7 +1310,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
calculateFinalPrice();
|
calculateFinalPrice();
|
||||||
}).on('select2:unselect', function() {
|
}).on('select2:unselect', function () {
|
||||||
if (salesUnitSelect) {
|
if (salesUnitSelect) {
|
||||||
salesUnitSelect.innerHTML = '<option value="">---------</option>';
|
salesUnitSelect.innerHTML = '<option value="">---------</option>';
|
||||||
$(salesUnitSelect).trigger('change');
|
$(salesUnitSelect).trigger('change');
|
||||||
@@ -1260,7 +1318,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
calculateFinalPrice();
|
calculateFinalPrice();
|
||||||
});
|
});
|
||||||
|
|
||||||
$(variantSelect).on('select2:select', function() {
|
$(variantSelect).on('select2:select', function () {
|
||||||
if (salesUnitSelect) {
|
if (salesUnitSelect) {
|
||||||
salesUnitSelect.innerHTML = '<option value="">---------</option>';
|
salesUnitSelect.innerHTML = '<option value="">---------</option>';
|
||||||
$(salesUnitSelect).trigger('change');
|
$(salesUnitSelect).trigger('change');
|
||||||
@@ -1290,7 +1348,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
let selectedFiles = [];
|
let selectedFiles = [];
|
||||||
|
|
||||||
if (photoInput) {
|
if (photoInput) {
|
||||||
photoInput.addEventListener('change', function(e) {
|
photoInput.addEventListener('change', function (e) {
|
||||||
selectedFiles = Array.from(e.target.files);
|
selectedFiles = Array.from(e.target.files);
|
||||||
|
|
||||||
if (selectedFiles.length > 0) {
|
if (selectedFiles.length > 0) {
|
||||||
@@ -1299,7 +1357,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
|
|
||||||
selectedFiles.forEach((file, index) => {
|
selectedFiles.forEach((file, index) => {
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onload = function(event) {
|
reader.onload = function (event) {
|
||||||
const col = document.createElement('div');
|
const col = document.createElement('div');
|
||||||
col.className = 'col-4 col-md-3 col-lg-2';
|
col.className = 'col-4 col-md-3 col-lg-2';
|
||||||
col.innerHTML = `
|
col.innerHTML = `
|
||||||
@@ -1315,13 +1373,39 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
reader.readAsDataURL(file);
|
reader.readAsDataURL(file);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
photoPreviewContainer.style.display = 'none';
|
photoPreviewContainer.style.display = 'none'; // Only hide if no source photos too (will check later)
|
||||||
photoPreview.innerHTML = '';
|
photoPreview.innerHTML = '';
|
||||||
|
|
||||||
|
// Re-render source photos if they exist and we just cleared new files
|
||||||
|
if (document.querySelectorAll('.source-photo-item').length > 0) {
|
||||||
|
photoPreviewContainer.style.display = 'block';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
window.removePhoto = function(index) {
|
// Render source photos if present
|
||||||
|
{% if source_photos %}
|
||||||
|
photoPreviewContainer.style.display = 'block';
|
||||||
|
{% for photo in source_photos %}
|
||||||
|
(function () {
|
||||||
|
const col = document.createElement('div');
|
||||||
|
col.className = 'col-4 col-md-3 col-lg-2 source-photo-item';
|
||||||
|
col.innerHTML = `
|
||||||
|
<div class="card position-relative border-0 shadow-sm">
|
||||||
|
<img src="{{ photo.image.url }}" class="card-img-top" alt="Source Photo">
|
||||||
|
<button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1" onclick="this.closest('.col-4').remove();">
|
||||||
|
<i class="bi bi-x"></i>
|
||||||
|
</button>
|
||||||
|
<input type="hidden" name="copied_photos" value="{{ photo.id }}">
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
photoPreview.appendChild(col);
|
||||||
|
})();
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
window.removePhoto = function (index) {
|
||||||
selectedFiles.splice(index, 1);
|
selectedFiles.splice(index, 1);
|
||||||
const dataTransfer = new DataTransfer();
|
const dataTransfer = new DataTransfer();
|
||||||
selectedFiles.forEach(file => dataTransfer.items.add(file));
|
selectedFiles.forEach(file => dataTransfer.items.add(file));
|
||||||
@@ -1413,7 +1497,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
// Обработчик для кнопки "Пополнить базу названиям<D18F><D0BC>"
|
// Обработчик для кнопки "Пополнить базу названиям<D18F><D0BC>"
|
||||||
const populateNamesBtn = document.getElementById('populateNamesBtn');
|
const populateNamesBtn = document.getElementById('populateNamesBtn');
|
||||||
if (populateNamesBtn) {
|
if (populateNamesBtn) {
|
||||||
populateNamesBtn.addEventListener('click', async function() {
|
populateNamesBtn.addEventListener('click', async function () {
|
||||||
const originalHTML = populateNamesBtn.innerHTML;
|
const originalHTML = populateNamesBtn.innerHTML;
|
||||||
populateNamesBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Пополнение...';
|
populateNamesBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Пополнение...';
|
||||||
populateNamesBtn.disabled = true;
|
populateNamesBtn.disabled = true;
|
||||||
@@ -1425,7 +1509,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
|
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
|
||||||
'Content-Type': 'application/x-www-form-urlencoded'
|
'Content-Type': 'application/x-www-form-urlencoded'
|
||||||
},
|
},
|
||||||
body: new URLSearchParams({'count': 100})
|
body: new URLSearchParams({ 'count': 100 })
|
||||||
});
|
});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
@@ -1512,7 +1596,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
document.querySelectorAll('.btn-take-name').forEach(button => {
|
document.querySelectorAll('.btn-take-name').forEach(button => {
|
||||||
// Проверяем, был ли уже добавлен обработчик
|
// Проверяем, был ли уже добавлен обработчик
|
||||||
if (!button.dataset.handlerAttached) {
|
if (!button.dataset.handlerAttached) {
|
||||||
button.addEventListener('click', async function() {
|
button.addEventListener('click', async function () {
|
||||||
const row = this.closest('.name-row');
|
const row = this.closest('.name-row');
|
||||||
const nameText = row.querySelector('.name-text').textContent;
|
const nameText = row.querySelector('.name-text').textContent;
|
||||||
const nameId = row.getAttribute('data-name-id');
|
const nameId = row.getAttribute('data-name-id');
|
||||||
@@ -1546,7 +1630,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
document.querySelectorAll('.btn-delete-name').forEach(button => {
|
document.querySelectorAll('.btn-delete-name').forEach(button => {
|
||||||
// Проверяем, был ли уже добавлен обработчик
|
// Проверяем, был ли уже добавлен обработчик
|
||||||
if (!button.dataset.handlerAttached) {
|
if (!button.dataset.handlerAttached) {
|
||||||
button.addEventListener('click', async function() {
|
button.addEventListener('click', async function () {
|
||||||
const row = this.closest('.name-row');
|
const row = this.closest('.name-row');
|
||||||
const nameId = row.getAttribute('data-name-id');
|
const nameId = row.getAttribute('data-name-id');
|
||||||
|
|
||||||
@@ -1632,7 +1716,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Инициализация обработчиков кнопок
|
// Инициализация обработчиков кнопок
|
||||||
document.addEventListener('click', function(e) {
|
document.addEventListener('click', function (e) {
|
||||||
if (e.target.classList.contains('btn-take-name') || e.target.classList.contains('btn-delete-name')) {
|
if (e.target.classList.contains('btn-take-name') || e.target.classList.contains('btn-delete-name')) {
|
||||||
attachNameRowHandlers();
|
attachNameRowHandlers();
|
||||||
}
|
}
|
||||||
@@ -1641,7 +1725,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
// ========== ВАЛИДАЦИЯ ПЕРЕД ОТПРАВКОЙ ==========
|
// ========== ВАЛИДАЦИЯ ПЕРЕД ОТПРАВКОЙ ==========
|
||||||
const kitForm = document.querySelector('form[method="post"]');
|
const kitForm = document.querySelector('form[method="post"]');
|
||||||
if (kitForm) {
|
if (kitForm) {
|
||||||
kitForm.addEventListener('submit', function(e) {
|
kitForm.addEventListener('submit', function (e) {
|
||||||
const formsContainer = document.getElementById('kititem-forms');
|
const formsContainer = document.getElementById('kititem-forms');
|
||||||
if (formsContainer) {
|
if (formsContainer) {
|
||||||
const allForms = formsContainer.querySelectorAll('.kititem-form');
|
const allForms = formsContainer.querySelectorAll('.kititem-form');
|
||||||
@@ -1671,6 +1755,6 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
allSelects.forEach(select => select.disabled = false);
|
allSelects.forEach(select => select.disabled = false);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -506,6 +506,9 @@
|
|||||||
<a href="{% url 'products:productkit-detail' object.pk %}" class="btn btn-outline-secondary">
|
<a href="{% url 'products:productkit-detail' object.pk %}" class="btn btn-outline-secondary">
|
||||||
Отмена
|
Отмена
|
||||||
</a>
|
</a>
|
||||||
|
<a href="{% url 'products:productkit-create' %}?copy_from={{ object.pk }}" class="btn btn-warning text-white mx-2">
|
||||||
|
<i class="bi bi-files me-1"></i>Копировать комплект
|
||||||
|
</a>
|
||||||
<button type="submit" class="btn btn-primary px-4">
|
<button type="submit" class="btn btn-primary px-4">
|
||||||
<i class="bi bi-check-circle me-1"></i>Сохранить изменения
|
<i class="bi bi-check-circle me-1"></i>Сохранить изменения
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -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, BouquetName
|
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 товаров/комплектов от префиксов.
|
||||||
@@ -132,7 +164,6 @@ 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, ProductSalesUnit
|
|
||||||
selected_products = {}
|
selected_products = {}
|
||||||
selected_variants = {}
|
selected_variants = {}
|
||||||
selected_sales_units = {}
|
selected_sales_units = {}
|
||||||
@@ -194,9 +225,99 @@ class ProductKitCreateView(LoginRequiredMixin, ManagerOwnerRequiredMixin, Create
|
|||||||
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['selected_sales_units'] = selected_sales_units
|
||||||
|
else:
|
||||||
|
# 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:
|
else:
|
||||||
context['kititem_formset'] = KitItemFormSetCreate(prefix='kititem')
|
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()
|
context['bouquet_names_count'] = BouquetName.objects.count()
|
||||||
|
|
||||||
@@ -235,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}" успешно создан!'
|
||||||
|
|||||||
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()
|
||||||
Reference in New Issue
Block a user