first push

This commit is contained in:
2026-01-18 11:42:00 +03:30
commit 1704e7356b
723 changed files with 273450 additions and 0 deletions

View File

View File

View File

@@ -0,0 +1,20 @@
from django_filters import rest_framework as filters
from LiveStock.models import Contractor
class ContractorFilterSet(filters.FilterSet):
class Meta:
model = Contractor
fields = [
'address__city__name',
'contractor_code',
'fullname',
'entity_code',
'national_id',
'company_name',
'user__mobile',
'user__first_name',
'user__last_name',
'user__fullname'
]

View File

View File

@@ -0,0 +1,14 @@
from rest_framework import serializers
from LiveStock.models import Union, Contractor
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
from authentication.serializers import SystemAddressSerializer
class ContractorSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
address = SystemAddressSerializer(read_only=True)
class Meta:
model = Contractor
fields = '__all__'

View File

@@ -0,0 +1,14 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from LiveStock.Contractor import views as contractor_views
router = DefaultRouter()
router.register(
r'contractor-views',
contractor_views.ContractorViewSet,
basename="contractor-views"
)
urlpatterns = [
path('', include(router.urls)),
]

View File

@@ -0,0 +1,60 @@
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from LiveStock.Contractor.filterset import ContractorFilterSet
from LiveStock.Contractor.serializers import ContractorSerializer
from LiveStock.helpers import build_query, CustomPagination
from LiveStock.models import Contractor
from authentication.models import SystemUserProfile
class ContractorViewSet(viewsets.ModelViewSet):
queryset = Contractor.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = ContractorSerializer
filterset_class = ContractorFilterSet
pagination_class = CustomPagination
def retrieve(self, request, pk=None, *args, **kwargs):
if 'profile' in request.GET:
user = SystemUserProfile.objects.get(user=request.user, trash=False)
union = user.contractor_user.all()
serializer = self.serializer_class(union[0])
return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs):
contractor = Contractor.objects.filter(trash=False).order_by('id')
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
contractor = contractor.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page = self.paginate_queryset(contractor)
if page is not None:
serializer = self.serializer_class(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(contractor, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
contractor = Contractor.objects.get(key=request.data['key'], trash=False)
request.data.pop('key')
serializer = self.serializer_class(contractor)
serializer.update(instance=contractor, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_200_OK)
def destroy(self, request, pk=None, *args, **kwargs):
contractor = Contractor.objects.get(key=request.GET["key"])
contractor.trash = True
contractor.save()
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)

View File

View File

@@ -0,0 +1,17 @@
from django_filters import rest_framework as filters
from LiveStock.models import Cooperative
class CooperativeFilterSet(filters.FilterSet):
class Meta:
model = Cooperative
fields = [
'address__city__name',
'name',
'mobile',
'user__mobile',
'user__first_name',
'user__last_name',
'user__fullname'
]

View File

View File

@@ -0,0 +1,66 @@
from rest_framework import serializers
from LiveStock.models import Cooperative, LiveStockRolseProduct
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
from authentication.serializers import SystemAddressSerializer
from ticket.serializers import SystemUserProfileForTicketPermissionSerializer
class CooperativeSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
address = SystemAddressSerializer(read_only=True)
user_bank_info = BankCardSerializer(required=False)
class Meta:
model = Cooperative
fields = '__all__'
class CooperativeForSharesSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
class Meta:
model = Cooperative
fields = ['user', 'name']
class CooperativeForAllocationsReportSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
info = serializers.SerializerMethodField('get_info')
class Meta:
model = Cooperative
fields = ['key','user', 'name','info']
def get_info(self, obj):
products = {
"bran":"سبوس",
"barley":"جو",
"soy":"سویا",
"corn":"ذرت",
"sheep_concentrate":"کنسانتره گوسفندی",
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
}
product =products[self.context.get('request').GET['name']]
cooperative_roles = LiveStockRolseProduct.objects.get(cooperative=obj,parent_product__name=product)
total_weight = cooperative_roles.total_weight
total_receipt_weight = cooperative_roles.total_receipt_weight
total_allocated_weight = cooperative_roles.total_allocated_weight
total_remain_weight = cooperative_roles.total_remain_weight
return {
"total_weight": total_weight,
"total_receipt_weight": total_receipt_weight,
"total_allocated_weight": total_allocated_weight,
"total_remain_weight": total_remain_weight,
}
class CooperativeForPosSerializer(serializers.ModelSerializer):
user = SystemUserProfileForTicketPermissionSerializer(read_only=True)
address = SystemAddressSerializer(read_only=True)
class Meta:
model = Cooperative
fields = ['user', 'name', 'address']

View File

@@ -0,0 +1,21 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from LiveStock.Cooperative import views as cooperative_views
router = DefaultRouter()
router.register(
r'cooperative-views',
cooperative_views.CooperativeViewSet,
basename="cooperative-views"
)
router.register(
r'cooperative-warehouse',
cooperative_views.CooperativeWarehouseDashboardViewSet,
basename="cooperative-warehouse"
)
urlpatterns = [
path('', include(router.urls)),
]

View File

@@ -0,0 +1,196 @@
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
import requests
from django.contrib.auth.models import User, Group
from LiveStock.Cooperative.filterset import CooperativeFilterSet
from LiveStock.Cooperative.serializers import CooperativeSerializer, CooperativeForAllocationsReportSerializer
from LiveStock.helpers import build_query, CustomPagination
from LiveStock.models import Cooperative, CooperativeProductsShare, LiveStockProduct, LiveStockRolseProduct
from authentication.models import SystemUserProfile, City, Province, SystemAddress
from authentication.views import ARTA_URL_CHANGE_MOBILE_NUMBER, ARTA_URL_REGISTER
from panel.admin import PROJECT_API_KEY
class CooperativeViewSet(viewsets.ModelViewSet):
queryset = Cooperative.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = CooperativeSerializer
filterset_class = CooperativeFilterSet
pagination_class = CustomPagination
def create(self, request, *args, **kwargs):
group = Group.objects.get(name__exact="Cooperative")
city = City.objects.get(name=request.data['city'])
request.data.pop('city')
province = Province.objects.get(key=city.province.key)
system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
if system_profile:
if Cooperative.objects.filter(user=system_profile, trash=False).exists():
return Response({"result": "این تعاونی قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)
else:
password = "123456"
data = {
"username": request.data['mobile'],
"password": password,
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_URL_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
user = User(username=request.data['mobile'], first_name=request.data['first_name'],
last_name=request.data['last_name'])
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
system_profile = SystemUserProfile(
mobile=request.data['mobile'],
first_name=request.data['first_name'],
last_name=request.data['last_name'],
fullname=request.data['first_name'] + " " + request.data['last_name'],
user=user,
base_order=base_id,
password=password,
national_id=request.data['national_id'],
city=city,
province=province
)
system_profile.save()
else:
return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
address = SystemAddress(city=city, province=province, address=request.data['address'],
postal_code=request.data['postal_code'])
address.save()
system_profile.role.add(group)
request.data.pop('first_name')
request.data.pop('last_name')
request.data.pop('address')
request.data.pop('postal_code')
products = LiveStockProduct.objects.filter(trash=False)
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
cooperative = serializer.create(validated_data=request.data)
cooperative.user = system_profile
cooperative.address = address
cooperative.save()
for product in products:
share = CooperativeProductsShare(
cooperative=cooperative,
product=product
)
share.save()
cooperative_roles_product = LiveStockRolseProduct(
cooperative=cooperative,
parent_product=product
)
cooperative_roles_product.save()
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def retrieve(self, request, pk=None, *args, **kwargs):
if 'profile' in request.GET:
user = SystemUserProfile.objects.get(user=request.user, trash=False)
cooperative = user.cooperative_user.all()
serializer = self.serializer_class(cooperative[0])
return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs):
cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
cooperatives = cooperatives.filter(
build_query(self.filterset_class.Meta.fields, search)
)
page = self.paginate_queryset(cooperatives)
if page is not None:
serializer = self.serializer_class(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(cooperatives, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, pk=None, *args, **kwargs):
cooperative = Cooperative.objects.get(key=request.data['cooperative_key'], trash=False)
address = SystemAddress.objects.get(key=cooperative.address.key, trash=False)
request.data.pop('cooperative_key')
if 'first_name' in request.data.keys():
system_user_profile = SystemUserProfile.objects.get(key=cooperative.user.key, trash=False)
system_user_profile.first_name = request.data['first_name']
system_user_profile.last_name = request.data['last_name']
system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
system_user_profile.save()
first_mobile_number = system_user_profile.mobile
second_mobile_number = request.data['mobile']
if first_mobile_number != second_mobile_number:
if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
status=status.HTTP_403_FORBIDDEN)
data = {
"first_mobile_number": first_mobile_number,
"second_mobile_number": second_mobile_number,
}
req = requests.post(
url=ARTA_URL_CHANGE_MOBILE_NUMBER,
data=data,
verify=False
)
if req.status_code == 200:
second_mobile_number = second_mobile_number
user = User.objects.get(id=system_user_profile.user.id)
user.username = second_mobile_number
user.save()
system_user_profile.mobile = second_mobile_number
system_user_profile.save()
city = City.objects.get(name=request.data['city'])
province = Province.objects.get(key=city.province.key)
address.city = city
address.province = province
address.address = request.data['address']
address.postal_code = request.data['postal_code']
address.save()
request.data.pop('first_name')
request.data.pop('last_name')
request.data.pop('address')
request.data.pop('city')
serializer = self.serializer_class(cooperative)
serializer.update(instance=cooperative, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_200_OK)
class CooperativeWarehouseDashboardViewSet(viewsets.ModelViewSet):
queryset = Cooperative.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = CooperativeForAllocationsReportSerializer
filterset_class = CooperativeFilterSet
pagination_class = CustomPagination
def list(self, request, *args, **kwargs):
cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
cooperatives = cooperatives.filter(
build_query(self.filterset_class.Meta.fields, search)
)
page = self.paginate_queryset(cooperatives)
if page is not None:
serializer = self.serializer_class(page, many=True,context={"request":request})
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(cooperatives, many=True,context={"request":request})
return Response(serializer.data, status=status.HTTP_200_OK)

View File

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
from django_filters import rest_framework as filters
from LiveStock.models import LiveStockAllocations, CooperativeProductsShare
class LiveStockAllocationsFilterSet(filters.FilterSet):
class Meta:
model = LiveStockAllocations
fields = [
'product__name',
'jahad__user__mobile',
'jahad__user__first_name',
'jahad__user__last_name',
'jahad__user__fullname',
'union__user__mobile',
'union__user__first_name',
'union__user__last_name',
'union__user__fullname',
'cooperative__user__mobile',
'cooperative__user__first_name',
'cooperative__user__last_name',
'cooperative__user__fullname'
]
class CooperativeProductsShareFilterSet(filters.FilterSet):
class Meta:
model = CooperativeProductsShare
fields = [
'product__name',
'cooperative__user__mobile',
'cooperative__user__first_name',
'cooperative__user__last_name',
'cooperative__user__fullname'
]

View File

@@ -0,0 +1,45 @@
from django.db.models import Sum, Q
from LiveStock.models import LiveStockAllocations
def jahad_warehousing(product):
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False,product=product, trash=False)
# allocations = LiveStockAllocations.objects.filter(jahad=product.jahad, trash=False)
input_allocations = allocations.filter(union__isnull=True, cooperative__isnull=True)
output_allocations = allocations.filter(Q(union__isnull=False) | Q(cooperative__isnull=False))
input_weight = input_allocations.aggregate(total=Sum('weight'))[
'total'] or 0
output_weight = output_allocations.aggregate(total=Sum('weight'))[
'total'] or 0
product.total_weight = input_weight
product.total_receipt_weight = input_weight
product.total_allocated_weight = output_weight
product.save()
def union_warehousing(product):
allocations = LiveStockAllocations.objects.filter(union=product.union,product__parent_product__name=product.parent_product.name, trash=False)
input_allocations = allocations.filter(jahad__isnull=False)
output_allocations = allocations.filter(cooperative__isnull=False)
input_weight = input_allocations.aggregate(total=Sum('weight'))[
'total'] or 0
output_weight = output_allocations.aggregate(total=Sum('weight'))[
'total'] or 0
product.total_weight = input_weight
product.total_receipt_weight = input_weight
product.total_allocated_weight = output_weight
product.save()
def cooperative_warehousing(product):
input_allocations = LiveStockAllocations.objects.filter(cooperative=product.cooperative,product__parent_product__name=product.parent_product.name, trash=False).values_list('id',flat=True)
total_receipt_weight = input_allocations.filter(charge=False).aggregate(total=Sum('weight'))[
'total'] or 0
real_input_weight = input_allocations.filter(charge=True).aggregate(total=Sum('weight'))[
'total'] or 0
product.total_receipt_weight = total_receipt_weight
product.total_weight = real_input_weight
product.save()

View File

@@ -0,0 +1,54 @@
from rest_framework import serializers
from LiveStock.Cooperative.serializers import CooperativeSerializer, CooperativeForSharesSerializer
from LiveStock.Union.serializers import UnionSerializer
from LiveStock.models import LiveStockProvinceJahad, LiveStockRolseProduct, LiveStockAllocations, LiveStockProduct, \
CooperativeProductsShare
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
from authentication.serializers import SystemAddressSerializer
from ticket.serializers import SystemUserProfileForTicketPermissionSerializer
class LiveStockProvinceJahadSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
address = SystemAddressSerializer(read_only=True)
user_bank_info = BankCardSerializer(required=False)
class Meta:
model = LiveStockProvinceJahad
fields = '__all__'
class LiveStockProductSerializer(serializers.ModelSerializer):
class Meta:
model = LiveStockProduct
fields = '__all__'
class LiveStockRolseProductSerializer(serializers.ModelSerializer):
parent_product = LiveStockProductSerializer(read_only=True)
class Meta:
model = LiveStockRolseProduct
fields = '__all__'
class LiveStockAllocationsSerializer(serializers.ModelSerializer):
product = LiveStockRolseProductSerializer(read_only=True)
union = UnionSerializer(read_only=True)
cooperative = CooperativeSerializer(read_only=True)
jahad = LiveStockProvinceJahadSerializer(read_only=True)
class Meta:
model = LiveStockAllocations
fields = '__all__'
class CooperativeProductsShareSerializer(serializers.ModelSerializer):
cooperative = CooperativeForSharesSerializer(read_only=True)
product = LiveStockRolseProductSerializer(read_only=True)
class Meta:
model = CooperativeProductsShare
fields = '__all__'

59
LiveStock/Jahad/urls.py Normal file
View File

@@ -0,0 +1,59 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from LiveStock.Jahad import views as jahad_views
from LiveStock.Jahad.excel_processing import allocation_live_stock_excel, warehouse_live_stock_excel, \
live_stock_transaction_excel, cooperative_warehouse_excel, management_live_stock_excel, rancher_management, \
live_stock_product_excel
from LiveStock.Jahad.views import get_user_live_stock
router = DefaultRouter()
router.register(
r'profile',
jahad_views.LiveStockProvinceJahadViewSet,
basename="profile"
)
router.register(
r'live-stock-role-products',
jahad_views.LiveStockRolseProductViewset,
basename="live-stock-role-products"
)
router.register(
r'live-stock-allocation',
jahad_views.LiveStockAllocationsViewSet,
basename="live-stock-allocation"
)
router.register(
r'live-stock-product',
jahad_views.LiveStockProductViewset,
basename="live-stock-product"
)
router.register(
r'dashboard-live-stock-allocation',
jahad_views.DashboardLiveStockAllocationsViewSet,
basename="dashboard-live-stock-allocation"
)
router.register(
r'live-stock-warehouse-charge-allocation',
jahad_views.LiveStockWarehouseChargeAllocationsViewSet,
basename="live-stock-warehouse-charge-allocation"
)
router.register(
r'cooperative-shares',
jahad_views.CooperativeProductsShareViewSet,
basename="cooperative-shares"
)
urlpatterns = [
path('', include(router.urls)),
path('get_user_live_stock/', get_user_live_stock),
path('allocation_live_stock_excel/', allocation_live_stock_excel),
path('warehouse_live_stock_excel/', warehouse_live_stock_excel),
path('live_stock_transaction_excel/', live_stock_transaction_excel),
path('cooperative_warehouse_excel/', cooperative_warehouse_excel),
path('management_live_stock_excel/', management_live_stock_excel),
path('rancher_management/', rancher_management),
path('live_stock_product_excel/', live_stock_product_excel),
]

690
LiveStock/Jahad/views.py Normal file
View File

@@ -0,0 +1,690 @@
import threading
from datetime import datetime
from django.db.models import Sum, Q
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from LiveStock.Jahad.filterset import LiveStockAllocationsFilterSet, CooperativeProductsShareFilterSet
from LiveStock.Jahad.helpers import jahad_warehousing, union_warehousing, cooperative_warehousing
from LiveStock.Jahad.serializers import LiveStockProvinceJahadSerializer, LiveStockRolseProductSerializer, \
LiveStockAllocationsSerializer, LiveStockProductSerializer, CooperativeProductsShareSerializer
from LiveStock.Rancher.helpers import update_quota_rancher_threading
from LiveStock.Rancher.serializers import RancherSerializer
from LiveStock.Union.serializers import UnionSerializer
from LiveStock.helpers import CustomPagination, build_query
from LiveStock.models import LiveStockProvinceJahad, LiveStockRolseProduct, LiveStockAllocations, Union, Cooperative, \
Rancher, LiveStockProduct, CooperativeProductsShare
from authentication.models import SystemUserProfile
class LiveStockProvinceJahadViewSet(viewsets.ModelViewSet):
queryset = LiveStockProvinceJahad.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = LiveStockProvinceJahadSerializer
def retrieve(self, request, pk=None, *args, **kwargs):
if 'profile' in request.GET:
user = SystemUserProfile.objects.get(user=request.user, trash=False)
jahad = user.jahad_user.all()
serializer = self.serializer_class(jahad[0])
return Response(serializer.data, status=status.HTTP_200_OK)
class LiveStockRolseProductViewset(viewsets.ModelViewSet):
queryset = LiveStockRolseProduct.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = LiveStockRolseProductSerializer
def list(self, request, *args, **kwargs):
user = SystemUserProfile.objects.get(user=request.user, trash=False)
products = {
"bran":"سبوس",
"barley":"جو",
"soy":"سویا",
"corn":"ذرت",
"sheep_concentrate":"کنسانتره گوسفندی",
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
}
name =products[request.GET.get('name')]
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
if request.GET['role'] == 'LiveStockProvinceJahad':
products = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
, parent_product=product).first()
elif request.GET['role'] == 'Union':
products = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
parent_product=product).first()
else:
products = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
parent_product=product).first()
serializer = self.serializer_class(products)
return Response(serializer.data, status=status.HTTP_200_OK)
class LiveStockAllocationsViewSet(viewsets.ModelViewSet):
queryset = LiveStockAllocations.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = LiveStockAllocationsSerializer
pagination_class = CustomPagination
filterset_class = LiveStockAllocationsFilterSet
def create(self, request, *args, **kwargs):
user = SystemUserProfile.objects.get(user=request.user, trash=False)
product = LiveStockRolseProduct.objects.get(key=request.data['product_key'])
allocator = request.data['allocator']
receiver = request.data['receiver']
request.data.pop('allocator')
request.data.pop('receiver')
request.data.pop('product_key')
if allocator == 'LiveStockProvinceJahad':
jahad = LiveStockProvinceJahad.objects.get(user=user, trash=False)
jahad_roles_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False,parent_product__name=product.parent_product.name,trash=False).first()
if receiver != 'LiveStockProvinceJahad':
if request.data['weight'] > jahad_roles_product.total_remain_weight:
return Response({"result": "مقدار وارد شده بیشتر از باقی مانده انبار است !"},
status=status.HTTP_403_FORBIDDEN)
elif allocator == 'Cooperative':
cooperative = Cooperative.objects.get(user=user, trash=False)
cooperative_roles_product = LiveStockRolseProduct.objects.get(cooperative=cooperative,parent_product__name=product.parent_product.name, trash=False)
if receiver != 'Cooperative':
if request.data[
'weight'] + cooperative_roles_product.total_remain_weight > cooperative_roles_product.total_receipt_weight:
return Response({"result": "مقدار وارد شده بیشتر از سهمیه دریافتی است !"},
status=status.HTTP_403_FORBIDDEN)
else:
union = Union.objects.get(user=user, trash=False)
union_roles_product = LiveStockRolseProduct.objects.filter(union__isnull=False,parent_product__name=product.parent_product.name, trash=False).first()
if request.data['weight'] > union_roles_product.total_remain_weight:
return Response({"result": "مقدار وارد شده بیشتر از باقی مانده انبار است !"},
status=status.HTTP_403_FORBIDDEN)
if receiver == 'LiveStockProvinceJahad':
pass
elif receiver == 'Union':
union = Union.objects.get(key=request.data['buyer_key'], trash=False)
request.data.pop('buyer_key')
else:
if allocator == 'Cooperative':
pass
else:
cooperative = Cooperative.objects.get(key=request.data['buyer_key'], trash=False)
request.data.pop('buyer_key')
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
allocation = serializer.create(validated_data=request.data)
allocation.product = product
if allocator == 'LiveStockProvinceJahad':
allocation.jahad = jahad
allocation.allocate_from = "LiveStockProvinceJahad"
elif allocator == 'Cooperative':
allocation.cooperative = cooperative
allocation.allocate_from = "Cooperative"
else:
allocation.union = union
allocation.allocate_from = "Union"
if receiver == 'LiveStockProvinceJahad':
allocation.allocate_to = "LiveStockProvinceJahad"
allocation.charge = True
allocation.state = 'accepted'
elif receiver == 'Union':
allocation.union = union
allocation.allocate_to = "Union"
else:
allocation.cooperative = cooperative
allocation.allocate_to = "Cooperative"
if allocator == 'Cooperative':
allocation.charge = True
allocation.save()
if allocator == 'LiveStockProvinceJahad':
jahad_warehousing(product)
elif allocator == 'Cooperative':
pass
else:
union_warehousing(product)
if receiver == 'Union':
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product, union=union)
union_warehousing(reciver_product)
elif receiver == 'Cooperative':
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
cooperative=cooperative)
cooperative_warehousing(reciver_product)
else:
pass
return Response({"result": "با موفقیت ثبت شد!"}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk=None, *args, **kwargs):
allocation = LiveStockAllocations.objects.get(key=request.data['allocation_key'], trash=False)
request.data.pop('allocation_key')
if allocation.charge == True:
if allocation.allocate_from == 'LiveStockProvinceJahad':
if request.data['weight'] < allocation.weight:
allocations = LiveStockAllocations.objects.filter(jahad=allocation.jahad,product=allocation.product, trash=False)
charge = (allocations.filter(charge=True).exclude(id=allocation.id).aggregate(total=Sum('weight'))[
'total'] or 0) + request.data['weight']
jahad_alocations = allocations.filter(charge=False).aggregate(total=Sum('weight'))['total'] or 0
if charge < jahad_alocations:
return Response(
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
else:
allocations = LiveStockAllocations.objects.filter(cooperative=allocation.cooperative,product=allocation.product, trash=False)
charge = (allocations.filter(charge=True).exclude(id=allocation.id).aggregate(total=Sum('weight'))[
'total'] or 0) + request.data['weight']
if request.data['weight'] < allocation.weight:
if charge < allocation.product.total_allocated_weight:
return Response(
{"result": "به علت عدم همخوانی موجودی و فروش امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
elif request.data['weight'] > allocation.weight:
if charge > allocation.product.total_receipt_weight:
return Response(
{
"result": "به علت عدم همخوانی سهمیه دریافتی و موجودی انبار امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
else:
if request.data['weight'] > allocation.weight:
if allocation.allocate_from == 'LiveStockProvinceJahad':
jahad_products = allocation.product
dif = request.data['weight'] - allocation.weight
if dif > jahad_products.total_remain_weight:
return Response(
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
else:
union_products = allocation.product
dif = request.data['weight'] - allocation.weight
if dif > union_products.total_remain_weight:
return Response(
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
elif request.data['weight'] < allocation.weight:
dif = allocation.weight - request.data['weight']
if allocation.allocate_to == 'Union':
union_role_product = LiveStockRolseProduct.objects.get(union=allocation.union,parent_product=allocation.product.parent_product, trash=False)
if dif > union_role_product.total_remain_weight:
return Response(
{"result": "به علت عدم همخوانی موجودی مقصد امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
elif allocation.allocate_to == 'Cooperative':
cooperative_role_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product,
trash=False)
if dif > (cooperative_role_product.total_receipt_weight - cooperative_role_product.total_weight):
return Response(
{"result": "به علت عدم همخوانی موجودی مقصد امکان ویرایش با این وزن وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
serializer = self.serializer_class(allocation)
serializer.update(instance=allocation, validated_data=request.data)
product = allocation.product
if allocation.allocate_from == 'LiveStockProvinceJahad':
jahad_warehousing(product)
elif allocation.allocate_from == 'Cooperative':
pass
else:
union_warehousing(product)
if allocation.allocate_to == 'Union':
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
union=allocation.union)
union_warehousing(reciver_product)
elif allocation.allocate_to == 'Cooperative':
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
cooperative=allocation.cooperative)
cooperative_warehousing(reciver_product)
else:
pass
return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs):
user = SystemUserProfile.objects.get(user=request.user, trash=False)
products = {
"bran":"سبوس",
"barley":"جو",
"soy":"سویا",
"corn":"ذرت",
"sheep_concentrate":"کنسانتره گوسفندی",
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
}
name =products[request.GET.get('name')]
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
if request.GET['role'] == 'LiveStockProvinceJahad':
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, allocate_from="LiveStockProvinceJahad",
trash=False, product__parent_product=product).order_by(
'id').exclude(allocate_to='LiveStockProvinceJahad')
elif request.GET['role'] == 'Union':
allocations = LiveStockAllocations.objects.filter(union__isnull=False, trash=False, allocate_from="Union",
product__parent_product=product).order_by('id')
else:
allocations = LiveStockAllocations.objects.filter(cooperative__user=user, charge=False,
allocate_to="Cooperative",
trash=False, product__parent_product=product).order_by(
'id')
date1 = request.GET.get('date1')
date2 = request.GET.get('date2')
if date1 and date2:
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
allocations = allocations.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page_size = request.query_params.get('page_size', None)
if page_size:
self.pagination_class.page_size = int(page_size)
page = self.paginate_queryset(allocations)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(allocations, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def destroy(self, request, pk=None, *args, **kwargs):
allocation = LiveStockAllocations.objects.get(key=request.GET["allocation_key"])
product = allocation.product
if allocation.allocate_from == 'LiveStockProvinceJahad':
if allocation.allocate_to == 'LiveStockProvinceJahad':
roles_product = allocation.product
elif allocation.allocate_to == 'Union':
roles_product = LiveStockRolseProduct.objects.get(union=allocation.union,parent_product=allocation.product.parent_product)
else:
roles_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product)
if allocation.weight > roles_product.total_remain_weight:
if allocation.allocate_to == 'Cooperative':
if roles_product.total_receipt_weight >= allocation.weight:
pass
else:
return Response(
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
elif allocation.allocate_from == 'Union':
if allocation.allocate_to == 'Union':
roles_product = allocation.product
else:
roles_product = LiveStockRolseProduct.objects.get(cooperative=allocation.cooperative,parent_product=allocation.product.parent_product)
if allocation.weight > roles_product.total_remain_weight:
if allocation.allocate_to == 'Cooperative':
if roles_product.total_receipt_weight >= allocation.weight:
pass
else:
return Response(
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
else:
cooperative_roles_product = allocation.product
if allocation.weight > cooperative_roles_product.total_remain_weight:
return Response(
{"result": "به علت عدم همخوانی موجودی و تخصیصات امکان حذف وجود ندارد!"},
status=status.HTTP_403_FORBIDDEN)
allocation.trash = True
allocation.save()
if allocation.allocate_from == 'LiveStockProvinceJahad':
jahad_warehousing(product)
elif allocation.allocate_from == 'Cooperative':
pass
else:
union_warehousing(product)
if allocation.allocate_to == 'Union':
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
union=allocation.union)
union_warehousing(reciver_product)
elif allocation.allocate_to == 'Cooperative':
reciver_product = LiveStockRolseProduct.objects.get(parent_product=product.parent_product,
cooperative=allocation.cooperative)
cooperative_warehousing(reciver_product)
else:
pass
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
class CooperativeProductsShareViewSet(viewsets.ModelViewSet):
queryset = CooperativeProductsShare.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = CooperativeProductsShareSerializer
pagination_class = CustomPagination
filterset_class = CooperativeProductsShareFilterSet
def update(self, request, pk=None, *args, **kwargs):
share = CooperativeProductsShare.objects.get(key=request.data['share_key'], trash=False)
request.data.pop('share_key')
serializer = self.serializer_class(share)
serializer.update(instance=share, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs):
shares = CooperativeProductsShare.objects.filter(product__name=request.GET['name'], trash=False).order_by(
'id')
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
shares = shares.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page_size = request.query_params.get('page_size', None)
if page_size:
self.pagination_class.page_size = int(page_size)
page = self.paginate_queryset(shares)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(shares, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class LiveStockProductViewset(viewsets.ModelViewSet):
queryset = LiveStockProduct.objects.all()
permission_classes = [AllowAny]
serializer_class = LiveStockProductSerializer
def list(self, request, *args, **kwargs):
products = {
"bran":"سبوس",
"barley":"جو",
"soy":"سویا",
"corn":"ذرت",
"sheep_concentrate":"کنسانتره گوسفندی",
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
}
name =products[request.GET.get('name')]
products = LiveStockProduct.objects.filter(trash=False, name=name).first()
serializer = self.serializer_class(products)
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
products = LiveStockProduct.objects.get(key=request.data['key'])
request.data.pop('key')
serializer = self.serializer_class(products)
serializer.update(instance=products, validated_data=request.data)
# todo:اگه نیاز شده با ترد بنویس تا همه دامدار ها اپدیت بشن
# send = threading.Thread(target=update_quota_rancher_threading)
# send.start()
return Response(serializer.data, status=status.HTTP_200_OK)
class DashboardLiveStockAllocationsViewSet(viewsets.ModelViewSet):
queryset = LiveStockAllocations.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = LiveStockAllocationsSerializer
filterset_class = LiveStockAllocationsFilterSet
def list(self, request, *args, **kwargs):
products = {
"bran":"سبوس",
"barley":"جو",
"soy":"سویا",
"corn":"ذرت",
"sheep_concentrate":"کنسانتره گوسفندی",
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
}
role = request.GET.get('role')
name =products[request.GET.get('name')]
user = SystemUserProfile.objects.get(user=request.user, trash=False)
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
if request.GET['role'] == 'LiveStockProvinceJahad':
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, trash=False,
product__parent_product=product).order_by('id')
roles_new_product = LiveStockRolseProduct.objects.filter(jahad__isnull=False, trash=False
, parent_product=product).first()
elif request.GET['role'] == 'Union':
allocations = LiveStockAllocations.objects.filter(union__user=user, trash=False,
product__parent_product=product).order_by('id')
roles_new_product = LiveStockRolseProduct.objects.filter(union__user=user, trash=False,
parent_product=product).first()
else:
allocations = LiveStockAllocations.objects.filter(cooperative__user=user, trash=False,
product__parent_product=product).order_by('id')
roles_new_product = LiveStockRolseProduct.objects.filter(cooperative__user=user, trash=False,
parent_product=product).first()
date1 = request.GET.get('date1')
date2 = request.GET.get('date2')
if date1 and date2:
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
allocations = allocations.filter(
build_query(self.filterset_class.Meta.fields, value)
)
jahat_to_union = allocations.filter(jahad__isnull=False, allocate_to='Union')
jahat_to_cooperative = allocations.filter(jahad__isnull=False, allocate_to='Cooperative')
union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False, trash=False, allocate_to='Cooperative')
if role == 'Union':
union_to_cooperative = LiveStockAllocations.objects.filter(union__isnull=False,trash=False, allocate_to='Cooperative')
jahat_to_union_weight = jahat_to_union.aggregate(total=Sum('weight'))[
'total'] or 0
jahat_to_union_real_weight = jahat_to_union.aggregate(total=Sum('real_weight'))[
'total'] or 0
jahat_to_cooperative_weight = jahat_to_cooperative.aggregate(total=Sum('weight'))[
'total'] or 0
jahat_to_cooperative_real_weight = jahat_to_cooperative.aggregate(total=Sum('real_weight'))[
'total'] or 0
union_to_cooperative_weight = union_to_cooperative.aggregate(total=Sum('weight'))[
'total'] or 0
union_to_cooperative_real_weight = union_to_cooperative.aggregate(total=Sum('real_weight'))[
'total'] or 0
if role =='Union':
role_product_union = roles_new_product.total_remain_weight
role_product_cooperative = 0
role_product_cooperative_receipt_weight = 0
elif role == 'Cooperative':
role_product_union = 0
role_product_cooperative = roles_new_product.total_remain_weight
role_product_cooperative_receipt_weight = roles_new_product.total_receipt_weight
else:
roles_product = LiveStockRolseProduct.objects.filter(trash=False, parent_product=product)
union_remain = roles_product.filter(union__isnull=False)
cooperative_remain = roles_product.filter(cooperative__isnull=False)
role_product_union = union_remain.aggregate(total=Sum('total_remain_weight'))[
'total'] or 0
role_product_cooperative = cooperative_remain.aggregate(total=Sum('total_remain_weight'))[
'total'] or 0
role_product_cooperative_receipt_weight = cooperative_remain.aggregate(total=Sum('total_receipt_weight'))[
'total'] or 0
if allocations:
dict1 = {
"total_weight": roles_new_product.total_weight,
"jahad_to_union": jahat_to_union_weight,
"jahat_to_union_real_weight": jahat_to_union_real_weight,
"jahat_to_cooperative": jahat_to_cooperative_weight,
"jahat_to_cooperative_real_weight": jahat_to_cooperative_real_weight,
"allocation_count": roles_new_product.total_allocated_weight,
"union_to_cooperative": union_to_cooperative_weight,
"union_to_cooperative_real_weight": union_to_cooperative_real_weight,
"total_remain_weight_jahad": roles_new_product.total_remain_weight,
"total_remain_weight_union": role_product_union,
"total_remain_weight_cooperative": role_product_cooperative,
"role_product_cooperative_receipt_weight": role_product_cooperative_receipt_weight,
"total_remain_weight": roles_new_product.total_remain_weight,
}
else:
dict1 = {
"total_weight": 0,
"jahad_to_union": 0,
"jahat_to_cooperative": 0,
"allocation_count": 0,
"union_to_cooperative": 0,
"total_remain_weight_jahad": 0,
"total_remain_weight_union": 0,
"total_remain_weight_cooperative": 0,
"total_remain_weight": 0,
"jahat_to_union_real_weight": 0,
"union_to_cooperative_real_weight": 0,
"jahat_to_cooperative_real_weight": 0,
"role_product_cooperative_receipt_weight": role_product_cooperative_receipt_weight,
}
return Response(dict1, status=status.HTTP_200_OK)
class LiveStockWarehouseChargeAllocationsViewSet(viewsets.ModelViewSet):
queryset = LiveStockAllocations.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = LiveStockAllocationsSerializer
pagination_class = CustomPagination
filterset_class = LiveStockAllocationsFilterSet
def list(self, request, *args, **kwargs):
user = SystemUserProfile.objects.get(user=request.user, trash=False)
products = {
"bran":"سبوس",
"barley":"جو",
"soy":"سویا",
"corn":"ذرت",
"sheep_concentrate":"کنسانتره گوسفندی",
"high_cow_concentrate":"کنسانتره گاو شیری پرتولید",
"medium_cow_concentrate":"کنسانتره گاو شیری متوسط",
"fattening_calf_concentrate":"کنسانتره گوساله پرواری",
}
name =products[request.GET.get('name')]
product = LiveStockProduct.objects.filter(trash=False, name=name).first()
if request.GET['role'] == 'LiveStockProvinceJahad':
allocations = LiveStockAllocations.objects.filter(jahad__isnull=False, trash=False,
product__parent_product=product,
allocate_to='LiveStockProvinceJahad').order_by('id')
elif request.GET['role'] == 'Union':
allocations = LiveStockAllocations.objects.filter(allocate_from='LiveStockProvinceJahad', union__isnull=False,
trash=False, product__parent_product=product).order_by(
'id')
else:
# allocations = LiveStockAllocations.objects.filter(
# allocate_from__in=('LiveStockProvinceJahad', 'Union', 'Cooperative'), cooperative__user=user,
# trash=False, product__parent_product=product).order_by('id')
allocations = LiveStockAllocations.objects.filter(
charge=True, cooperative__user=user,
trash=False, product__parent_product=product).order_by('id')
date1 = request.GET.get('date1')
date2 = request.GET.get('date2')
if date1 and date2:
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
allocations = allocations.filter(date__date__gte=date1, date__date__lte=date2)
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
allocations = allocations.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page_size = request.query_params.get('page_size', None)
if page_size:
self.pagination_class.page_size = int(page_size)
page = self.paginate_queryset(allocations)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(allocations, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def get_user_live_stock(request):
type = request.GET['type']
if type == 'Union':
unions = Union.objects.filter(trash=False).order_by('id')
serializer = UnionSerializer(unions, many=True)
else:
cooperatives = Cooperative.objects.filter(trash=False).order_by('id')
serializer = RancherSerializer(cooperatives, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

View File

@@ -0,0 +1,174 @@
import datetime
import hashlib
from io import BytesIO
import openpyxl
import requests
from django.contrib.auth.models import Group, User
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from LiveStock.models import LiveStock, Rancher, Cooperative
#todo:فعلا چون دامدار تکراری داریم نمیشه ثبت کر باید از طریف آدرس بریم
from authentication.models import SystemUserProfile, Province, City, SystemAddress
from authentication.register import ARTA_REGISTER
from panel.admin import PROJECT_API_KEY
from panel.convert_date import convert_to_shamsi
def add_rancher_to_live_stock(request):
livestock=LiveStock.objects.filter(trash=False)
for l in livestock:
rancher=Rancher.objects.filter(trash=False,herd_code=l.herd_code).first()
l.rancher=rancher
l.save()
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def create_live_stock_and_rancher_from_excel(request):
file = request.FILES['file'].read()
read = openpyxl.load_workbook(BytesIO(file), data_only=True)
sheet = read.active
group = Group.objects.get(name='Rancher')
password = '123456'
result_list=[]
yesterday= datetime.datetime.now().date() - datetime.timedelta(days=1)
birth_day=convert_to_shamsi(day=yesterday.day,
month=yesterday.month,
year=yesterday.year).replace('-','/')
for i, row in enumerate(sheet.iter_rows(values_only=True)):
if i <= 1:
continue
first_name = row[1]
last_name = row[2]
rancher_name = row[3]
type_rancher = row[4]
herd_code = row[5]
epidemiological_code = row[6]
postal_code = row[7]
type_live_stock = row[8]
gender = row[9]
national_id = row[10]
mobile = row[11]
city = row[12]
range_live_stock = row[13]
if not herd_code:
herd_code = '0000' + str(national_id)
mobile = str(mobile)
if len(mobile) < 10:
continue
if len(mobile) == 10:
mobile = '0' + mobile
try:
city_id = City.objects.filter(trash=False, name=city).first()
province = Province.objects.filter(trash=False,key=city_id.province.key).first()
if not Rancher.objects.filter(Q(herd_code=herd_code) | Q(user__mobile=mobile) | Q(mobile=mobile)
,trash=False).exists():
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
data = {
"username": mobile,
"first_name": first_name,
"last_name": last_name,
"password": hashed_password,
"national_code": national_id,
"role": "Rancher",
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
system_profile = SystemUserProfile(
mobile=mobile,
first_name=first_name,
last_name=last_name,
fullname=first_name+' ' + last_name,
user=user,
base_order=base_id,
password=password,
birthday=datetime.datetime.now().date(),
city=city_id,
province=province
)
system_profile.save()
system_profile.role.add(group)
address = SystemAddress(
province=province,
city=city_id,
address='',
)
address.save()
system_profile=SystemUserProfile.objects.filter(trash=False, mobile=mobile).first()
cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
rancher = Rancher(
user=system_profile,
cooperative=cooperative,
name=rancher_name,
mobile=mobile,
fullname=first_name + ' ' + last_name,
city=city,
herd_name=rancher_name,
postal_code=postal_code,
epidemiological_code=epidemiological_code,
herd_code=herd_code,
national_id=national_id,
type='rural' if type_rancher == 'روستایی' else 'industrial'
)
rancher.save()
rancher = Rancher.objects.filter(Q(herd_code=herd_code) | Q(user__mobile=mobile) | Q(mobile=mobile)
,trash=False).first()
if rancher:
live_stock_count = LiveStock.objects.filter(trash=False, herd_code=rancher.herd_code,
type=type_live_stock)\
.count()
if live_stock_count > int(range_live_stock):
new_range = live_stock_count - range_live_stock
for _i in range(new_range):
live_stock = LiveStock.objects.filter(
herd_code=rancher.herd_code,
type=type_live_stock,
trash=False
).first()
live_stock.trash = True
live_stock.save()
elif live_stock_count < int(range_live_stock):
new_range = range_live_stock - live_stock_count
for _i in range(new_range):
live_stock = LiveStock(
herd_code=rancher.herd_code,
type=type_live_stock,
birth_day=birth_day,
birth_day_gh=yesterday,
gender=gender,
)
live_stock.save()
except:
result_list.append(rancher_name)
return Response(result_list)

View File

@@ -0,0 +1,22 @@
from django_filters import rest_framework as filters
from LiveStock.models import LiveStock
class LiveStockFilterSet(filters.FilterSet):
class Meta:
model = LiveStock
fields = [
'national_id_livestock_code',
'herd_code',
'type',
'gender',
'contractor_code',
'unique_identifier',
'agent',
'registering_user',
'rancher__user__mobile',
'rancher__user__first_name',
'rancher__user__last_name',
'rancher__user__fullname'
]

View File

@@ -0,0 +1,19 @@
from django.http import HttpResponse
from LiveStock.helpers import convert_to_miladi
from LiveStock.models import LiveStock, LiveStockRolseProduct, LiveStockProduct, Rancher
def add_birthday(reqeust):
live_stock=LiveStock.objects.filter(trash=False,birth_day_gh__isnull=True).only('birth_day')
for l in live_stock:
birth_day=l.birth_day.split('/')
birth_day_gh=convert_to_miladi(year=int(birth_day[0]),month=int(birth_day[1]),day=int(birth_day[2]))
l.birth_day_gh=birth_day_gh
l.save()
return HttpResponse('ok')
def add_live_stock(request):
rancher=Rancher.objects.get(herd_code='139894930',trash=False)
for _i in rancher(110):
pass

View File

@@ -0,0 +1,36 @@
from django.db.models import Sum
from rest_framework import serializers
from LiveStock.Cooperative.serializers import CooperativeSerializer
from LiveStock.Rancher.serializers import RancherSerializer
from LiveStock.models import LiveStock, Rancher
import datetime
class LiveStockSerializer(serializers.ModelSerializer):
rancher = serializers.SerializerMethodField('get_rancher')
age = serializers.SerializerMethodField('get_age')
class Meta:
model = LiveStock
fields = '__all__'
def get_rancher(self,instance):
rancher=Rancher.objects.filter(herd_code=instance.herd_code).first()
ser_data=RancherSerializer(rancher)
return ser_data.data
def get_age(self,instance):
if instance.birth_day_gh:
now=datetime.datetime.now().date()
age=(now - instance.birth_day_gh.date()).days
return age
else:
return None
class PosLiveStockSerializer(serializers.ModelSerializer):
cooperative=CooperativeSerializer(read_only=True)
class Meta:
model = Rancher
fields = ['key','fullname','cooperative','mobile','city','herd_code','national_id','allow_buy','weight_allocation_heavy','weight_allocation_light']

View File

@@ -0,0 +1,28 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from LiveStock.LiveStoksAndPoultry import views as live_stock_views
from LiveStock.LiveStoksAndPoultry.excel_processing import create_live_stock_and_rancher_from_excel
from LiveStock.LiveStoksAndPoultry.helpers import add_birthday
from LiveStock.LiveStoksAndPoultry.views import dashboard_live_stock
from LiveStock.Rancher.excel_processing import get_rancher_excel, get_union_excel, get_cooperative_excel
router = DefaultRouter()
router.register(
r'live-stock-view',
live_stock_views.LiveStockViewSet,
basename="live-stock-view"
)
router.register(
r'pos-live-stock',
live_stock_views.PosLiveStockViewSet,
basename="pos-live-stock"
)
urlpatterns = [
path('', include(router.urls)),
path('dashboard_live_stock/', dashboard_live_stock),
path('add_birthday/', add_birthday),
path('create_live_stock_and_rancher_from_excel/', create_live_stock_and_rancher_from_excel),
]

View File

@@ -0,0 +1,459 @@
from datetime import datetime, timedelta
import jdatetime
from dateutil.relativedelta import relativedelta
from django.db.models import Count, Q
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from LiveStock.LiveStoksAndPoultry.filterset import LiveStockFilterSet
from LiveStock.LiveStoksAndPoultry.serializers import LiveStockSerializer, PosLiveStockSerializer
from LiveStock.Rancher.helpers import update_one_rancher
from LiveStock.helpers import build_query, CustomPagination, convert_to_miladi
from LiveStock.models import LiveStock, Rancher, LiveStockProduct, LiveStockRolseProduct, Cooperative, Union, \
CooperativeProductsShare
from authentication.models import SystemUserProfile
from panel.models import POSMachine, PosMachineTransactions
from panel.validate_headers import PosDeviceValidator
class LiveStockViewSet(viewsets.ModelViewSet):
queryset = LiveStock.objects.filter(trash=False).order_by('-birth_day_gh')
permission_classes = [TokenHasReadWriteScope]
serializer_class = LiveStockSerializer
filterset_class = LiveStockFilterSet
pagination_class = CustomPagination
def list(self, request, *args, **kwargs):
role = request.GET['role']
user = SystemUserProfile.objects.get(user=request.user, trash=False)
type=request.GET.get('type')
if type == 'archive':
live_stocks=LiveStock.objects.filter(trash=True,archive=True).order_by('-birth_day_gh')
else:
live_stocks=LiveStock.objects.filter(trash=False).order_by('-birth_day_gh')
if role == 'Cooperative':
# todo:فعلا چون دامدار تکراری داریم نمیشه از طریق دامدار پیداکرد باید از طریف آدرس بریم
cooperative = Cooperative.objects.get(user=user, trash=False)
ranchers = Rancher.objects.filter(city=cooperative.address.city.name).values_list('herd_code',
flat=True).distinct()
live_stocks = live_stocks.filter(herd_code__in=ranchers)
date1 = request.GET.get('date1')
date2 = request.GET.get('date2')
if date1 and date2:
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
live_stocks = live_stocks.filter(birth_day__gte=date1, birth_day__lte=date2)
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
live_stocks = live_stocks.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page = self.paginate_queryset(live_stocks)
if page is not None:
serializer = self.serializer_class(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(live_stocks, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def create(self, request, *args, **kwargs):
rancher = Rancher.objects.get(key=request.data['rancher_key'])
request.data.pop('rancher_key')
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
live_stock = serializer.create(validated_data=request.data)
live_stock.rancher = rancher
live_stock.herd_code = rancher.herd_code
live_stock.contractor_code = rancher.contractor_code
live_stock.save()
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk=None, *args, **kwargs):
user=SystemUserProfile.objects.filter(trash=False,user=request.user).first()
filter_kwargs = {'key': request.data['live_stock_key']}
if 'return_from_archive' in request.data.keys():
filter_kwargs['trash']=True
filter_kwargs['archive']=True
else:
filter_kwargs['trash'] = False
live_stock = LiveStock.objects.get(**filter_kwargs)
live_stocks = LiveStock.objects.filter(herd_code=live_stock.herd_code, trash=False)
rancher = Rancher.objects.get(herd_code=live_stock.herd_code)
request.data.pop('live_stock_key')
serializer = self.serializer_class(live_stock)
if 'herd_code' in request.data.keys() and request.data['herd_code']:
rancher.herd_code = request.data['herd_code']
rancher.save()
live_stocks.update(herd_code=request.data['herd_code'])
if 'return_from_archive' in request.data.keys():
live_stock.archive = False
live_stock.trash = False
live_stock.returner_from_archive=user.fullname
live_stock.return_from_archive_date=datetime.now()
live_stock.save()
request.data.pop('return_from_archive')
serializer.update(instance=live_stock, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_200_OK)
def destroy(self, request, *args, **kwargs):
user=SystemUserProfile.objects.filter(trash=False,user=request.user).first()
live_stock = LiveStock.objects.get(key=request.GET['live_stock_key'], trash=False)
if not live_stock.birth_day_gh:
year, month, day = map(int, live_stock.birth_day.split('/'))
live_stock.birth_day_gh = convert_to_miladi(year, month, day)
live_stock.save()
live_stock.trash=True
live_stock.archive=True
live_stock.archiver=user.fullname
live_stock.archive_date=datetime.now()
live_stock.age_of_archive=(datetime.now().date() - live_stock.birth_day_gh.date()).days
live_stock.save()
return Response({"result":"با موفقیت بایگانی شد."}, status=status.HTTP_200_OK)
class PosLiveStockViewSet(viewsets.ModelViewSet):
queryset = Rancher.objects.all()
permission_classes = [AllowAny]
serializer_class = PosLiveStockSerializer
def get_transactions_month(self,natcode):
import json
transactions = PosMachineTransactions.objects.filter(natcode=natcode,paid=True,live_stock=True, trash=False)
has_month_data = False
last_month = None
earliest_transaction_date = None
for transaction in transactions:
try:
additional_data = json.loads(transaction.additional)
if 'month' in additional_data and isinstance(additional_data['month'], list):
has_month_data = True
for month in additional_data['month']:
if last_month is None or month > last_month:
last_month = month
except (json.JSONDecodeError, AttributeError):
pass
if hasattr(transaction, 'create_date'):
created_date = transaction.create_date
if earliest_transaction_date is None or created_date < earliest_transaction_date:
earliest_transaction_date = created_date
future_months = []
if not transactions:
base_date = jdatetime.date.today().togregorian() - relativedelta(months=1)
include_current = True
elif has_month_data and last_month:
year = int(str(last_month)[:4])
month = int(str(last_month)[4:6])
base_date = jdatetime.date(year, month, 1).togregorian()
include_current = False
else:
if earliest_transaction_date:
base_date = earliest_transaction_date
else:
base_date = jdatetime.date.today().togregorian()
include_current = False
start_offset = 0 if include_current else 1
for i in range(start_offset, start_offset + 6):
future_date = base_date + relativedelta(months=i)
jd_future = jdatetime.date.fromgregorian(date=future_date)
future_months.append(int(f"{jd_future.year}{jd_future.month:02d}"))
return future_months
def list(self, request, *args, **kwargs):
validator = PosDeviceValidator(request)
validation_error = validator.validation_version()
if validation_error:
return validation_error
validation_device = validator.validation_device()
if not validation_device:
return Response({"result": "نشست شما منقضی شده لطفا محدد وارد شوید!"}, status=status.HTTP_401_UNAUTHORIZED)
pos = POSMachine.objects.get(pos_id=validation_device)
if pos.cooperative is None:
return Response({"result": "دستگاه شما برای مدیریت امور دام تعریف نشده است!"},
status=403)
if int(validator.device_version) < 218:
return Response(
{"result": "لطفا جهت بروزرسانی نسخه دستگاه کارت خوان با پشتیبانی دستگاه ارتباط بگیرید!"},
status=status.HTTP_403_FORBIDDEN)
if 'nath_id' in request.GET:
ranchers = Rancher.objects.filter(national_id=request.GET['nath_id'], trash=False).first()
if not ranchers:
return Response({"result": "دامدار یافت نشد!"},
status=403)
union = Union.objects.filter(trash=False).first()
if 'product_key' in request.GET:
product = LiveStockRolseProduct.objects.filter(key=request.GET['product_key'], trash=False).select_related(
'parent_product').only('parent_product__price', 'parent_product__name', 'parent_product__image',
'parent_product__light_wight', 'parent_product__heavy_wight',
'parent_product__shipping_price', 'parent_product__union_price',
'parent_product__cooperative_price').first()
else:
product = LiveStockRolseProduct.objects.filter(cooperative=pos.cooperative, trash=False).select_related(
'parent_product').only('parent_product__price', 'parent_product__name', 'parent_product__image',
'parent_product__light_wight', 'parent_product__heavy_wight',
'parent_product__shipping_price', 'parent_product__union_price',
'parent_product__cooperative_price').first()
main_product = product.parent_product
share = CooperativeProductsShare.objects.get(product=main_product, cooperative=pos.cooperative, trash=False)
if ranchers.type == 'rural':
heavy_rate= product.parent_product.heavy_wight
light_rate= product.parent_product.light_wight
else:
heavy_rate= product.parent_product.heavy_wight_industrial
light_rate= product.parent_product.light_wight_industrial
month_list = self.get_transactions_month(request.GET['nath_id'])
shares_list = []
if share.union_price > 0:
shares_list.append({
"name":'union',
"shaba":union.account,
"price":share.union_price,
})
if share.company_price > 0:
shares_list.append({
"name":'company',
"shaba":"IR170150000003100050545702",
"price":share.company_price,
})
if pos.cooperative.first_sub_cooperative_price > 0:
shares_list.append({
"name":'first_sub_cooperative',
"shaba":pos.cooperative.first_sub_cooperative_account,
"price":pos.cooperative.first_sub_cooperative_price,
})
if pos.cooperative.second_sub_cooperative_price > 0:
shares_list.append({
"name":'second_sub_cooperative',
"shaba":pos.cooperative.second_sub_cooperative_price,
"price":pos.cooperative.second_sub_cooperative_price,
})
dict1 = {
"title": [
{"key": "نام و نام خانوادگی", "value": ranchers.fullname if ranchers.fullname else ranchers.user.fullname},
{"key": "موبایل", "value": ranchers.mobile},
{"key": "وزن کل خریداری شده", "value": str(ranchers.total_weight)}
],
"key": ranchers.key,
"herd_code": ranchers.herd_code,
"national_id": ranchers.national_id,
"fullname": ranchers.fullname if ranchers.fullname else ranchers.user.fullname,
"type": ranchers.type,
"mobile": ranchers.mobile,
"allow_buy": ranchers.allow_buy,
"more_than_inventory": True,
"pos_owners": [],
"allow_buy_message": " ",
"real_light_livestock": ranchers.light_livestock, # تعداد تعیین شده دام توسط سامانه
"real_heavy_livestock": ranchers.heavy_livestock, # تعداد تعیین شده دام توسط سامانه
"real_dhi_livestock": 0, # تعداد تعیین شده دام توسط سامانه
"weight_quota_heavy": ranchers.weight_quota_heavy, # سهمیه قابل دریافت
"weight_quota_light": ranchers.weight_quota_light, # سهمیه قابل دریافت
"weight_quota_dhi": ranchers.dhi_amount, # سهمیه قابل دریافت
"heavy_rate": heavy_rate, # نرخ تبدیل جهت دریافت سهمیه
"light_rate": light_rate, # نرخ تبدیل جهت دریافت سهمیه
"dhi_rate": product.parent_product.heavy_wight_dha, # نرخ تبدیل جهت دریافت سهمیه
"round_rate": 1, # مضرب رند کردن فروش
"total_weight": ranchers.total_weight, # کل خرید دامدار ریم د دمش
"product_total_weight": product.total_weight,
"product_total_allocated_weight": product.total_allocated_weight,
"product_total_remain_weight": product.total_remain_weight,
"product_name": product.parent_product.name,
"product_image": product.parent_product.image,
"product_price": share.price,
"cooperative_price_with_shipping": share.price + share.shipping_price + share.cooperative_price,
"cooperative_price_without_shipping": share.price + share.cooperative_price,
"union_price": share.union_price,
"union_shaba": union.account,
"shares": shares_list,
"cooperative_shaba": pos.cooperative.account,
"month_list": month_list,
}
return Response(dict1, status=status.HTTP_200_OK)
return Response({"resut": "کد ملی وارد نشده است!"}, status=status.HTTP_403_FORBIDDEN)
# class DashboardLiveStockViewSet(viewsets.ModelViewSet):
# queryset = LiveStock.objects.filter(trash=False)
# permission_classes = [TokenHasReadWriteScope]
# serializer_class = LiveStockSerializer
# filterset_class = LiveStockFilterSet
#
# def list(self, request, *args, **kwargs):
# role = request.GET['role']
# user = SystemUserProfile.objects.get(user=request.user, trash=False)
# if role == 'Cooperative':
# # todo:فعلا چون دامدار تکراری داریم نمیشه از طریق دامدار پیداکرد باید از طریف آدرس بریم
# cooperative = Cooperative.objects.get(user=user, trash=False)
# ranchers = Rancher.objects.filter(city=cooperative.address.city.name).values_list('herd_code',
# flat=True).distinct()
# live_stocks = self.queryset.filter(herd_code__in=ranchers)
# else:
# live_stocks = self.queryset
# date1 = request.GET.get('date1')
# date2 = request.GET.get('date2')
# if date1 and date2:
# date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
# date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
# live_stocks = live_stocks.filter(birth_day__gte=date1, birth_day__lte=date2)
#
# value = request.GET.get('value')
# search = request.GET.get('search')
# if value and search == 'filter':
# if search != 'undefined' and search.strip():
# live_stocks = live_stocks.filter(
# build_query(self.filterset_class.Meta.fields, value)
# )
# sheep = live_stocks.filter(type='گوسفند').count()
# goat = live_stocks.filter(type='بز').count()
# cow = live_stocks.filter(type='گاو').count()
# horse = live_stocks.filter(type='اسب').count()
# camel = live_stocks.filter(type='شتر').count()
# light_livestock = live_stocks.filter(type__in=('بز', 'گوسفند')).count()
# heavy_livestock = live_stocks.filter(type__in=('گاو', 'اسب', 'شتر')).count()
#
# dict1={
# 'live_stocks_count':live_stocks.count(),
# "sheep":sheep,
# "goat":goat,
# "cow":cow,
# "horse":horse,
# "camel":camel,
# "light_livestock":light_livestock,
# "heavy_livestock":heavy_livestock,
#
# }
# return Response(dict1, status=status.HTTP_200_OK)
@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def dashboard_live_stock(request):
role = request.GET['role']
user = SystemUserProfile.objects.get(user=request.user, trash=False)
type = request.GET.get('type')
if type == 'archive':
live_stocks = LiveStock.objects.filter(trash=True, archive=True).only('type')
else:
live_stocks = LiveStock.objects.filter(trash=False).only('type')
if role == 'Cooperative':
cooperative = Cooperative.objects.get(user=user, trash=False)
ranchers = Rancher.objects.filter(city=cooperative.address.city.name).values_list('herd_code',
flat=True).distinct()
live_stocks = live_stocks.filter(herd_code__in=ranchers)
date1 = request.GET.get('date1')
date2 = request.GET.get('date2')
if date1 and date2:
date1 = datetime.strptime(str(request.GET['date1']), '%Y-%m-%d').date()
date2 = datetime.strptime(str(request.GET['date2']), '%Y-%m-%d').date()
live_stocks = live_stocks.filter(birth_day__gte=date1, birth_day__lte=date2)
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
live_stocks = live_stocks.filter(
build_query(LiveStockFilterSet.Meta.fields, value)
)
counts = live_stocks.values('type').annotate(total=Count('id'))
count_dict = {item['type']: item['total'] for item in counts}
light_livestock = count_dict.get('بز', 0) + count_dict.get('گوسفند', 0)
heavy_livestock = count_dict.get('گاو', 0) + count_dict.get('اسب', 0) + count_dict.get('شتر', 0)
result = {
'live_stocks_count': sum(count_dict.values()),
"sheep": count_dict.get('گوسفند', 0),
"goat": count_dict.get('بز', 0),
"cow": count_dict.get('گاو', 0),
"horse": count_dict.get('اسب', 0),
"camel": count_dict.get('شتر', 0),
"light_livestock": light_livestock,
"heavy_livestock": heavy_livestock,
}
return Response(result, status=status.HTTP_200_OK)
from datetime import date, timedelta
def archive_live_stock(request):
today = date.today()
archive_msg = 'بایگانی خودکار به علت سن بالا'
stocks_to_convert = LiveStock.objects.filter(trash=False, birth_day_gh__isnull=True)
for stock in stocks_to_convert:
try:
year, month, day = map(int, stock.birth_day.split('/'))
stock.birth_day_gh = convert_to_miladi(year, month, day)
stock.save()
except:
continue
archive_conditions = Q(
Q(type__in=['بز', 'گوسفند'], gender='نر') & Q(birth_day_gh__lte=today - timedelta(days=425)) |
Q(type__in=['بز', 'گوسفند'], gender='ماده') & Q(birth_day_gh__lte=today - timedelta(days=1825)) |
Q(type='گاو') & Q(birth_day_gh__lte=today - timedelta(days=3285)) |
Q(type='اسب') & Q(birth_day_gh__lte=today - timedelta(days=4380))
)
archived_count = LiveStock.objects.filter(
trash=False,
birth_day_gh__isnull=False
).filter(archive_conditions).update(
trash=True,
archive=True,
archiver=archive_msg
)
return HttpResponse('ok')

View File

View File

@@ -0,0 +1,608 @@
import datetime
import hashlib
import requests
from django.contrib.auth.models import User, Group
from django.db.models import Count
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from openpyxl import Workbook
from openpyxl.styles import Alignment
from rest_framework import status
import openpyxl
from io import BytesIO
from rest_framework.response import Response
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny
from LiveStock.Rancher.helpers import update_one_rancher
from LiveStock.helpers import convert_to_miladi
from LiveStock.models import Rancher, Cooperative, Union, Contractor, LiveStockRolseProduct, LiveStockProvinceJahad, \
LiveStock
from authentication.models import SystemUserProfile, Province, SystemAddress, City
from authentication.register import ARTA_REGISTER
from panel.admin import PROJECT_API_KEY
from panel.helper_excel import create_header, excel_description, create_header_freez, create_value
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_rancher_excel(request):
file = request.FILES['file'].read()
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
sheet = wb_obj.active
group = Group.objects.get(name__exact="Rancher")
system_user = SystemUserProfile.objects.filter(trash=False)
for i, row in enumerate(sheet.iter_rows(values_only=True)):
if i < 1:
continue
herd_code = row[0]
epidemiological_code = row[1]
postal_code = row[2]
unit_id = row[3]
herd_name = row[4]
national_id = row[5]
name = row[6]
mobile = row[7]
city = row[9]
lng = row[10]
lot = row[11]
registering_user = row[12]
mobile = str(mobile)
if len(mobile) < 10:
continue
if len(mobile) == 10:
mobile = '0' + mobile
full_name = name.split(':')
if not system_user.filter(mobile=mobile).exists():
if not User.objects.filter(username=mobile).exists():
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
data = {
"username": mobile,
"first_name": full_name[0],
"last_name": full_name[1],
"password": hashed_password,
"national_code": national_id,
"role": "Rancher",
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
province = Province.objects.filter(trash=False).first()
user = User(username=mobile, first_name=full_name[0], last_name=full_name[1],
password=hashed_password)
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
city_id = City.objects.filter(trash=False, id=city).first()
system_profile = SystemUserProfile(
mobile=mobile,
first_name=full_name[0],
last_name=full_name[1],
fullname=name,
user=user,
base_order=base_id,
password='1404',
birthday=datetime.datetime.now().date(),
city=city_id,
province=province
)
system_profile.save()
system_profile.role.add(group)
address = SystemAddress(
province=province,
city=city_id,
address=city,
postal_code=postal_code
)
address.save()
cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
if not Rancher.objects.filter(trash=False, herd_code=herd_code).exists():
rancher = Rancher(
user=system_profile,
address=address,
cooperative=cooperative,
name=name,
registering_user=registering_user,
lng=lng,
lot=lot,
mobile=mobile,
fullname=name,
city=city,
herd_name=herd_name,
unit_id=unit_id,
postal_code=postal_code,
epidemiological_code=epidemiological_code,
herd_code=herd_code,
national_id=national_id,
)
rancher.save()
return Response({"result": "ok"}, status=status.HTTP_200_OK)
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_union_excel(request):
file = request.FILES['file'].read()
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
sheet = wb_obj.active
group = Group.objects.get(name__exact="Union")
for i, row in enumerate(sheet.iter_rows(values_only=True)):
if i < 3:
continue
type = row[4]
address = row[5]
name = row[2]
mobile = row[6]
mobile = str(mobile)
if len(mobile) < 10:
continue
if len(mobile) == 10:
mobile = '0' + mobile
print(mobile)
full_name = name.split(' ')
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
data = {
"username": mobile,
"first_name": full_name[0],
"last_name": full_name[1],
"password": hashed_password,
"national_code": '0',
"role": "Union",
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
province = Province.objects.filter(trash=False).first()
user = User(username=mobile, first_name=full_name[0], last_name=full_name[1], password=hashed_password)
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
city_id = City.objects.filter(trash=False, name='همدان').first()
system_profile = SystemUserProfile(
mobile=mobile,
first_name=full_name[0],
last_name=full_name[1],
fullname=name,
user=user,
base_order=base_id,
password='1404',
birthday=datetime.datetime.now().date(),
city=city_id,
province=province
)
system_profile.save()
system_profile.role.add(group)
address = SystemAddress(
province=province,
city=city_id,
address=address,
)
address.save()
if not Union.objects.filter(trash=False, user__mobile=mobile).exists():
union = Union(
user=system_profile,
address=address,
name=name,
mobile=mobile,
type=type,
)
union.save()
# role_product=LiveStockRolseProduct(union=union)
# role_product.save()
return Response({"result": "ok"}, status=status.HTTP_200_OK)
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_cooperative_excel(request):
file = request.FILES['file'].read()
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
sheet = wb_obj.active
group = Group.objects.get(name__exact="Cooperative")
for i, row in enumerate(sheet.iter_rows(values_only=True)):
if i < 3:
continue
city = row[3]
address = row[5]
name = row[4]
mobile = row[6]
national_id = row[7]
mobile = str(mobile)
if len(mobile) < 10:
continue
if len(mobile) == 10:
mobile = '0' + mobile
print(mobile)
full_name = name.split(' ')
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
data = {
"username": mobile,
"first_name": full_name[0],
"last_name": full_name[1],
"password": hashed_password,
"national_code": national_id,
"role": "Cooperative",
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
province = Province.objects.filter(trash=False).first()
user = User(username=mobile, first_name=full_name[0], last_name=full_name[1:], password=hashed_password)
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
city_id = City.objects.filter(trash=False, name__contains=city).first()
system_profile = SystemUserProfile(
mobile=mobile,
first_name=full_name[0],
last_name=full_name[1],
fullname=name,
user=user,
base_order=base_id,
password='1404',
birthday=datetime.datetime.now().date(),
city=city_id,
province=province
)
system_profile.save()
system_profile.role.add(group)
address = SystemAddress(
province=province,
city=city_id,
address=address,
)
address.save()
if not Cooperative.objects.filter(trash=False, user__mobile=mobile).exists():
cooperative = Cooperative(
user=system_profile,
address=address,
name=name,
mobile=mobile,
national_id=national_id,
)
cooperative.save()
# role_product=LiveStockRolseProduct(union=union)
# role_product.save()
return Response({"result": "ok"}, status=status.HTTP_200_OK)
def hgsahgsad(request):
rancher = Cooperative.objects.all().order_by('id')
for r in rancher:
m=LiveStockRolseProduct(
cooperative=r
)
m.save()
return HttpResponse('ok')
import random
def generate_random_phone_number():
prefix = "0908"
used_numbers = set()
while True:
suffix = ''.join([str(random.randint(0, 9)) for _ in range(7)])
full_number = prefix + suffix
if not SystemUserProfile.objects.filter(mobile=full_number):
used_numbers.add(full_number)
return full_number
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_contractor_excel(request):
file = request.FILES['file'].read()
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
sheet = wb_obj.active
group = Group.objects.get(name__exact="Cooperative")
for i, row in enumerate(sheet.iter_rows(values_only=True)):
if i < 1:
continue
contractor_code = row[0]
first_name = row[1]
last_name = row[2]
full_name=first_name+ ' ' + last_name
entity_code=row[3]
city=row[4]
national_id=row[5]
postal_code=row[7]
company_name=row[8]
mobile = str(generate_random_phone_number())
if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
data = {
"username": mobile,
"first_name": first_name,
"last_name": last_name,
"password": hashed_password,
"national_code": national_id,
"role": "Contractor",
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
province = Province.objects.filter(trash=False).first()
user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
city_id = City.objects.filter(trash=False, id=city).first()
system_profile = SystemUserProfile(
mobile=mobile,
first_name=first_name,
last_name=last_name,
fullname=full_name,
user=user,
base_order=base_id,
password='1404',
birthday=datetime.datetime.now().date(),
city=city_id,
province=province
)
system_profile.save()
system_profile.role.add(group)
address = SystemAddress(
province=province,
city=city_id,
postal_code=postal_code,
)
address.save()
if not Contractor.objects.filter(trash=False, user__mobile=mobile).exists():
contractor = Contractor(
user=system_profile,
address=address,
contractor_code=contractor_code,
fullname=full_name,
entity_code=entity_code,
national_id=national_id,
company_name=company_name
)
contractor.save()
# role_product=LiveStockRolseProduct(union=union)
# role_product.save()
return Response({"result": "ok"}, status=status.HTTP_200_OK)
def kjdfjsd(request):
live=LiveStock.objects.filter(birth_day_gh__isnull=True).count()
return HttpResponse(live)
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_live_stock_excel(request):
file = request.FILES['file'].read()
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
sheet = wb_obj.active
existing_codes = set(LiveStock.objects.filter(trash=False).values_list('national_id_livestock_code', flat=True))
live_stocks_to_create = []
l = 0
for i, row in enumerate(sheet.iter_rows(values_only=True)):
if i < 1:
continue
national_id_livestock_code = row[0]
if national_id_livestock_code not in existing_codes:
birth_day = row[3].split('/')
birth_day_ghamari = convert_to_miladi(
year=int(birth_day[0]),
month=int(birth_day[1]),
day=int(birth_day[2])
)
live_stock = LiveStock(
national_id_livestock_code=row[0],
herd_code=row[1],
type=row[2],
birth_day=row[3],
birth_day_gh=birth_day_ghamari,
gender=row[4],
contractor_code=row[5],
unique_identifier=row[6],
agent=row[7],
registering_user=row[8],
registering_date=row[9],
)
live_stocks_to_create.append(live_stock)
l += 1
LiveStock.objects.bulk_create(live_stocks_to_create)
return Response({"result": l}, status=status.HTTP_200_OK)
@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_cooepritive_or_rural_excel(request):
file = request.FILES['file'].read()
wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
sheet = wb_obj.active
rancher=Rancher.objects.filter(trash=False).only('national_id','type')
l=0
for i, row in enumerate(sheet.iter_rows(values_only=True)):
national_id= row[0]
new_rancher=rancher.filter(national_id=national_id)
if new_rancher:
if len(new_rancher) >1:
for r in new_rancher:
r.type='industrial'
r.save()
else:
n=new_rancher.first()
n.type = 'industrial'
n.save()
l+=1
return Response({"result": l}, status=status.HTTP_200_OK)
def rancher_repetitive_excel(request):
duplicates = Rancher.objects.filter(trash=False).values('national_id').annotate(
count=Count('national_id')
).filter(count__gt=1)
# حالا رکوردهایی که national_id تکراری دارند را استخراج می‌کنیم
duplicate_records = Rancher.objects.filter(
national_id__in=[item['national_id'] for item in duplicates],
trash=False
)
excel_options = [
'ردیف',
'نام دامدار',
'شماره ملی',
'کد گله',
'تعداد دام سبک',
'تعداد دام سنگین',
]
output = BytesIO()
workbook = Workbook()
worksheet = workbook.active
worksheet.sheet_view.rightToLeft = True
worksheet.insert_rows(1)
cell = worksheet.cell(row=1, column=1)
cell.alignment = Alignment(horizontal='center', vertical='center')
excel_description(worksheet, 'B1', f'انبار', color='red', row2='C1')
create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)
l = 5
m = 1
if duplicate_records:
for data in duplicate_records:
while True:
update_ranchers = update_one_rancher(data)
if update_ranchers:
break
list1 = [
m,
data.fullname,
data.national_id,
data.herd_code,
data.light_livestock,
data.heavy_livestock,
]
m += 1
l += 1
create_value(worksheet, list1, l + 1, 1, border_style='thin')
workbook.save(output)
output.seek(0)
response = HttpResponse(
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response[
'Content-Disposition'] = f'attachment; filename="تکراری.xlsx"'.encode(
'utf-8')
response.write(output.getvalue())
return response
def create_live_stovk(request):
l=0
for _i in range(60):
live_stock=LiveStock(
national_id_livestock_code=random.randint(10**9, 10**10 - 1),
herd_code='000005307',
type='اسب',
birth_day='1402/12/27',
birth_day_gh=datetime.datetime.now() - datetime.timedelta(days=360),
gender='نر',
unique_identifier='0000053070',
)
live_stock.save()
l+=1
return HttpResponse(l)

View File

@@ -0,0 +1,25 @@
from django_filters import rest_framework as filters
from LiveStock.models import Rancher
class RancherFilterSet(filters.FilterSet):
class Meta:
model = Rancher
fields = [
'fullname',
'herd_code',
'mobile',
'city',
'national_id',
'herd_code',
'user__mobile',
'user__first_name',
'user__last_name',
'user__fullname',
'registering_user',
'unit_id',
'epidemiological_code',
'postal_code',
]

View File

@@ -0,0 +1,110 @@
from django.http import HttpResponse
from django.db.models import Count, Q
from LiveStock.models import Rancher, LiveStock, LiveStockProduct
def update_quota_rancher_threading():
rancher=Rancher.objects.filter(trash=False).only('trash').order_by('id')
for rancher in rancher:
rancher.save()
def get_live_stock_info(request):
rancher=Rancher.objects.filter(trash=False,has_script=False).only('cow','sheep','goat','horse','camel','light_livestock','heavy_livestock','has_script'
)
rachers=rancher.values_list('herd_code',flat=True).distinct()
live_stocks = LiveStock.objects.filter(trash=False,herd_code__in=rachers ).only('type')
for r in rancher:
live_stock=live_stocks.filter(herd_code=r.herd_code).only('type')
if live_stock:
sheep=live_stock.filter(type='گوسفند').count()
goat=live_stock.filter(type='بز').count()
cow=live_stock.filter(type='گاو').count()
horse=live_stock.filter(type='اسب').count()
camel=live_stock.filter(type='شتر').count()
light_livestock = live_stock.filter(type__in=('بز', 'گوسفند')).count()
heavy_livestock = live_stock.filter(type__in=('گاو','اسب','شتر')).count()
product = LiveStockProduct.objects.filter(trash=False, name='سبوس').first()
r.sheep=sheep
r.horse=horse
r.camel=camel
r.light_livestock=light_livestock
r.heavy_livestock=heavy_livestock
r.goat=goat
r.cow=cow
r.has_script=True
r.weight_quota_heavy = product.heavy_wight * heavy_livestock
r.weight_quota_light = product.light_wight * light_livestock
r.save()
return HttpResponse('ok')
def update_rancher(rancherss):
for ranchers in rancherss:
live_stocks = LiveStock.objects.filter(trash=False, herd_code=ranchers.herd_code).only('type')
sheep = live_stocks.filter(type='گوسفند').count()
goat = live_stocks.filter(type='بز').count()
cow = live_stocks.filter(type='گاو').count()
horse = live_stocks.filter(type='اسب').count()
camel = live_stocks.filter(type='شتر').count()
light_livestock = live_stocks.filter(type__in=('بز', 'گوسفند')).count()
heavy_livestock = live_stocks.filter(type__in=('گاو', 'اسب', 'شتر')).count()
product = LiveStockProduct.objects.filter(name='سبوس', trash=False).first()
ranchers.sheep = sheep
ranchers.horse = horse
ranchers.camel = camel
ranchers.light_livestock = light_livestock
ranchers.heavy_livestock = heavy_livestock
ranchers.goat = goat
ranchers.cow = cow
ranchers.weight_quota_heavy = product.heavy_wight * heavy_livestock
ranchers.weight_quota_light = product.light_wight * light_livestock
ranchers.save()
return True
def al_get_live_stock_info(request):
rancher = Rancher.objects.filter(trash=False, has_script=False).only('cow', 'sheep', 'goat', 'horse', 'camel',
'light_livestock', 'heavy_livestock',
'has_script'
).count()
return HttpResponse(rancher)
def update_one_rancher(ranchers):
counts = LiveStock.objects.filter(
trash=False,
herd_code=ranchers.herd_code
).aggregate(
sheep_count=Count('id', filter=Q(type='گوسفند')),
goat_count=Count('id', filter=Q(type='بز')),
cow_count=Count('id', filter=Q(type='گاو')),
horse_count=Count('id', filter=Q(type='اسب')),
camel_count=Count('id', filter=Q(type='شتر')),
light_count=Count('id', filter=Q(type__in=('بز', 'گوسفند'))),
heavy_count=Count('id', filter=Q(type__in=('گاو', 'اسب', 'شتر')))
)
product = LiveStockProduct.objects.filter(name='سبوس', trash=False).first()
ranchers.sheep = counts['sheep_count']
ranchers.goat = counts['goat_count']
ranchers.cow = counts['cow_count']
ranchers.horse = counts['horse_count']
ranchers.camel = counts['camel_count']
ranchers.light_livestock = counts['light_count']
ranchers.heavy_livestock = counts['heavy_count']
ranchers.weight_quota_heavy = product.heavy_wight * counts['heavy_count']
ranchers.weight_quota_light = product.light_wight * counts['light_count']
ranchers.has_script = True
ranchers.save()
return True

View File

@@ -0,0 +1,40 @@
from rest_framework import serializers
from LiveStock.models import Rancher, LiveStock, LiveStockProduct
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
from authentication.serializers import SystemAddressSerializer
class RancherSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
# address = SystemAddressSerializer(read_only=True)
class Meta:
model = Rancher
fields = '__all__'
class RancherForBazrasiSerializer(serializers.ModelSerializer):
heavy_livestock = serializers.SerializerMethodField()
light_livestock = serializers.SerializerMethodField()
class Meta:
model = Rancher
fields = [
'herd_code',
'fullname',
'mobile',
'lot',
'lng',
'heavy_livestock',
'light_livestock',
'type'
]
def get_heavy_livestock(self, obj):
heavy_counts = self.context.get('heavy_counts') or {}
return heavy_counts.get(obj.herd_code, 0)
def get_light_livestock(self, obj):
light_counts = self.context.get('light_counts') or {}
return light_counts.get(obj.herd_code, 0)

40
LiveStock/Rancher/urls.py Normal file
View File

@@ -0,0 +1,40 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from LiveStock.Rancher import views as rancher_views
from LiveStock.Rancher.excel_processing import get_rancher_excel, get_union_excel, get_cooperative_excel, hgsahgsad, \
get_contractor_excel, kjdfjsd, get_live_stock_excel, get_cooepritive_or_rural_excel, rancher_repetitive_excel, \
create_live_stovk
from LiveStock.Rancher.helpers import get_live_stock_info
from LiveStock.Rancher.views import get_detail_rancher, dashboard_rancher
router = DefaultRouter()
router.register(
r'rancher-view',
rancher_views.RancherViewSet,
basename="rancher-view"
)
router.register(
r'bazrasi-rancher-view',
rancher_views.RancherForBazrasiViewSet,
basename="bazrasi-rancher-view"
)
urlpatterns = [
path('', include(router.urls)),
path('get_rancher_excel/', get_rancher_excel),
path('get_union_excel/', get_union_excel),
path('get_cooperative_excel/', get_cooperative_excel),
path('hgsahgsad/', hgsahgsad),
path('get_contractor_excel/', get_contractor_excel),
path('get_live_stock_info/', get_live_stock_info),
path('get_detail_rancher/', get_detail_rancher),
path('dashboard_rancher/', dashboard_rancher),
path('kjdfjsd/', kjdfjsd),
path('get_live_stock_excel/', get_live_stock_excel),
path('get_cooepritive_or_rural_excel/', get_cooepritive_or_rural_excel),
path('rancher_repetitive_excel/', rancher_repetitive_excel),
path('create_live_stovk/', create_live_stovk),
]

352
LiveStock/Rancher/views.py Normal file
View File

@@ -0,0 +1,352 @@
from django.db.models import Sum, Count, Q
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from LiveStock.Rancher.filterset import RancherFilterSet
from LiveStock.Rancher.serializers import RancherSerializer, RancherForBazrasiSerializer
from LiveStock.helpers import CustomPagination, build_query
from LiveStock.models import Rancher, Cooperative, LiveStock
from authentication.models import SystemUserProfile, City, Province
from LiveStock.Rancher.helpers import update_rancher, update_one_rancher
from django.contrib.auth.models import User, Group
from authentication.views import ARTA_URL_REGISTER, ARTA_URL_CHANGE_MOBILE_NUMBER
from panel.admin import PROJECT_API_KEY
import requests
class RancherViewSet(viewsets.ModelViewSet):
queryset = Rancher.objects.filter(trash=False).only('herd_code', 'epidemiological_code', 'postal_code', 'unit_id',
'herd_name', 'national_id',
'fullname', 'mobile', 'contractor_code', 'city',
'registering_user', 'light_livestock', 'heavy_livestock', 'cow',
'goat', 'sheep', 'horse', 'camel', 'lot', 'lng',
'allow_buy').order_by('id')
permission_classes = [TokenHasReadWriteScope]
serializer_class = RancherSerializer
pagination_class = CustomPagination
filterset_class = RancherFilterSet
def retrieve(self, request, pk=None, *args, **kwargs):
if 'profile' in request.GET:
user = SystemUserProfile.objects.get(user=request.user, trash=False)
rancher = user.rancher_user.all()
serializer = self.serializer_class(rancher[0])
return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs):
user = SystemUserProfile.objects.get(user=request.user, trash=False)
if request.GET['role'] == 'Cooperative':
cooperative = Cooperative.objects.get(user=user, trash=False)
ranchers = Rancher.objects.filter(trash=False, city=cooperative.address.city.name).only('herd_code',
'epidemiological_code',
'postal_code',
'unit_id',
'herd_name',
'national_id',
'fullname',
'mobile',
'contractor_code',
'city',
'registering_user',
'light_livestock',
'heavy_livestock',
'cow',
'goat', 'sheep',
'horse', 'camel',
'lot', 'lng',
'allow_buy').order_by(
'id')
else:
ranchers = Rancher.objects.filter(trash=False).only('herd_code', 'epidemiological_code', 'postal_code',
'unit_id', 'herd_name', 'national_id',
'fullname', 'mobile', 'contractor_code', 'city',
'registering_user', 'light_livestock',
'heavy_livestock', 'cow',
'goat', 'sheep', 'horse', 'camel', 'lot', 'lng',
'allow_buy').order_by('id')
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
ranchers = ranchers.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page_size = request.query_params.get('page_size', None)
if page_size:
self.pagination_class.page_size = int(page_size)
page = self.paginate_queryset(ranchers)
if page is not None:
serializer = self.serializer_class(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(ranchers.first())
# serializer = self.serializer_class(ranchers, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def create(self, request, *args, **kwargs):
group = Group.objects.get(name__exact="Rancher")
city = City.objects.get(name=request.data['city'])
request.data.pop('city')
province = Province.objects.get(key=city.province.key)
system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
if system_profile:
if Rancher.objects.filter(user=system_profile, trash=False).exists():
return Response({"result": "این اتحادیه قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)
else:
password = "123456"
data = {
"username": request.data['mobile'],
"password": password,
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_URL_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
user = User(username=request.data['mobile'], first_name=request.data['first_name'],
last_name=request.data['last_name'])
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
system_profile = SystemUserProfile(
mobile=request.data['mobile'],
first_name=request.data['first_name'],
last_name=request.data['last_name'],
fullname=request.data['first_name'] + " " + request.data['last_name'],
user=user,
base_order=base_id,
password=password,
national_id=request.data['national_id'],
city=city,
province=province
)
system_profile.save()
else:
return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
system_profile.role.add(group)
request.data.pop('first_name')
request.data.pop('last_name')
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
rancher = serializer.create(validated_data=request.data)
rancher.user = system_profile
rancher.save()
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk=None, *args, **kwargs):
rancher = Rancher.objects.get(key=request.data['key'], trash=False)
if 'first_name' in request.data.keys():
# system_user_profile = SystemUserProfile.objects.get(key=rancher.user.key, trash=False)
# system_user_profile.first_name = request.data['first_name']
# system_user_profile.last_name = request.data['last_name']
# system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
# system_user_profile.save()
# first_mobile_number = system_user_profile.mobile
# second_mobile_number = request.data['mobile']
# if first_mobile_number != second_mobile_number:
# if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
# return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
# status=status.HTTP_403_FORBIDDEN)
# data = {
# "first_mobile_number": first_mobile_number,
# "second_mobile_number": second_mobile_number,
# }
# req = requests.post(
# url=ARTA_URL_CHANGE_MOBILE_NUMBER,
# data=data,
# verify=False
# )
# if req.status_code == 200:
# second_mobile_number = second_mobile_number
# user = User.objects.get(id=system_user_profile.user.id)
# user.username = second_mobile_number
# user.save()
# system_user_profile.mobile = second_mobile_number
# system_user_profile.save()
request.data.pop('first_name')
request.data.pop('last_name')
serializer = self.serializer_class(rancher)
serializer.update(instance=rancher, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_200_OK)
def destroy(self, request, pk=None, *args, **kwargs):
rancher = Rancher.objects.get(key=request.GET["rancher_key"])
rancher.trash = True
rancher.save()
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
# def update(self, request, *args, **kwargs):
# rancher = self.queryset.get(key=request.data['key'], trash=False)
# request.data.pop('key')
#
# serializer = self.serializer_class(rancher)
# serializer.update(instance=rancher, validated_data=request.data)
# return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def get_detail_rancher(request):
ranchers = Rancher.objects.filter(herd_code=request.GET['herd_code']).first()
while True:
update_ranchers = update_one_rancher(ranchers)
if update_ranchers:
break
dict1 = {
"light_livestock": ranchers.light_livestock,
"heavy_livestock": ranchers.heavy_livestock,
"sheep": ranchers.sheep,
"goat": ranchers.goat,
"cow": ranchers.cow,
"camel": ranchers.camel,
"horse": ranchers.horse
}
return Response(dict1, status=status.HTTP_200_OK)
class RancherForBazrasiViewSet(viewsets.ModelViewSet):
queryset = Rancher.objects.filter(trash=False, type='industrial').only(
'herd_code',
'fullname',
'mobile',
'lot',
'lng',
'industrial',
'heavy_livestock',
'light_livestock'
).order_by('-industrial', 'id')
permission_classes = [AllowAny]
serializer_class = RancherForBazrasiSerializer
def list(self, request, *args, **kwargs):
type_filter = request.GET.get('type')
queryset = Rancher.objects.filter(trash=False).only(
'herd_code',
'fullname',
'mobile',
'lot',
'lng',
'industrial',
'heavy_livestock',
'light_livestock',
'type'
).order_by('-industrial', 'id')
if type_filter in ('industrial', 'rural'):
queryset = queryset.filter(type=type_filter)
herd_codes = list(queryset.values_list('herd_code', flat=True))
heavy_counts = {}
light_counts = {}
valid_herd_codes = set()
if herd_codes:
heavy_types = ('گاو', 'اسب', 'شتر')
light_types = ('بز', 'گوسفند')
livestock_counts = (
LiveStock.objects.filter(
trash=False,
herd_code__in=herd_codes,
type__in=heavy_types + light_types
)
.values('herd_code', 'type')
.annotate(total=Count('id'))
)
for item in livestock_counts:
herd_code = item['herd_code']
livestock_type = item['type']
total = item['total']
if livestock_type in heavy_types:
heavy_counts[herd_code] = heavy_counts.get(herd_code, 0) + total
elif livestock_type in light_types:
light_counts[herd_code] = light_counts.get(herd_code, 0) + total
valid_herd_codes = set(heavy_counts.keys()) | set(light_counts.keys())
if valid_herd_codes:
queryset = queryset.filter(herd_code__in=valid_herd_codes)
else:
queryset = queryset.none()
serializer = self.get_serializer(
queryset,
many=True,
context={
'heavy_counts': heavy_counts,
'light_counts': light_counts
}
)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(["GET"])
@csrf_exempt
@permission_classes([TokenHasReadWriteScope])
def dashboard_rancher(request):
user = SystemUserProfile.objects.get(user=request.user, trash=False)
role = request.GET.get('role')
ranchers = Rancher.objects.filter(trash=False).values_list('herd_code', flat=True).distinct()
live_stocks = LiveStock.objects.filter(trash=False, herd_code__in=ranchers).only('type')
if role == 'Cooperative':
cooperative = Cooperative.objects.get(user=user, trash=False)
ranchers = Rancher.objects.filter(trash=False, city=cooperative.address.city.name).values_list('herd_code',
flat=True).distinct()
live_stocks = live_stocks.filter(herd_code__in=ranchers)
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
ranchers = ranchers.filter(build_query(RancherFilterSet.Meta.fields, value))
counts = live_stocks.values('type').annotate(total=Count('id'))
count_dict = {item['type']: item['total'] for item in counts}
light_livestock = count_dict.get('بز', 0) + count_dict.get('گوسفند', 0)
heavy_livestock = count_dict.get('گاو', 0) + count_dict.get('اسب', 0) + count_dict.get('شتر', 0)
total_ranchers = len(ranchers)
dhi_amount = ranchers.filter(dhi_amount__gt=1,trash=False).aggregate(total=Sum('dhi_amount'))['total'] or 0
result = {
'rancher_count': total_ranchers,
'live_stocks_count': sum(count_dict.values()),
"sheep": count_dict.get('گوسفند', 0),
"goat": count_dict.get('بز', 0),
"cow": count_dict.get('گاو', 0),
"horse": count_dict.get('اسب', 0),
"camel": count_dict.get('شتر', 0),
"light_livestock": light_livestock,
"heavy_livestock": heavy_livestock,
"dhi_amount": dhi_amount,
}
return Response(result, status=status.HTTP_200_OK)

View File

View File

View File

@@ -0,0 +1,17 @@
from django_filters import rest_framework as filters
from LiveStock.models import Union
class UnionFilterSet(filters.FilterSet):
class Meta:
model = Union
fields = [
'address__city__name',
'name',
'mobile',
'user__mobile',
'user__first_name',
'user__last_name',
'user__fullname'
]

View File

View File

@@ -0,0 +1,15 @@
from rest_framework import serializers
from LiveStock.models import Union
from authentication.serializer.serializer import BankCardSerializer, SystemUserProfileForInspectionSerializer
from authentication.serializers import SystemAddressSerializer
class UnionSerializer(serializers.ModelSerializer):
user = SystemUserProfileForInspectionSerializer(read_only=True)
address = SystemAddressSerializer(read_only=True)
user_bank_info = BankCardSerializer(required=False)
class Meta:
model = Union
fields = '__all__'

14
LiveStock/Union/urls.py Normal file
View File

@@ -0,0 +1,14 @@
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from LiveStock.Union import views as union_views
router = DefaultRouter()
router.register(
r'union-view',
union_views.UnionViewSet,
basename="union"
)
urlpatterns = [
path('', include(router.urls)),
]

181
LiveStock/Union/views.py Normal file
View File

@@ -0,0 +1,181 @@
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from LiveStock.Union.filterset import UnionFilterSet
from LiveStock.Union.serializers import UnionSerializer
from LiveStock.helpers import build_query, CustomPagination
from LiveStock.models import Union
from authentication.models import SystemUserProfile, City, Province, SystemAddress
from django.contrib.auth.models import User, Group
from authentication.views import ARTA_URL_REGISTER, ARTA_URL_CHANGE_MOBILE_NUMBER
from panel.admin import PROJECT_API_KEY
import requests
class UnionViewSet(viewsets.ModelViewSet):
queryset = Union.objects.all()
permission_classes = [TokenHasReadWriteScope]
serializer_class = UnionSerializer
filterset_class = UnionFilterSet
pagination_class = CustomPagination
def retrieve(self, request, pk=None, *args, **kwargs):
if 'profile' in request.GET:
user = SystemUserProfile.objects.get(user=request.user, trash=False)
union = user.union_user.all()
serializer = self.serializer_class(union[0])
return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs):
unions = Union.objects.filter(trash=False).order_by('id')
value = request.GET.get('value')
search = request.GET.get('search')
if value and search == 'filter':
if search != 'undefined' and search.strip():
unions = unions.filter(
build_query(self.filterset_class.Meta.fields, value)
)
page = self.paginate_queryset(unions)
if page is not None:
serializer = self.serializer_class(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.serializer_class(unions, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def create(self, request, *args, **kwargs):
group = Group.objects.get(name__exact="Union")
city = City.objects.get(name=request.data['city'])
request.data.pop('city')
province = Province.objects.get(key=city.province.key)
system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
if system_profile:
if Union.objects.filter(user=system_profile, trash=False).exists():
return Response({"result": "این اتحادیه قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)
else:
password = "123456"
data = {
"username": request.data['mobile'],
"password": password,
"api_key": PROJECT_API_KEY
}
req = requests.post(
url=ARTA_URL_REGISTER,
data=data,
verify=False
)
if req.status_code == 200:
user = User(username=request.data['mobile'], first_name=request.data['first_name'],
last_name=request.data['last_name'])
user.save()
base_id = SystemUserProfile.objects.all()
if base_id.count() > 0:
base_id = int(base_id.last().base_order) + 1
else:
base_id = 1000
system_profile = SystemUserProfile(
mobile=request.data['mobile'],
first_name=request.data['first_name'],
last_name=request.data['last_name'],
fullname=request.data['first_name'] + " " + request.data['last_name'],
user=user,
base_order=base_id,
password=password,
national_id=request.data['national_id'],
city=city,
province=province
)
system_profile.save()
else:
return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
address = SystemAddress(city=city, province=province, address=request.data['address'],
postal_code=request.data['postal_code'])
address.save()
system_profile.role.add(group)
request.data.pop('first_name')
request.data.pop('last_name')
request.data.pop('address')
request.data.pop('postal_code')
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
union = serializer.create(validated_data=request.data)
union.user = system_profile
union.address = address
union.save()
return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk=None, *args, **kwargs):
union = Union.objects.get(key=request.data['union_key'], trash=False)
address = SystemAddress.objects.get(key=union.address.key, trash=False)
request.data.pop('union_key')
if 'first_name' in request.data.keys():
system_user_profile = SystemUserProfile.objects.get(key=union.user.key, trash=False)
system_user_profile.first_name = request.data['first_name']
system_user_profile.last_name = request.data['last_name']
system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
system_user_profile.save()
first_mobile_number = system_user_profile.mobile
second_mobile_number = request.data['mobile']
if first_mobile_number != second_mobile_number:
if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
status=status.HTTP_403_FORBIDDEN)
data = {
"first_mobile_number": first_mobile_number,
"second_mobile_number": second_mobile_number,
}
req = requests.post(
url=ARTA_URL_CHANGE_MOBILE_NUMBER,
data=data,
verify=False
)
if req.status_code == 200:
second_mobile_number = second_mobile_number
user = User.objects.get(id=system_user_profile.user.id)
user.username = second_mobile_number
user.save()
system_user_profile.mobile = second_mobile_number
system_user_profile.save()
city = City.objects.get(name=request.data['city'])
province = Province.objects.get(key=city.province.key)
address.city = city
address.province = province
address.address = request.data['address']
address.postal_code = request.data['postal_code']
address.save()
request.data.pop('first_name')
request.data.pop('last_name')
request.data.pop('address')
request.data.pop('city')
serializer = self.serializer_class(union)
serializer.update(instance=union, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_200_OK)
# def update(self, request, *args, **kwargs):
# union = Union.objects.get(key=request.data['key'], trash=False)
# request.data.pop('key')
# if 'city' in request.data:
# city_key=request.data['city']
# request.data.pop('city')
# city=City.objects.filter(key=city_key,trash=False).first()
# union.address.city=city
# union.address.save()
# serializer = self.serializer_class(union)
#
# serializer.update(instance=union, validated_data=request.data)
# return Response(serializer.data, status=status.HTTP_200_OK)
def destroy(self, request, pk=None, *args, **kwargs):
union = Union.objects.get(key=request.GET["key"])
union.trash = True
union.save()
return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)

0
LiveStock/__init__.py Normal file
View File

3
LiveStock/admin.py Normal file
View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
LiveStock/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class LivestockConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'LiveStock'

19
LiveStock/helpers.py Normal file
View File

@@ -0,0 +1,19 @@
import jdatetime
from rest_framework.pagination import PageNumberPagination
class CustomPagination(PageNumberPagination):
page_size = 10
def convert_to_miladi(year=None, month=None, day=None):
date = jdatetime.datetime(year, month, day).togregorian()
return date
def build_query(fields, value):
from django.db.models import Q
query = Q()
for field in fields:
query |= Q(**{f"{field}__icontains": value})
return query

View File

@@ -0,0 +1,187 @@
# Generated by Django 3.2.13 on 2025-03-03 20:36
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('authentication', '0050_auto_20250303_2036'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Cooperative',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('name', models.CharField(max_length=200, null=True)),
('mobile', models.CharField(max_length=200, null=True)),
('type', models.CharField(max_length=200, null=True)),
('account', models.CharField(max_length=200, null=True)),
('national_id', models.CharField(max_length=100, null=True)),
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_address', to='authentication.systemaddress')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_modifiedby', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_user', to='authentication.systemuserprofile')),
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_bank_info', to='authentication.bankcard')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='LiveStockProduct',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('name', models.CharField(max_length=200, null=True)),
('image', models.CharField(max_length=500, null=True)),
('unit', models.CharField(max_length=200, null=True)),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockproduct_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockproduct_modifiedby', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='LiveStockProvinceJahad',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('name', models.CharField(max_length=200, null=True)),
('mobile', models.CharField(max_length=200, null=True)),
('type', models.CharField(max_length=200, null=True)),
('account', models.CharField(max_length=200, null=True)),
('national_id', models.CharField(max_length=100, null=True)),
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='live_stock_jahad_address', to='authentication.systemaddress')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockprovincejahad_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockprovincejahad_modifiedby', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='live_stock_jahad_user', to='authentication.systemuserprofile')),
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='live_stock_jahad_bank_info', to='authentication.bankcard')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Union',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('name', models.CharField(max_length=200, null=True)),
('mobile', models.CharField(max_length=200, null=True)),
('type', models.CharField(max_length=200, null=True)),
('account', models.CharField(max_length=200, null=True)),
('national_id', models.CharField(max_length=100, null=True)),
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_address', to='authentication.systemaddress')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_modifiedby', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_user', to='authentication.systemuserprofile')),
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_bank_info', to='authentication.bankcard')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Rancher',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('name', models.CharField(max_length=200, null=True)),
('registering_user', models.CharField(max_length=200, null=True)),
('lng', models.FloatField(default=0)),
('lot', models.FloatField(default=0)),
('mobile', models.CharField(max_length=200, null=True)),
('fullname', models.CharField(max_length=200, null=True)),
('city', models.CharField(max_length=200, null=True)),
('herd_name', models.CharField(max_length=200, null=True)),
('unit_id', models.CharField(max_length=100, null=True)),
('postal_code', models.CharField(max_length=100, null=True)),
('epidemiological_code', models.CharField(max_length=100, null=True)),
('herd_code', models.CharField(max_length=100, null=True)),
('national_id', models.CharField(max_length=100, null=True)),
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_address', to='authentication.systemaddress')),
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_cooperative', to='LiveStock.cooperative')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_modifiedby', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_user', to='authentication.systemuserprofile')),
('user_bank_info', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_bank_info', to='authentication.bankcard')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='LiveStockRolseProduct',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('name', models.CharField(max_length=200, null=True)),
('total_weight', models.BigIntegerField(default=0)),
('total_allocated_weight', models.BigIntegerField(default=0)),
('total_remain_weight', models.CharField(max_length=500, null=True)),
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_product', to='LiveStock.cooperative')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockrolseproduct_createdby', to=settings.AUTH_USER_MODEL)),
('jahad', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='jahad_product', to='LiveStock.livestockprovincejahad')),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockrolseproduct_modifiedby', to=settings.AUTH_USER_MODEL)),
('parent_product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='parents_product', to='LiveStock.livestockproduct')),
('union', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_product', to='LiveStock.union')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='LiveStockAllocations',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('state', models.CharField(default='pending', max_length=200)),
('weight', models.BigIntegerField(default=0)),
('real_weight', models.BigIntegerField(default=0)),
('date', models.DateTimeField(default=datetime.datetime.now)),
('allocate_from', models.CharField(max_length=200, null=True)),
('allocate_to', models.CharField(max_length=200, null=True)),
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_allocation', to='LiveStock.cooperative')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockallocations_createdby', to=settings.AUTH_USER_MODEL)),
('jahad', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='jahad_allocation', to='LiveStock.livestockprovincejahad')),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestockallocations_modifiedby', to=settings.AUTH_USER_MODEL)),
('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='product_allocation', to='LiveStock.livestockrolseproduct')),
('union', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='union_allocation', to='LiveStock.union')),
],
options={
'abstract': False,
},
),
]

View File

@@ -0,0 +1,43 @@
# Generated by Django 3.2.13 on 2025-03-04 13:40
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('LiveStock', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='LiveStock',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('national_id_livestock_code', models.CharField(max_length=200, null=True)),
('herd_code', models.CharField(max_length=100, null=True)),
('type', models.CharField(max_length=200, null=True)),
('birth_day', models.DateField(null=True)),
('gender', models.CharField(max_length=100, null=True)),
('contractor_code', models.CharField(max_length=100, null=True)),
('unique_identifier', models.CharField(max_length=100, null=True)),
('agent', models.CharField(max_length=100, null=True)),
('registering_user', models.CharField(max_length=200, null=True)),
('registering_date', models.DateTimeField(null=True)),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestock_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='livestock_modifiedby', to=settings.AUTH_USER_MODEL)),
('rancher', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='LiveStock.rancher')),
],
options={
'abstract': False,
},
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-03-05 13:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0002_livestock'),
]
operations = [
migrations.AlterField(
model_name='livestock',
name='birth_day',
field=models.CharField(max_length=200, null=True),
),
migrations.AlterField(
model_name='livestock',
name='registering_date',
field=models.CharField(max_length=200, null=True),
),
]

View File

@@ -0,0 +1,28 @@
# Generated by Django 3.2.13 on 2025-03-05 17:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0003_auto_20250305_1353'),
]
operations = [
migrations.AddField(
model_name='rancher',
name='allow_buy',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='rancher',
name='weight_allocation_heavy',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='weight_allocation_light',
field=models.IntegerField(default=0),
),
]

View File

@@ -0,0 +1,38 @@
# Generated by Django 3.2.13 on 2025-03-05 20:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0004_auto_20250305_1721'),
]
operations = [
migrations.AddField(
model_name='livestockproduct',
name='cooperative_percent',
field=models.CharField(max_length=200, null=True),
),
migrations.AddField(
model_name='livestockproduct',
name='price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='union_percent',
field=models.CharField(max_length=200, null=True),
),
migrations.AddField(
model_name='rancher',
name='weight_quota_heavy',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='weight_quota_light',
field=models.IntegerField(default=0),
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-03-06 00:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0005_auto_20250305_2028'),
]
operations = [
migrations.AddField(
model_name='rancher',
name='total_weight',
field=models.BigIntegerField(default=0),
),
migrations.AlterField(
model_name='livestockrolseproduct',
name='total_remain_weight',
field=models.BigIntegerField(default=0),
),
]

View File

@@ -0,0 +1,45 @@
# Generated by Django 3.2.13 on 2025-03-06 12:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('authentication', '0051_auto_20250306_1213'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('LiveStock', '0006_auto_20250306_0023'),
]
operations = [
migrations.AddField(
model_name='rancher',
name='contractor_code',
field=models.CharField(max_length=100, null=True),
),
migrations.CreateModel(
name='Contractor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('contractor_code', models.CharField(max_length=100, null=True)),
('fullname', models.CharField(max_length=200, null=True)),
('entity_code', models.CharField(max_length=200, null=True)),
('national_id', models.CharField(max_length=100, null=True)),
('company_name', models.CharField(max_length=200, null=True)),
('address', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_user', to='authentication.systemaddress')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_modifiedby', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_user', to='authentication.systemuserprofile')),
],
options={
'abstract': False,
},
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-03-07 09:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0007_auto_20250306_1213'),
]
operations = [
migrations.AddField(
model_name='livestockproduct',
name='heavy_wight',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='light_wight',
field=models.IntegerField(default=0),
),
]

View File

@@ -0,0 +1,25 @@
# Generated by Django 3.2.13 on 2025-03-07 10:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0008_auto_20250307_0930'),
]
operations = [
migrations.RemoveField(
model_name='rancher',
name='address',
),
migrations.RemoveField(
model_name='rancher',
name='cooperative',
),
migrations.RemoveField(
model_name='rancher',
name='user_bank_info',
),
]

View File

@@ -0,0 +1,48 @@
# Generated by Django 3.2.13 on 2025-03-07 11:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0009_auto_20250307_1059'),
]
operations = [
migrations.AddField(
model_name='rancher',
name='camel',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='cow',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='goat',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='heavy_livestock',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='horse',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='light_livestock',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='sheep',
field=models.IntegerField(default=0),
),
]

View File

@@ -0,0 +1,39 @@
# Generated by Django 3.2.13 on 2025-03-07 13:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0010_auto_20250307_1107'),
]
operations = [
migrations.AddField(
model_name='contractor',
name='cooperative',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contractor_cooperative', to='LiveStock.cooperative'),
),
migrations.AddField(
model_name='contractor',
name='heavy_livestock',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='contractor',
name='light_livestock',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='contractor',
name='number_of_rancher',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='has_script',
field=models.BooleanField(default=False),
),
]

View File

@@ -0,0 +1,47 @@
# Generated by Django 3.2.13 on 2025-03-07 21:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0011_auto_20250307_1322'),
]
operations = [
migrations.RemoveField(
model_name='livestockproduct',
name='cooperative_percent',
),
migrations.RemoveField(
model_name='livestockproduct',
name='union_percent',
),
migrations.AddField(
model_name='livestockproduct',
name='company_price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='cooperative_price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='shipping_price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='union_price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='cooperative',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rancher_cooperative', to='LiveStock.cooperative'),
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-03-08 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0012_auto_20250307_2135'),
]
operations = [
migrations.AddField(
model_name='livestockallocations',
name='description',
field=models.TextField(null=True),
),
migrations.AddField(
model_name='livestockallocations',
name='place',
field=models.TextField(null=True),
),
]

View File

@@ -0,0 +1,33 @@
# Generated by Django 3.2.13 on 2025-03-09 16:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0013_auto_20250308_1617'),
]
operations = [
migrations.AddField(
model_name='cooperative',
name='active',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='livestockallocations',
name='charge',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='livestockallocations',
name='code',
field=models.CharField(max_length=200, null=True),
),
migrations.AddField(
model_name='livestockrolseproduct',
name='total_receipt_weight',
field=models.BigIntegerField(default=0),
),
]

