149 lines
5.8 KiB
Python
149 lines
5.8 KiB
Python
from django.db import models, transaction, connection
|
|
from django.db.models import Sum
|
|
|
|
|
|
class ProductCategory(models.Model):
|
|
category_name = models.CharField(max_length=50)
|
|
|
|
def __str__(self):
|
|
return self.category_name
|
|
|
|
|
|
class Product(models.Model):
|
|
class Meta:
|
|
permissions = [
|
|
("ViewProduct", "ViewProduct"),
|
|
]
|
|
ProductCategory = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
|
|
product_name = models.CharField(max_length=50)
|
|
product_price = models.IntegerField()
|
|
year = models.IntegerField(default=1400)
|
|
createdDT = models.DateTimeField(auto_now_add=True)
|
|
changeDT = models.DateTimeField(auto_now=True)
|
|
|
|
def __str__(self):
|
|
return self.product_name
|
|
|
|
|
|
class ProductInStore(models.Model):
|
|
class Meta:
|
|
permissions = [
|
|
("ViewProductInStore", "ViewProductInStore"),
|
|
("EditProductInStore", "EditProductInStore"),
|
|
("OnlyAnbar", "OnlyAnbar"),
|
|
]
|
|
class MovementType(models.TextChoices):
|
|
SALE = 'SALE', 'فروش عادی'
|
|
WARRANTY = 'WARRANTY', 'گارانتی'
|
|
PROMOTION = 'PROMOTION', 'اشانتیون'
|
|
TRANSFER = 'TRANSFER', 'انتقال'
|
|
INITIAL = 'INITIAL', 'موجودی اولیه'
|
|
DIRECT_IN = 'DIRECT_IN', 'ورود دستی'
|
|
DIRECT_OUT = 'DIRECT_OUT', 'خروج دستی'
|
|
RETURN = 'RETURN', 'برگشت از فروش'
|
|
ERROR_CORRECTION = 'ERROR_CORRECTION', 'اصلاح خطای ثبت'
|
|
|
|
StoreRoom = models.ForeignKey('StoreRoom', on_delete=models.CASCADE)
|
|
Product = models.ForeignKey(Product, on_delete=models.CASCADE)
|
|
s_in = models.IntegerField(default=0)
|
|
s_out = models.IntegerField(default=0)
|
|
current_stock_at_time = models.IntegerField(default=0, help_text="موجودی انبار در لحظه این تراکنش")
|
|
desc = models.CharField(max_length=50, default='')
|
|
year = models.IntegerField(default=1400)
|
|
createdDT = models.DateTimeField(auto_now_add=True)
|
|
changeDT = models.DateTimeField(auto_now=True)
|
|
|
|
# تغییر بسیار مهم استراتژیک: تبدیل CASCADE به PROTECT
|
|
# هیچکس نمیتواند فاکتوری که کالا از انبار خارج کرده را از دیتابیس پاک کند!
|
|
factor = models.ForeignKey('Factor', on_delete=models.PROTECT, null=True, blank=True)
|
|
|
|
movement_type = models.CharField(
|
|
max_length=20,
|
|
choices=MovementType.choices,
|
|
db_index=True,
|
|
null=True,
|
|
blank=True
|
|
)
|
|
|
|
def __str__(self):
|
|
return f"{self.Product.product_name} - In: {self.s_in} Out: {self.s_out}"
|
|
|
|
# متدهای save و delete دقیقاً همان کدهای بینقص و پرسرعتی هستند که در پیام قبل تایید کردیم
|
|
def save(self, *args, **kwargs):
|
|
from .store import ProductStockHistory
|
|
|
|
try:
|
|
self.s_in = int(self.s_in or 0)
|
|
self.s_out = int(self.s_out or 0)
|
|
except (ValueError, TypeError):
|
|
self.s_in, self.s_out = 0, 0
|
|
|
|
is_created = self.pk is None
|
|
|
|
with transaction.atomic():
|
|
qs_lock = ProductInStore.objects.filter(StoreRoom=self.StoreRoom, Product=self.Product)
|
|
if connection.features.has_select_for_update:
|
|
qs_lock = qs_lock.select_for_update()
|
|
list(qs_lock)
|
|
|
|
if not is_created:
|
|
old_instance = ProductInStore.objects.get(pk=self.pk)
|
|
old_balance = old_instance.s_in - old_instance.s_out
|
|
new_balance = self.s_in - self.s_out
|
|
change_amount = new_balance - old_balance
|
|
description = self.desc or f"ویرایش تراکنش: {self.desc}"
|
|
else:
|
|
change_amount = self.s_in - self.s_out
|
|
description = self.desc or "ثبت تراکنش جدید انبار"
|
|
|
|
super().save(*args, **kwargs)
|
|
|
|
totals = ProductInStore.objects.filter(StoreRoom=self.StoreRoom, Product=self.Product).aggregate(
|
|
total_in=Sum('s_in'),
|
|
total_out=Sum('s_out')
|
|
)
|
|
total_in = totals['total_in'] or 0
|
|
total_out = totals['total_out'] or 0
|
|
current_stock = total_in - total_out
|
|
|
|
ProductInStore.objects.filter(pk=self.pk).update(current_stock_at_time=current_stock)
|
|
self.current_stock_at_time = current_stock
|
|
|
|
ProductStockHistory.objects.create(
|
|
store_room=self.StoreRoom,
|
|
product=self.Product,
|
|
quantity_changed=change_amount,
|
|
current_stock=current_stock,
|
|
desc=description
|
|
)
|
|
|
|
def delete(self, *args, **kwargs):
|
|
from .store import ProductStockHistory
|
|
|
|
store_room = self.StoreRoom
|
|
product = self.Product
|
|
change_amount = -(int(self.s_in or 0) - int(self.s_out or 0))
|
|
description = f"حذف دستی تراکنش انبار: {self.desc}"
|
|
|
|
with transaction.atomic():
|
|
qs_lock = ProductInStore.objects.filter(StoreRoom=store_room, Product=product)
|
|
if connection.features.has_select_for_update:
|
|
qs_lock = qs_lock.select_for_update()
|
|
list(qs_lock)
|
|
|
|
super().delete(*args, **kwargs)
|
|
|
|
totals = ProductInStore.objects.filter(StoreRoom=store_room, Product=product).aggregate(
|
|
total_in=Sum('s_in'),
|
|
total_out=Sum('s_out')
|
|
)
|
|
current_stock = (totals['total_in'] or 0) - (totals['total_out'] or 0)
|
|
|
|
ProductStockHistory.objects.create(
|
|
store_room=store_room,
|
|
product=product,
|
|
quantity_changed=change_amount,
|
|
current_stock=current_stock,
|
|
desc=description
|
|
)
|