first push

This commit is contained in:
2026-01-18 11:45:53 +03:30
commit 6bcd71d9ec
702 changed files with 272997 additions and 0 deletions

View File

View File

@@ -0,0 +1,592 @@
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

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,111 @@
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):
if not ranchers.has_script:
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)

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

@@ -0,0 +1,38 @@
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
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),
]

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)