free sale of inventory entry system deployment - add dhi state to rancher

This commit is contained in:
2025-09-20 12:41:24 +03:30
parent ce6e468b13
commit e8f4c77e9f
12 changed files with 390 additions and 158 deletions

View File

@@ -0,0 +1,37 @@
# Generated by Django 5.0 on 2025-09-16 07:41
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0036_organization_phone'),
('product', '0073_historicalquotadistribution_free_sale_and_more'),
('warehouse', '0023_inventoryquotasaletransaction_inventory_entry_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ExtraSale',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('creator_info', models.CharField(max_length=100, null=True)),
('modifier_info', models.CharField(max_length=100, null=True)),
('trash', models.BooleanField(default=False)),
('weight', models.PositiveBigIntegerField(default=0)),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_createddby', to=settings.AUTH_USER_MODEL)),
('distribution', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='extra_sales', to='product.quotadistribution')),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='%(class)s_modifiedby', to=settings.AUTH_USER_MODEL)),
('organization', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='extra_sales', to='authentication.organization')),
],
options={
'abstract': False,
},
),
]

View File

@@ -0,0 +1,24 @@
# Generated by Django 5.0 on 2025-09-17 05:06
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('warehouse', '0024_extrasale'),
]
operations = [
migrations.AddField(
model_name='extrasale',
name='transaction',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='warehouse.inventoryquotasaletransaction'),
),
migrations.AddField(
model_name='inventoryquotasaleitem',
name='is_extra',
field=models.BooleanField(default=False),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 5.0 on 2025-09-17 05:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('warehouse', '0025_extrasale_transaction_and_more'),
]
operations = [
migrations.AlterField(
model_name='extrasale',
name='weight',
field=models.IntegerField(default=0),
),
]

View File

@@ -0,0 +1,19 @@
# Generated by Django 5.0 on 2025-09-17 10:41
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('warehouse', '0026_alter_extrasale_weight'),
]
operations = [
migrations.AddField(
model_name='extrasale',
name='sale_item',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sale_items', to='warehouse.inventoryquotasaleitem'),
),
]

View File

@@ -1,7 +1,7 @@
import string
import random
from apps.authentication.models import User, Organization
from apps.product import models as product_models
from apps.authentication.models import User
from apps.pos_device.models import Device
from apps.herd.models import Rancher
from apps.core.models import BaseModel
@@ -149,9 +149,44 @@ class InventoryQuotaSaleItem(BaseModel):
weight = models.PositiveBigIntegerField(default=0)
unit_price = models.PositiveBigIntegerField(default=0)
total_price = models.PositiveBigIntegerField(default=0)
is_extra = models.BooleanField(default=False)
def __str__(self):
return f'Item {self.product} - {self.weight} Kg - {self.total_price}'
def save(self, *args, **kwargs):
return super(InventoryQuotaSaleItem, self).save(*args, **kwargs)
class ExtraSale(BaseModel):
organization = models.ForeignKey(
Organization,
on_delete=models.CASCADE,
related_name='extra_sales',
null=True
)
distribution = models.ForeignKey(
product_models.QuotaDistribution,
on_delete=models.CASCADE,
related_name='extra_sales',
null=True
)
transaction = models.ForeignKey(
InventoryQuotaSaleTransaction,
on_delete=models.CASCADE,
related_name='transactions',
null=True
)
sale_item = models.ForeignKey(
InventoryQuotaSaleItem,
on_delete=models.CASCADE,
related_name='sale_items',
null=True
)
weight = models.IntegerField(default=0)
def __str__(self):
return f'Extra Sale on {self.organization.name} - {self.distribution.distribution_id}'
def save(self, *args, **kwargs):
return super(ExtraSale, self).save(*args, **kwargs)

View File

