Initial commit: Django inventory system
This commit is contained in:
259
myproject/docs/example_usage.py
Normal file
259
myproject/docs/example_usage.py
Normal file
@@ -0,0 +1,259 @@
|
||||
"""
|
||||
Примеры использования системы вариантов товаров.
|
||||
|
||||
Этот файл содержит примеры кода для демонстрации работы с системой.
|
||||
Запускать через Django shell: python manage.py shell < docs/example_usage.py
|
||||
"""
|
||||
|
||||
from decimal import Decimal
|
||||
from products.models import (
|
||||
Product, ProductKit, KitItem, ProductCategory,
|
||||
ProductVariantGroup, KitItemPriority
|
||||
)
|
||||
from products.utils.stock_manager import StockManager
|
||||
|
||||
|
||||
def example_1_create_variant_group():
|
||||
"""Пример 1: Создание группы вариантов"""
|
||||
print("\n" + "="*60)
|
||||
print("ПРИМЕР 1: Создание группы вариантов")
|
||||
print("="*60)
|
||||
|
||||
# Создаём категорию
|
||||
category, _ = ProductCategory.objects.get_or_create(
|
||||
name="Цветы",
|
||||
defaults={'slug': 'cvety'}
|
||||
)
|
||||
|
||||
# Создаём товары - розы разной длины
|
||||
rose_50, _ = Product.objects.get_or_create(
|
||||
name="Роза Freedom 50см красная",
|
||||
defaults={
|
||||
'cost_price': Decimal('80.00'),
|
||||
'sale_price': Decimal('100.00'),
|
||||
'category': category
|
||||
}
|
||||
)
|
||||
|
||||
rose_60, _ = Product.objects.get_or_create(
|
||||
name="Роза Freedom 60см красная",
|
||||
defaults={
|
||||
'cost_price': Decimal('120.00'),
|
||||
'sale_price': Decimal('150.00'),
|
||||
'category': category
|
||||
}
|
||||
)
|
||||
|
||||
rose_70, _ = Product.objects.get_or_create(
|
||||
name="Роза Freedom 70см красная",
|
||||
defaults={
|
||||
'cost_price': Decimal('160.00'),
|
||||
'sale_price': Decimal('200.00'),
|
||||
'category': category
|
||||
}
|
||||
)
|
||||
|
||||
# Создаём группу вариантов
|
||||
group, created = ProductVariantGroup.objects.get_or_create(
|
||||
name="Роза красная Freedom",
|
||||
defaults={
|
||||
'description': 'Красная роза Freedom различной длины (50-70см)'
|
||||
}
|
||||
)
|
||||
|
||||
# Добавляем товары в группу
|
||||
rose_50.variant_groups.add(group)
|
||||
rose_60.variant_groups.add(group)
|
||||
rose_70.variant_groups.add(group)
|
||||
|
||||
print(f"✓ Создана группа: {group.name}")
|
||||
print(f" Товаров в группе: {group.get_products_count()}")
|
||||
print(f" Товары:")
|
||||
for product in group.products.all():
|
||||
print(f" - {product.name} ({product.sale_price} руб.)")
|
||||
|
||||
return group, rose_50, rose_60, rose_70
|
||||
|
||||
|
||||
def example_2_create_premium_bouquet(group, rose_50, rose_60, rose_70):
|
||||
"""Пример 2: Создание премиум букета с приоритетами"""
|
||||
print("\n" + "="*60)
|
||||
print("ПРИМЕР 2: Создание премиум букета")
|
||||
print("="*60)
|
||||
|
||||
# Создаём букет
|
||||
kit, _ = ProductKit.objects.get_or_create(
|
||||
name="Ранчо Виталия Премиум",
|
||||
defaults={
|
||||
'slug': 'rancho-vitaliya-premium',
|
||||
'pricing_method': 'from_sale_prices'
|
||||
}
|
||||
)
|
||||
|
||||
# Создаём позицию с группой вариантов
|
||||
kit_item, _ = KitItem.objects.get_or_create(
|
||||
kit=kit,
|
||||
variant_group=group,
|
||||
defaults={
|
||||
'quantity': Decimal('15.000'),
|
||||
'notes': 'Использовать самые длинные розы'
|
||||
}
|
||||
)
|
||||
|
||||
# Настраиваем приоритеты (для премиум букета - сначала длинные)
|
||||
KitItemPriority.objects.get_or_create(
|
||||
kit_item=kit_item,
|
||||
product=rose_70,
|
||||
defaults={'priority': 0} # Наивысший приоритет
|
||||
)
|
||||
KitItemPriority.objects.get_or_create(
|
||||
kit_item=kit_item,
|
||||
product=rose_60,
|
||||
defaults={'priority': 1}
|
||||
)
|
||||
KitItemPriority.objects.get_or_create(
|
||||
kit_item=kit_item,
|
||||
product=rose_50,
|
||||
defaults={'priority': 2} # Самый низкий приоритет
|
||||
)
|
||||
|
||||
print(f"✓ Создан букет: {kit.name}")
|
||||
print(f" Позиций: {kit.get_total_components_count()}")
|
||||
print(f" С вариантами: {kit.get_components_with_variants_count()}")
|
||||
print(f"\n Приоритеты для позиции '{kit_item.get_display_name()}':")
|
||||
for priority in kit_item.priorities.all().order_by('priority'):
|
||||
print(f" {priority.priority}. {priority.product.name} - {priority.product.sale_price} руб.")
|
||||
|
||||
return kit
|
||||
|
||||
|
||||
def example_3_create_economy_bouquet(group, rose_50, rose_60, rose_70):
|
||||
"""Пример 3: Создание эконом букета"""
|
||||
print("\n" + "="*60)
|
||||
print("ПРИМЕР 3: Создание эконом букета")
|
||||
print("="*60)
|
||||
|
||||
# Создаём эконом букет
|
||||
kit, _ = ProductKit.objects.get_or_create(
|
||||
name="Ранчо Виталия Эконом",
|
||||
defaults={
|
||||
'slug': 'rancho-vitaliya-econom',
|
||||
'pricing_method': 'from_sale_prices'
|
||||
}
|
||||
)
|
||||
|
||||
# Та же группа вариантов, но другие приоритеты
|
||||
kit_item, _ = KitItem.objects.get_or_create(
|
||||
kit=kit,
|
||||
variant_group=group,
|
||||
defaults={
|
||||
'quantity': Decimal('15.000'),
|
||||
'notes': 'Эконом вариант'
|
||||
}
|
||||
)
|
||||
|
||||
# Для эконом букета - сначала короткие (дешевые)
|
||||
KitItemPriority.objects.get_or_create(
|
||||
kit_item=kit_item,
|
||||
product=rose_50,
|
||||
defaults={'priority': 0} # Наивысший приоритет
|
||||
)
|
||||
KitItemPriority.objects.get_or_create(
|
||||
kit_item=kit_item,
|
||||
product=rose_60,
|
||||
defaults={'priority': 1}
|
||||
)
|
||||
KitItemPriority.objects.get_or_create(
|
||||
kit_item=kit_item,
|
||||
product=rose_70,
|
||||
defaults={'priority': 2} # Самый низкий приоритет
|
||||
)
|
||||
|
||||
print(f"✓ Создан букет: {kit.name}")
|
||||
print(f"\n Приоритеты для позиции '{kit_item.get_display_name()}':")
|
||||
for priority in kit_item.priorities.all().order_by('priority'):
|
||||
print(f" {priority.priority}. {priority.product.name} - {priority.product.sale_price} руб.")
|
||||
|
||||
return kit
|
||||
|
||||
|
||||
def example_4_check_availability(premium_kit, economy_kit):
|
||||
"""Пример 4: Проверка доступности"""
|
||||
print("\n" + "="*60)
|
||||
print("ПРИМЕР 4: Проверка доступности букетов")
|
||||
print("="*60)
|
||||
|
||||
stock_manager = StockManager()
|
||||
|
||||
# Проверяем премиум букет
|
||||
print(f"\nПремиум букет: {premium_kit.name}")
|
||||
if premium_kit.check_availability(stock_manager):
|
||||
print(" ✓ Доступен для сборки")
|
||||
price = premium_kit.calculate_price_with_substitutions(stock_manager)
|
||||
print(f" Цена: {price} руб.")
|
||||
else:
|
||||
print(" ✗ Недоступен")
|
||||
|
||||
# Проверяем эконом букет
|
||||
print(f"\nЭконом букет: {economy_kit.name}")
|
||||
if economy_kit.check_availability(stock_manager):
|
||||
print(" ✓ Доступен для сборки")
|
||||
price = economy_kit.calculate_price_with_substitutions(stock_manager)
|
||||
print(f" Цена: {price} руб.")
|
||||
else:
|
||||
print(" ✗ Недоступен")
|
||||
|
||||
|
||||
def example_5_best_product():
|
||||
"""Пример 5: Получение лучшего доступного товара"""
|
||||
print("\n" + "="*60)
|
||||
print("ПРИМЕР 5: Выбор лучшего доступного товара")
|
||||
print("="*60)
|
||||
|
||||
# Получаем премиум букет
|
||||
kit = ProductKit.objects.filter(name="Ранчо Виталия Премиум").first()
|
||||
if not kit:
|
||||
print(" Букет не найден")
|
||||
return
|
||||
|
||||
stock_manager = StockManager()
|
||||
|
||||
for kit_item in kit.kit_items.all():
|
||||
print(f"\nПозиция: {kit_item.get_display_name()}")
|
||||
print(f"Количество: {kit_item.quantity}")
|
||||
|
||||
best_product = kit_item.get_best_available_product(stock_manager)
|
||||
if best_product:
|
||||
print(f"✓ Лучший доступный товар: {best_product.name}")
|
||||
print(f" Цена: {best_product.sale_price} руб.")
|
||||
print(f" Стоимость позиции: {best_product.sale_price * kit_item.quantity} руб.")
|
||||
else:
|
||||
print("✗ Нет доступных товаров")
|
||||
|
||||
|
||||
def main():
|
||||
"""Запуск всех примеров"""
|
||||
print("\n" + "="*60)
|
||||
print("ДЕМОНСТРАЦИЯ СИСТЕМЫ ВАРИАНТОВ ТОВАРОВ")
|
||||
print("="*60)
|
||||
|
||||
# Создаём данные
|
||||
group, rose_50, rose_60, rose_70 = example_1_create_variant_group()
|
||||
|
||||
# Создаём букеты
|
||||
premium_kit = example_2_create_premium_bouquet(group, rose_50, rose_60, rose_70)
|
||||
economy_kit = example_3_create_economy_bouquet(group, rose_50, rose_60, rose_70)
|
||||
|
||||
# Проверяем доступность
|
||||
example_4_check_availability(premium_kit, economy_kit)
|
||||
|
||||
# Получаем лучший товар
|
||||
example_5_best_product()
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("ДЕМОНСТРАЦИЯ ЗАВЕРШЕНА")
|
||||
print("="*60 + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user