View File

@@ -0,0 +1,58 @@
# Generated by Django 3.2.13 on 2025-03-10 18:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('LiveStock', '0014_auto_20250309_1654'),
]
operations = [
migrations.AddField(
model_name='livestock',
name='active',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='rancher',
name='active',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='union',
name='active',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='livestockallocations',
name='description',
field=models.TextField(blank=True, null=True),
),
migrations.CreateModel(
name='CooperativeProductsShare',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('price', models.IntegerField(default=0)),
('shipping_price', models.IntegerField(default=0)),
('union_price', models.IntegerField(default=0)),
('cooperative_price', models.IntegerField(default=0)),
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_share_product', to='LiveStock.cooperative')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperativeproductsshare_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperativeproductsshare_modifiedby', to=settings.AUTH_USER_MODEL)),
('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='cooperative_share_product', to='LiveStock.livestockproduct')),
],
options={
'abstract': False,
},
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-03-11 10:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0015_auto_20250310_1820'),
]
operations = [
migrations.AddField(
model_name='livestock',
name='birth_day_gh',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='livestock',
name='registering_date_gh',
field=models.DateTimeField(null=True),
),
]

View File

@@ -0,0 +1,37 @@
# Generated by Django 3.2.13 on 2025-03-11 13:36
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('LiveStock', '0016_auto_20250311_1055'),
]
operations = [
migrations.CreateModel(
name='PosSeller',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
('trash', models.BooleanField(default=False)),
('full_name', models.CharField(max_length=200, null=True)),
('mobile', models.CharField(max_length=50, null=True)),
('national_id', models.CharField(max_length=50, null=True)),
('city', models.CharField(max_length=100, null=True)),
('cooperative', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='seller_pos_cooperative', to='LiveStock.cooperative')),
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posseller_createdby', to=settings.AUTH_USER_MODEL)),
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posseller_modifiedby', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 3.2.13 on 2025-03-12 11:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0017_posseller'),
]
operations = [
migrations.AddField(
model_name='rancher',
name='type',
field=models.CharField(default='rural', max_length=200),
),
]