@@ -7,10 +7,13 @@ from apps.product.services.services import (
)
from apps.pos_device.services.services import pos_organizations_sharing_information
from apps.pos_device.pos.api.v1.serializers.device import DeviceSerializer
from apps.product.exceptions import DistributionWeightException
from apps.warehouse.services.services import create_extra_sale
from apps.herd.pos.api.v1.serializers import RancherSerializer
from apps.product.models import QuotaDistribution, Product
from apps.warehouse import models as warehouse_models
from apps.core.models import SystemConfig
from django.db.transaction import atomic
from apps.warehouse.exceptions import (
TotalInventorySaleException
)
@@ -99,6 +102,7 @@ class InventoryEntrySerializer(serializers.ModelSerializer):
class InventoryQuotaSaleTransactionSerializer(serializers.ModelSerializer):
rancher_national_code = serializers.CharField(max_length=50, required=False)
class Meta: # noqa
model = warehouse_models.InventoryQuotaSaleTransaction
fields = '__all__'
@@ -106,60 +110,66 @@ class InventoryQuotaSaleTransactionSerializer(serializers.ModelSerializer):
def create(self, validated_data):
items_data = self.context['request'].data['items']
with atomic():
# get rancher with national code
rancher = Rancher.objects.get(national_code=validated_data.pop('rancher_national_code'))
validated_data.update({'rancher': rancher})
# get rancher with national code
rancher = Rancher.objects.get(national_code=validated_data.pop('rancher_national_code'))
validated_data.update({'rancher': rancher})
# if transaction exists, update transaction status
transaction = self.Meta.model.objects.filter(
transaction_id=validated_data.get('transaction_id')
)
if transaction.exists():
obj = transaction.first()
obj.transaction_status = validated_data.get('transaction_status')
obj.save(update_fields=['transaction_status'])
return obj
# create transaction record
transaction = warehouse_models.InventoryQuotaSaleTransaction.objects.create(
**validated_data
)
# calculate total price of product items in shopping cart
total_price = 0
for item_data in items_data:
item = warehouse_models.InventoryQuotaSaleItem.objects.create(
transaction=transaction,
quota_distribution=QuotaDistribution.objects.get(
id=item_data.pop('quota_distribution')
),
product=Product.objects.get(
id=item_data.pop('product')
),
**item_data
# if transaction exists, update transaction status
transaction = self.Meta.model.objects.filter(
transaction_id=validated_data.get('transaction_id')
)
total_price += item.total_price
transaction.transaction_price = total_price
transaction.save()
if transaction.exists():
obj = transaction.first()
obj.transaction_status = validated_data.get('transaction_status')
obj.save(update_fields=['transaction_status'])
return transaction
return obj
# create transaction record
transaction = warehouse_models.InventoryQuotaSaleTransaction.objects.create(
**validated_data
)
# calculate total price of product items in shopping cart
total_price = 0
for item_data in items_data:
item = warehouse_models.InventoryQuotaSaleItem.objects.create(
transaction=transaction,
quota_distribution=QuotaDistribution.objects.get(
id=item_data.pop('quota_distribution')
),
product=Product.objects.get(
id=item_data.pop('product')
),
**item_data
)
total_price += item.total_price
# create extra sale
create_extra_sale(transaction=transaction, sale_item=item)
transaction.transaction_price = total_price
transaction.save()
return transaction
def validate(self, attrs):
"""
validate total inventory sale should be fewer than
inventory entry from distribution
distribution weight
"""
if 'quota_distribution' in attrs.keys():
distribution = attrs['quota_distribution']
total_sale_weight = distribution.inventory_sales.aggregate(
total=models.Sum('weight')
)['total'] or 0
items = self.context['request'].data['items']
for item in items:
if 'quota_distribution' in item.keys():
distribution = QuotaDistribution.objects.get(id=item.get('quota_distribution'))
total_sale_weight = distribution.sale_items.aggregate(
total=models.Sum('weight')
)['total'] or 0
if total_sale_weight + attrs['weight'] > distribution.warehouse_balance:
raise TotalInventorySaleException()
if total_sale_weight + attrs['weight'] > distribution.weight:
raise DistributionWeightException()
return attrs

View File

@@ -1,8 +1,14 @@
from apps.herd.services.services import rancher_quota_weight, get_rancher_statistics
from apps.warehouse.models import InventoryEntry, InventoryQuotaSaleTransaction
from apps.warehouse.models import (
InventoryEntry,
InventoryQuotaSaleTransaction,
InventoryQuotaSaleItem,
ExtraSale
)
from apps.product.models import QuotaDistribution
from apps.core.models import SystemConfig
from django.db.models import Sum
import typing
def get_total_sold(rancher, inventory_entry: InventoryEntry = None, distribution: QuotaDistribution = None):
@@ -53,3 +59,35 @@ def can_buy_from_inventory(rancher, inventory_entry: InventoryEntry = None, dist
total_sold = get_total_sold(inventory_entry, rancher)
return total_sold < total_allowed
def create_extra_sale(
sale_item: InventoryQuotaSaleItem,
transaction: InventoryQuotaSaleTransaction
) -> typing.Any:
"""
:param sale_item
:param transaction
create extra sale for items that weight are
more than distribution warehouse balance
"""
if sale_item.quota_distribution.free_sale:
if sale_item.weight > sale_item.quota_distribution.warehouse_balance:
# calculate extra weight between item weight and warehouse balance
extra_weight = sale_item.weight - sale_item.quota_distribution.warehouse_balance
extra_sale = ExtraSale.objects.create( # create extra sale
transaction=transaction,
sale_item=sale_item,
distribution=sale_item.quota_distribution,
weight=extra_weight
)
# set distribution warehouse balance to 0 because we have extra sale
sale_item.quota_distribution.warehouse_balance = 0
sale_item.quota_distribution.save()
return extra_sale
pass
pass

View File

@@ -21,6 +21,11 @@ def warehouse_sold_and_balance(quota_distribution: QuotaDistribution):
quota_distribution.been_sold = total_sold
quota_distribution.warehouse_balance = quota_distribution.warehouse_entry - total_sold
if quota_distribution.warehouse_balance >= 0:
extra_sales = quota_distribution.extra_sales.all()
total_extra_sales_weight = extra_sales.aggregate(total=Sum('weight'))['total'] or 0
if total_extra_sales_weight != 0:
quota_distribution.warehouse_balance = quota_distribution.warehouse_entry - total_extra_sales_weight
quota_distribution.save(update_fields=['been_sold', 'warehouse_balance'])