View File

@@ -0,0 +1,33 @@
# Generated by Django 3.2.13 on 2025-03-12 14:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0018_rancher_type'),
]
operations = [
migrations.AddField(
model_name='livestockproduct',
name='heavy_wight_dha',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='heavy_wight_industrial',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='light_wight_dha',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestockproduct',
name='light_wight_industrial',
field=models.IntegerField(default=0),
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-03-12 14:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0019_auto_20250312_1429'),
]
operations = [
migrations.AddField(
model_name='rancher',
name='dhi_amount',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='rancher',
name='industrial',
field=models.BooleanField(default=False),
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 3.2.13 on 2025-04-12 16:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0020_auto_20250312_1459'),
]
operations = [
migrations.AddField(
model_name='livestock',
name='archive',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='livestock',
name='archiver',
field=models.CharField(max_length=250, null=True),
),
]

View File

@@ -0,0 +1,38 @@
# Generated by Django 3.2.13 on 2025-05-28 14:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0021_auto_20250412_1613'),
]
operations = [
migrations.AddField(
model_name='cooperativeproductsshare',
name='company_price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='livestock',
name='age_of_archive',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='livestock',
name='archive_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='livestock',
name='return_from_archive_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='livestock',
name='returner_from_archive',
field=models.CharField(max_length=250, null=True),
),
]

View File

@@ -0,0 +1,33 @@
# Generated by Django 3.2.13 on 2025-08-10 11:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LiveStock', '0022_auto_20250528_1439'),
]
operations = [
migrations.AddField(
model_name='cooperative',
name='first_sub_cooperative_account',
field=models.CharField(max_length=200, null=True),
),
migrations.AddField(
model_name='cooperative',
name='first_sub_cooperative_price',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='cooperative',
name='second_sub_cooperative_account',
field=models.CharField(max_length=200, null=True),
),
migrations.AddField(
model_name='cooperative',
name='second_sub_cooperative_price',
field=models.IntegerField(default=0),
),
]

View File

372
LiveStock/models.py Normal file
View File

@@ -0,0 +1,372 @@
import datetime
from authentication.models import BaseModel, SystemUserProfile, SystemAddress, BankCard
from django.db import models
class LiveStockProvinceJahad(BaseModel):
user = models.ForeignKey(
SystemUserProfile,
on_delete=models.CASCADE,
related_name="live_stock_jahad_user",
null=True
)
address = models.ForeignKey(
SystemAddress,
on_delete=models.CASCADE,
related_name="live_stock_jahad_address",
null=True
)
user_bank_info = models.ForeignKey(
BankCard,
on_delete=models.CASCADE,
related_name="live_stock_jahad_bank_info",
null=True
)
name = models.CharField(max_length=200, null=True)
mobile = models.CharField(max_length=200, null=True)
type = models.CharField(max_length=200, null=True)
account = models.CharField(max_length=200, null=True)
national_id = models.CharField(max_length=100, null=True)
def save(self, *args, **kwargs):
super(LiveStockProvinceJahad, self).save(*args, **kwargs)
class Union(BaseModel):
user = models.ForeignKey(
SystemUserProfile,
on_delete=models.CASCADE,
related_name="union_user",
null=True
)
address = models.ForeignKey(
SystemAddress,
on_delete=models.CASCADE,
related_name="union_address",
null=True
)
user_bank_info = models.ForeignKey(
BankCard,
on_delete=models.CASCADE,
related_name="union_bank_info",
null=True
)
name = models.CharField(max_length=200, null=True)
mobile = models.CharField(max_length=200, null=True)
type = models.CharField(max_length=200, null=True)
account = models.CharField(max_length=200, null=True)
national_id = models.CharField(max_length=100, null=True)
active = models.BooleanField(default=True)
def save(self, *args, **kwargs):
super(Union, self).save(*args, **kwargs)
class Cooperative(BaseModel):
user = models.ForeignKey(
SystemUserProfile,
on_delete=models.CASCADE,
related_name="cooperative_user",
null=True
)
address = models.ForeignKey(
SystemAddress,
on_delete=models.CASCADE,
related_name="cooperative_address",
null=True
)
user_bank_info = models.ForeignKey(
BankCard,
on_delete=models.CASCADE,
related_name="cooperative_bank_info",
null=True
)
name = models.CharField(max_length=200, null=True)
mobile = models.CharField(max_length=200, null=True)
type = models.CharField(max_length=200, null=True)
account = models.CharField(max_length=200, null=True)
national_id = models.CharField(max_length=100, null=True)
active = models.BooleanField(default=True)
first_sub_cooperative_price = models.IntegerField(default=0)
first_sub_cooperative_account = models.CharField(max_length=200, null=True)
second_sub_cooperative_price = models.IntegerField(default=0)
second_sub_cooperative_account = models.CharField(max_length=200, null=True)
def save(self, *args, **kwargs):
super(Cooperative, self).save(*args, **kwargs)
class Rancher(BaseModel):
user = models.ForeignKey(
SystemUserProfile,
on_delete=models.CASCADE,
related_name="rancher_user",
null=True
)
# address = models.ForeignKey(
# SystemAddress,
# on_delete=models.CASCADE,
# related_name="rancher_address",
# null=True
# )
# user_bank_info = models.ForeignKey(
# BankCard,
# on_delete=models.CASCADE,
# related_name="rancher_bank_info",
# null=True
# )
# contractor = models.ForeignKey(
# Contractor,
# on_delete=models.CASCADE,
# related_name="rancher_contractor",
# null=True
# )
cooperative = models.ForeignKey(
Cooperative,
on_delete=models.CASCADE,
related_name="rancher_cooperative",
null=True
)
name = models.CharField(max_length=200, null=True)
registering_user = models.CharField(max_length=200, null=True)
lng = models.FloatField(default=0)
lot = models.FloatField(default=0)
mobile = models.CharField(max_length=200, null=True)
fullname = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
herd_name = models.CharField(max_length=200, null=True)
unit_id = models.CharField(max_length=100, null=True)
postal_code = models.CharField(max_length=100, null=True)
epidemiological_code = models.CharField(max_length=100, null=True)
herd_code = models.CharField(max_length=100, null=True)
national_id = models.CharField(max_length=100, null=True)
allow_buy = models.BooleanField(default=True)
weight_allocation_light = models.IntegerField(default=0)
weight_allocation_heavy = models.IntegerField(default=0)
weight_quota_heavy = models.IntegerField(default=0)
weight_quota_light = models.IntegerField(default=0)
total_weight = models.BigIntegerField(default=0)
contractor_code = models.CharField(max_length=100, null=True)
sheep = models.IntegerField(default=0)
goat = models.IntegerField(default=0)
cow = models.IntegerField(default=0)
horse = models.IntegerField(default=0)
camel = models.IntegerField(default=0)
light_livestock = models.IntegerField(default=0)
heavy_livestock = models.IntegerField(default=0)
has_script = models.BooleanField(default=False)
active = models.BooleanField(default=True)
type = models.CharField(max_length=200, default='rural')
industrial = models.BooleanField(default=False)
dhi_amount = models.IntegerField(default=0)
def save(self, *args, **kwargs):
# live_stocks = LiveStock.objects.filter(trash=False, herd_code=self.herd_code).only('type')
# light_livestock = live_stocks.filter(type__in=('بز', 'گوسفند')).count()
# heavy_livestock = live_stocks.filter(type__in=('گاو', 'اسب', 'شتر')).count()
# product = LiveStockProduct.objects.filter(trash=False, name='سبوس').first()
# self.weight_quota_heavy=product.heavy_wight * heavy_livestock
# self.weight_quota_light=product.light_wight * light_livestock
super(Rancher, self).save(*args, **kwargs)
class LiveStock(BaseModel):
rancher = models.ForeignKey(Rancher, on_delete=models.CASCADE, null=True)
national_id_livestock_code = models.CharField(max_length=200, null=True)
herd_code = models.CharField(max_length=100, null=True)
type = models.CharField(max_length=200, null=True)
birth_day = models.CharField(max_length=200, null=True)
gender = models.CharField(max_length=100, null=True)
contractor_code = models.CharField(max_length=100, null=True)
unique_identifier = models.CharField(max_length=100, null=True)
agent = models.CharField(max_length=100, null=True)
registering_user = models.CharField(max_length=200, null=True)
registering_date = models.CharField(max_length=200, null=True)
active = models.BooleanField(default=True)
birth_day_gh = models.DateTimeField(null=True)
registering_date_gh = models.DateTimeField(null=True)
archive=models.BooleanField(default=False)
age_of_archive=models.IntegerField(default=1)
archiver=models.CharField(max_length=250,null=True)
archive_date=models.DateTimeField(null=True)
returner_from_archive=models.CharField(max_length=250,null=True)
return_from_archive_date=models.DateTimeField(null=True)
def save(self, *args, **kwargs):
super(LiveStock, self).save(*args, **kwargs)
class LiveStockProduct(BaseModel):
name = models.CharField(max_length=200, null=True)
image = models.CharField(max_length=500, null=True)
unit = models.CharField(max_length=200, null=True)
price = models.IntegerField(default=0)
light_wight = models.IntegerField(default=0)
heavy_wight = models.IntegerField(default=0)
company_price = models.IntegerField(default=0)
shipping_price = models.IntegerField(default=0)
union_price = models.IntegerField(default=0)
cooperative_price = models.IntegerField(default=0)
light_wight_industrial = models.IntegerField(default=0)
heavy_wight_industrial = models.IntegerField(default=0)
light_wight_dha = models.IntegerField(default=0)
heavy_wight_dha = models.IntegerField(default=0)
def save(self, *args, **kwargs):
super(LiveStockProduct, self).save(*args, **kwargs)
class CooperativeProductsShare(BaseModel):
cooperative = models.ForeignKey(
Cooperative,
on_delete=models.CASCADE,
related_name="cooperative_share_product",
null=True
)
product = models.ForeignKey(
LiveStockProduct,
on_delete=models.CASCADE,
related_name="cooperative_share_product",
null=True
)
price = models.IntegerField(default=0)
shipping_price = models.IntegerField(default=0)
union_price = models.IntegerField(default=0)
cooperative_price = models.IntegerField(default=0)
company_price = models.IntegerField(default=0)
def save(self, *args, **kwargs):
super(CooperativeProductsShare, self).save(*args, **kwargs)
class LiveStockRolseProduct(BaseModel):
parent_product = models.ForeignKey(
LiveStockProduct,
on_delete=models.CASCADE,
related_name="parents_product",
null=True
)
jahad = models.ForeignKey(
LiveStockProvinceJahad,
on_delete=models.CASCADE,
related_name="jahad_product",
null=True
)
union = models.ForeignKey(
Union,
on_delete=models.CASCADE,
related_name="union_product",
null=True
)
cooperative = models.ForeignKey(
Cooperative,
on_delete=models.CASCADE,
related_name="cooperative_product",
null=True
)
# rancher = models.ForeignKey(
# Rancher,
# on_delete=models.CASCADE,
# related_name="rancher_product",
# null=True
# )
name = models.CharField(max_length=200, null=True)
total_weight = models.BigIntegerField(default=0)
total_receipt_weight = models.BigIntegerField(default=0)
total_allocated_weight = models.BigIntegerField(default=0)
total_remain_weight = models.BigIntegerField(default=0)
def save(self, *args, **kwargs):
self.total_remain_weight = self.total_weight - self.total_allocated_weight
super(LiveStockRolseProduct, self).save(*args, **kwargs)
class LiveStockAllocations(BaseModel):
product = models.ForeignKey(
LiveStockRolseProduct,
on_delete=models.CASCADE,
related_name="product_allocation",
null=True
)
jahad = models.ForeignKey(
LiveStockProvinceJahad,
on_delete=models.CASCADE,
related_name="jahad_allocation",
null=True
)
union = models.ForeignKey(
Union,
on_delete=models.CASCADE,
related_name="union_allocation",
null=True
)
cooperative = models.ForeignKey(
Cooperative,
on_delete=models.CASCADE,
related_name="cooperative_allocation",
null=True
)
state = models.CharField(max_length=200, default='pending')
weight = models.BigIntegerField(default=0)
real_weight = models.BigIntegerField(default=0)
date = models.DateTimeField(default=datetime.datetime.now)
allocate_from = models.CharField(max_length=200, null=True)
allocate_to = models.CharField(max_length=200, null=True)
place = models.TextField(null=True)
charge = models.BooleanField(default=False)
code = models.CharField(max_length=200, null=True)
description = models.TextField(null=True, blank=True)
def save(self, *args, **kwargs):
super(LiveStockAllocations, self).save(*args, **kwargs)
class Contractor(BaseModel):
user = models.ForeignKey(
SystemUserProfile,
on_delete=models.CASCADE,
related_name="contractor_user",
null=True
)
address = models.ForeignKey(
SystemAddress,
on_delete=models.CASCADE,
related_name="contractor_user",
null=True
)
cooperative = models.ForeignKey(
Cooperative,
on_delete=models.CASCADE,
related_name="contractor_cooperative",
null=True
)
contractor_code = models.CharField(max_length=100, null=True)
fullname = models.CharField(max_length=200, null=True)
entity_code = models.CharField(max_length=200, null=True)
national_id = models.CharField(max_length=100, null=True)
company_name = models.CharField(max_length=200, null=True)
number_of_rancher = models.IntegerField(default=0)
heavy_livestock = models.IntegerField(default=0)
light_livestock = models.IntegerField(default=0)
def save(self, *args, **kwargs):
super(Contractor, self).save(*args, **kwargs)
class PosSeller(BaseModel):
cooperative = models.ForeignKey(
Cooperative,
on_delete=models.CASCADE,
related_name="seller_pos_cooperative",
null=True
)
full_name=models.CharField(max_length=200,null=True)
mobile=models.CharField(max_length=50,null=True)
national_id=models.CharField(max_length=50,null=True)
city=models.CharField(max_length=100,null=True)
def save(self, *args, **kwargs):
super(PosSeller, self).save(*args, **kwargs)

View File

@@ -0,0 +1,31 @@
import requests
from django.http import HttpResponse
from LiveStock.models import Cooperative
from authentication.sahandsms.sms import USERNAME_SMS, PASSWORD_SMS, USERNAME_SMS_FINANCIAL, PASSWORD_SMS_FINANCIAL
from panel.helper import check_mobile_number
def send_sms_for_cooperative(request):
cooperative=Cooperative.objects.filter(trash=False)
for c in cooperative:
mobile=c.user.mobile
password=c.user.password
message = 'کاربر گرامی' \
f'\n' \
f'اطلاعات کاربری شما در سامانه به شرح زیر میباشد:' \
f'\n' \
f'\n' \
f'نام کاربری: {mobile}' \
f'\n' \
f'رمز عبور: {password}' \
f'\n' \
f'(سامانه رصدیار)' \
check_mobile = check_mobile_number(mobile)
if check_mobile:
u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username={}&password={}&from=30002501&to={}&message={}".format(
USERNAME_SMS, PASSWORD_SMS,
mobile, message)
return HttpResponse('pk')

3
LiveStock/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

10
LiveStock/urls.py Normal file
View File

@@ -0,0 +1,10 @@
from django.urls import path, include
urlpatterns = [
path('jahad/', include('LiveStock.Jahad.urls')),
path('union/', include('LiveStock.Union.urls')),
path('cooperative/', include('LiveStock.Cooperative.urls')),
path('rancher/', include('LiveStock.Rancher.urls')),
path('live-stock/', include('LiveStock.LiveStoksAndPoultry.urls')),
path('contractor/', include('LiveStock.Contractor.urls')),
]

3
LiveStock/views.py Normal file
View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.